@guren/server 2.20.0 → 2.22.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 (36) hide show
  1. package/dist/{Logger-DFifRAtc.js → Logger-DWXdtLSJ.js} +62 -2
  2. package/dist/agent/approval-status.d.ts +1 -1
  3. package/dist/agent/approval.d.ts +2 -2
  4. package/dist/agent/audit-emitter.d.ts +11 -1
  5. package/dist/agent/gate.d.ts +10 -8
  6. package/dist/agent/meta-tools.d.ts +13 -5
  7. package/dist/agent/pipeline.d.ts +10 -9
  8. package/dist/auth/index.js +1 -1
  9. package/dist/auth/password/DefaultHasher.d.ts +1 -0
  10. package/dist/{auth-BXcHQwHf.js → auth-CjE2oO50.js} +21 -2
  11. package/dist/cache/index.js +1 -1
  12. package/dist/{cache-DUhlolkJ.js → cache-DikxP7Bk.js} +2 -2
  13. package/dist/container/bindings.d.ts +4 -4
  14. package/dist/http/Application.d.ts +15 -0
  15. package/dist/http/middleware/index.d.ts +1 -1
  16. package/dist/http/middleware/session-manager.d.ts +7 -0
  17. package/dist/i18n/index.js +1 -1
  18. package/dist/index.d.ts +5 -3
  19. package/dist/index.js +628 -413
  20. package/dist/lambda/index.js +1 -1
  21. package/dist/logging/index.js +2 -2
  22. package/dist/{logging-DXmqqUl4.js → logging-Dmzdb6mL.js} +1 -1
  23. package/dist/mvc/Router.d.ts +18 -15
  24. package/dist/mvc/inertia/InertiaEngine.d.ts +6 -0
  25. package/dist/mvc/prototype.d.ts +105 -0
  26. package/dist/runtime/index.js +2 -2
  27. package/dist/storage/index.js +1 -1
  28. package/dist/support/keep-alive.d.ts +26 -0
  29. package/dist/support/request-deferrer.d.ts +10 -0
  30. package/dist/vite/index.js +147 -0
  31. package/dist/vite/plugin.d.ts +39 -0
  32. package/dist/{vite-manifest-BZQ-75hf.js → vite-manifest-D295_7-_.js} +1 -1
  33. package/package.json +5 -4
  34. package/dist/{DocsViewerServiceProvider-D2cuVgtN.js → DocsViewerServiceProvider-DWnlXx_y.js} +1 -1
  35. package/dist/{i18n-Cg1aajRP.js → i18n-BZ2VrSud.js} +1 -1
  36. package/dist/{storage-BB59f07j.js → storage-D_yNe54O.js} +1 -1
@@ -1,3 +1,59 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ //#region src/support/request-deferrer.ts
3
+ /**
4
+ * The `waitUntil` of the Workers request being served, for code that holds no
5
+ * request: a container-singleton `Logger` resolved inside a service, say. Only a
6
+ * fetch handler abandons unfinished work when its context closes (a Durable
7
+ * Object keeps it), so `Application.fetch` is the one place that enters a scope.
8
+ */
9
+ const scope = new AsyncLocalStorage();
10
+ /**
11
+ * `ctx` is typed `unknown` because `app.fetch`'s third argument is a cast
12
+ * wherever it arrives from. One without a callable `waitUntil` (every runtime
13
+ * but Workers) enters no scope, so a nested call keeps the outer request's.
14
+ */
15
+ function runInRequestScope(ctx, fn) {
16
+ const waitUntil = ctx?.waitUntil;
17
+ return typeof waitUntil === "function" ? scope.run(waitUntil.bind(ctx), fn) : fn();
18
+ }
19
+ /** The deferrer of the request this code runs for, when one was entered. */
20
+ function requestDeferrer() {
21
+ return scope.getStore();
22
+ }
23
+ //#endregion
24
+ //#region src/support/keep-alive.ts
25
+ /**
26
+ * How a best-effort side channel (an audit sink, an approval notification, an
27
+ * async log channel) is invoked so that it can neither fail the call it was
28
+ * only recording nor be lost by the runtime. Three orderings have to hold
29
+ * together, and each is wrong in a way tests off Workers cannot see: a
30
+ * synchronous throw and a rejection both reach `onFailure`; the `.catch` is
31
+ * attached *before* deferring, since `waitUntil` on a rejecting promise raises
32
+ * an unhandled rejection in workerd; and `defer` itself throws there once the
33
+ * response has settled.
34
+ */
35
+ /**
36
+ * `defer` defaults to the deferrer of the Workers request being served, where
37
+ * an undeferred channel is abandoned with the request context; `waitUntil`
38
+ * keeps it alive past the response. Outside a request, and on every other
39
+ * runtime, there is none and the channel is fire-and-forget.
40
+ */
41
+ function keepAlive(channel, defer = requestDeferrer()) {
42
+ let settled;
43
+ try {
44
+ settled = Promise.resolve(channel.run()).catch(channel.onFailure);
45
+ } catch (error) {
46
+ channel.onFailure(error);
47
+ return;
48
+ }
49
+ if (!defer) return;
50
+ try {
51
+ defer(settled);
52
+ } catch (error) {
53
+ console.warn(`[guren] ${channel.label} could not be deferred: ${String(error)}`);
54
+ }
55
+ }
56
+ //#endregion
1
57
  //#region src/logging/Logger.ts
2
58
  const DEFAULT_FILTER_KEYS = [
3
59
  "password",
@@ -89,7 +145,11 @@ var Logger = class Logger {
89
145
  };
90
146
  for (const channel of this.channels) try {
91
147
  const pending = channel.log(entry);
92
- if (isPromiseLike(pending)) Promise.resolve(pending).catch(reportLoggingError);
148
+ if (isPromiseLike(pending)) keepAlive({
149
+ run: () => pending,
150
+ onFailure: reportLoggingError,
151
+ label: "a log entry"
152
+ });
93
153
  } catch (error) {
94
154
  reportLoggingError(error);
95
155
  }
@@ -111,4 +171,4 @@ var Logger = class Logger {
111
171
  }
112
172
  };
113
173
  //#endregion
114
- export { filterSensitiveData as n, isPromiseLike as r, Logger as t };
174
+ export { runInRequestScope as a, keepAlive as i, filterSensitiveData as n, isPromiseLike as r, Logger as t };
@@ -4,7 +4,7 @@
4
4
  * clock, no protocol.
5
5
  *
6
6
  * Here rather than in an adapter because two surfaces answer this question —
7
- * `guren.approval_status` over MCP and a durable agent's own status check
7
+ * `guren_approval_status` over MCP and a durable agent's own status check
8
8
  * (RFC 0017 §5) — and a record one of them calls "approved" must not be one
9
9
  * the other hides.
10
10
  */
@@ -86,7 +86,7 @@ export interface AgentApprovalStore {
86
86
  /** Persist a new pending request. */
87
87
  create(request: AgentApprovalRequest): Promise<void>;
88
88
  /**
89
- * The request with this id, or `null`. Backs `guren.approval_status`. Takes
89
+ * The request with this id, or `null`. Backs `guren_approval_status`. Takes
90
90
  * no principal: the caller-scoping rule is applied by the framework (see
91
91
  * {@link agentApprovalVisibleTo}), because a store that forgot to filter
92
92
  * would leak other principals' pending actions and nothing would fail.
@@ -176,7 +176,7 @@ export declare function agentApprovalStatusAt(request: AgentApprovalRequest, now
176
176
  export declare function agentApprovalUsableAt(request: AgentApprovalRequest, now: Date): boolean;
177
177
  /**
178
178
  * Whether `principal` may be told anything at all about `request` — the scope
179
- * rule of `guren.approval_status` (RFC 0016 §5.4): a caller reads only the
179
+ * rule of `guren_approval_status` (RFC 0016 §5.4): a caller reads only the
180
180
  * status of a request it created, or an agent could walk ids and enumerate
181
181
  * other principals' pending actions. A `false` here must be answered *exactly*
182
182
  * as an unknown id is: any difference in message, shape or timing reintroduces it.
@@ -11,6 +11,7 @@
11
11
  import type { AgentToolDenied, AgentToolInvoked } from './events.js';
12
12
  import type { EventManager } from '../events/index.js';
13
13
  import { type AgentAuditRecord } from './audit.js';
14
+ import { type Deferrer } from '../support/keep-alive.js';
14
15
  /**
15
16
  * The container service an application's audit emitter is published under
16
17
  * (`ServiceBindings['agent.audit']`). A constant because `@guren/plugin-mcp`
@@ -26,6 +27,15 @@ export type AgentAuditSink = (record: AgentAuditRecord) => void | Promise<void>;
26
27
  * because it is a container binding (`'agent.audit'`) as well as a return value.
27
28
  */
28
29
  export type AgentAuditEmitter = (event: AgentToolInvoked | AgentToolDenied) => void;
30
+ /** Options an emitter is built with, beyond its sink and its events. */
31
+ export interface AuditEmitterOptions {
32
+ /**
33
+ * Where an unfinished write goes so the runtime keeps it alive past the
34
+ * response: `ExecutionContext.waitUntil` on Workers, where an undeferred one
35
+ * is abandoned with the request context, silently. See {@link keepAlive}.
36
+ */
37
+ defer?: Deferrer;
38
+ }
29
39
  /**
30
40
  * **The sink is called directly, not subscribed as a listener**:
31
41
  * `EventManager.emit` awaits listeners in a bare `for` loop, so one unrelated
@@ -33,4 +43,4 @@ export type AgentAuditEmitter = (event: AgentToolInvoked | AgentToolDenied) => v
33
43
  * emitted for genuine listeners (RFC 0016 §5.2). Neither half may fail the call
34
44
  * it records: both are caught, the sink's failure warned rather than swallowed.
35
45
  */
36
- export declare function createAuditEmitter(sink: AgentAuditSink | undefined, events: EventManager | undefined, now?: () => Date): AgentAuditEmitter;
46
+ export declare function createAuditEmitter(sink: AgentAuditSink | undefined, events: EventManager | undefined, now?: () => Date, options?: AuditEmitterOptions): AgentAuditEmitter;
@@ -11,6 +11,7 @@
11
11
  import { type AgentApprovalRequest, type AgentApprovalStore } from './approval.js';
12
12
  import type { DerivedAgentTool } from './derive.js';
13
13
  import type { AgentPrincipal, AgentToolDenialReason } from './events.js';
14
+ import { type Deferrer } from '../support/keep-alive.js';
14
15
  export type GateVerdict = {
15
16
  allowed: true;
16
17
  } | {
@@ -75,18 +76,19 @@ export interface ApprovalGateContext {
75
76
  /**
76
77
  * Called once, only for a record this call created, and **never awaited**: a
77
78
  * channel that is down must not fail the call or lose the persisted record.
78
- * Implementations report their own failures; see {@link notifyApprovers}.
79
+ * Implementations report their own failures and keep a slow channel alive
80
+ * past the response where the runtime needs telling; see {@link notifyApprovers}.
79
81
  */
80
82
  notify(request: AgentApprovalRequest): void;
81
83
  }
82
84
  /**
83
- * Wrap the application's `notify` so a failure can neither fail the tool call nor
84
- * lose the record: it is already persisted when this runs, so a dead channel costs
85
- * an approver an email, not a request. The failure is warned about with the request
86
- * id, which is what finds the record sitting there unannounced. Both shapes are
87
- * caught — a synchronous throw and a rejected promise.
85
+ * A failure may neither fail the tool call nor lose the record: it is persisted
86
+ * before this runs, so a dead channel costs an approver an email. The warning
87
+ * carries the request id, which is what finds the record sitting there
88
+ * unannounced. Everything else about invoking a best-effort channel — which
89
+ * failures are caught, and when `defer` runs — is {@link keepAlive}'s.
88
90
  */
89
- export declare function notifyApprovers(notify: (request: AgentApprovalRequest) => void | Promise<void>): (request: AgentApprovalRequest) => void;
91
+ export declare function notifyApprovers(notify: (request: AgentApprovalRequest) => void | Promise<void>, defer?: Deferrer): (request: AgentApprovalRequest) => void;
90
92
  /**
91
93
  * Scope and approval, in that order — a caller learns a tool needs approval only
92
94
  * once its token could invoke it, so an unauthorized probe cannot map which
@@ -104,7 +106,7 @@ export declare function gateToolCall(tool: DerivedAgentTool, abilities: readonly
104
106
  */
105
107
  export declare function gateApproval(tool: DerivedAgentTool, args: Record<string, unknown>, context: ApprovalGateContext): Promise<GateVerdict>;
106
108
  /**
107
- * The scope half alone — what `guren.preflight` checks before rehearsing a call
109
+ * The scope half alone — what `guren_preflight` checks before rehearsing a call
108
110
  * (RFC 0016 §5.4). Checking requires the *same* scope as calling, or the
109
111
  * companion becomes a probe of tools the token cannot call. Approval is not
110
112
  * applied: a rehearsal executes nothing, and approval gates an ability rather
@@ -1,13 +1,21 @@
1
1
  /**
2
2
  * The names a protocol adapter may add to an application's tool catalogue on
3
3
  * its own, and which an application route therefore may not claim (RFC 0016
4
- * §5.4). One rule, two readers: `@guren/plugin-mcp` adds `guren.preflight` to
4
+ * §5.4). One rule, two readers: `@guren/plugin-mcp` adds `guren_preflight` to
5
5
  * the catalogue it serves, `guren check` fails a route whose tool name
6
6
  * collides; the CLI cannot import the plugin, hence beside the derivation. A
7
7
  * `tools/list` carrying two tools with one name is rejected wholesale by an MCP
8
- * client, so a collision costs the *entire* catalogue. The `guren.` prefix is
8
+ * client, so a collision costs the *entire* catalogue. The `guren_` prefix is
9
9
  * not reserved wholesale: that would fail routes over collisions that do not exist.
10
10
  */
11
+ /**
12
+ * The grammar every known client accepts: a strict subset of MCP's own
13
+ * (`AGENT_TOOL_NAME_PATTERN`, which admits `.` and 128 characters). The Claude and
14
+ * OpenAI tool APIs enforce it; Claude Managed Agents silently skips an MCP tool
15
+ * outside it (#787). Meta-tools have no `toolName` escape hatch, so the names
16
+ * below must match; `guren check` warns on a route name that does not.
17
+ */
18
+ export declare const PORTABLE_AGENT_TOOL_NAME_PATTERN: RegExp;
11
19
  /**
12
20
  * The preflight companion tool (RFC 0016 §5.4). Preflight cannot be an
13
21
  * *argument* of the tool being checked: a tool advertising an `outputSchema`
@@ -15,7 +23,7 @@
15
23
  * error, and a verdict conforms to no route's output. One meta-tool for the
16
24
  * whole catalogue, not one companion per tool (§5.5).
17
25
  */
18
- export declare const PREFLIGHT_TOOL_NAME = "guren.preflight";
26
+ export declare const PREFLIGHT_TOOL_NAME = "guren_preflight";
19
27
  /**
20
28
  * The approval-status companion tool (RFC 0016 §5.4 item 4). A caller handed a
21
29
  * request id needs something that can say what became of it, and the gated tool
@@ -23,12 +31,12 @@ export declare const PREFLIGHT_TOOL_NAME = "guren.preflight";
23
31
  * mode of the first, so neither output schema is the union of two unrelated
24
32
  * shapes.
25
33
  */
26
- export declare const APPROVAL_STATUS_TOOL_NAME = "guren.approval_status";
34
+ export declare const APPROVAL_STATUS_TOOL_NAME = "guren_approval_status";
27
35
  /** Every meta-tool name an adapter may occupy. */
28
36
  export declare const RESERVED_AGENT_TOOL_NAMES: readonly string[];
29
37
  /**
30
38
  * Whether a tool name belongs to the framework rather than the application.
31
- * Case-sensitive: MCP tool names are matched literally, so `Guren.Preflight` is
39
+ * Case-sensitive: MCP tool names are matched literally, so `Guren_Preflight` is
32
40
  * a different tool and reserving it would take a name away for nothing.
33
41
  */
34
42
  export declare function isReservedAgentToolName(name: string): boolean;
@@ -15,10 +15,11 @@ import type { DerivedAgentTool } from './derive.js';
15
15
  import { type ToolCallOutcome } from './dispatch.js';
16
16
  import { type AgentPrincipal, type AgentSurface, type AgentToolDenialReason } from './events.js';
17
17
  import { type ApprovalGateContext } from './gate.js';
18
+ import type { Deferrer } from '../support/keep-alive.js';
18
19
  /**
19
20
  * What the audit hooks need from a tool: its name, and the redaction rules its
20
21
  * arguments are recorded under. Narrower than {@link DerivedAgentTool} because
21
- * one audited call has no route behind it: a `guren.preflight` invocation is
22
+ * one audited call has no route behind it: a `guren_preflight` invocation is
22
23
  * recorded under the meta-tool's name with the *checked* tool's `redact` list,
23
24
  * the meta-tool's own being empty.
24
25
  */
@@ -72,7 +73,7 @@ export type AgentInvocationResult =
72
73
  export interface InterposedAgentCall {
73
74
  tool: DerivedAgentTool;
74
75
  args: Record<string, unknown>;
75
- /** True for a rehearsal (`guren.preflight`), which executes nothing. */
76
+ /** True for a rehearsal (`guren_preflight`), which executes nothing. */
76
77
  preflight: boolean;
77
78
  }
78
79
  /**
@@ -162,17 +163,17 @@ export interface AgentInvocationOptions {
162
163
  executionCtx?: ExecutionContext;
163
164
  }
164
165
  /**
165
- * Build {@link AgentInvocationOptions.approvals} for one caller.
166
- *
167
- * The TTL default, the redaction rules and the `notify` wrapping are invariants
168
- * of an approval record rather than of a protocol. Per caller, because an
169
- * approval binds to the principal that asked; `undefined` means no queue.
166
+ * Build {@link AgentInvocationOptions.approvals} for one caller — an approval binds
167
+ * to the principal that asked; `undefined` means no queue. The TTL default, the
168
+ * redaction rules and the `notify` wrapping are invariants of an approval record
169
+ * rather than of a protocol, which is why `defer` arrives here: a `notify` the
170
+ * pipeline received already wrapped cannot be given a deferrer afterwards.
170
171
  */
171
172
  export declare function createAgentApprovalContext(config: {
172
173
  store: AgentApprovalStore;
173
174
  notify: (request: AgentApprovalRequest) => void | Promise<void>;
174
175
  ttlMs?: number;
175
- } | undefined, principal: AgentPrincipal | null): NonNullable<AgentInvocationOptions['approvals']> | undefined;
176
+ } | undefined, principal: AgentPrincipal | null, defer?: Deferrer): NonNullable<AgentInvocationOptions['approvals']> | undefined;
176
177
  /** What {@link createAgentAuditRecorder} needs, settled once per caller. */
177
178
  export interface AgentAuditRecorderOptions {
178
179
  audit?: AgentAuditEmitter;
@@ -207,7 +208,7 @@ export interface AgentInvocation {
207
208
  preflight?: boolean;
208
209
  /**
209
210
  * The identity the record is written under, when it is not the dispatched
210
- * tool's own — see {@link AuditedTool}. `guren.preflight` is the one caller:
211
+ * tool's own — see {@link AuditedTool}. `guren_preflight` is the one caller:
211
212
  * the meta-tool's name, the checked tool's redaction rules.
212
213
  */
213
214
  audited?: AuditedTool;
@@ -1,2 +1,2 @@
1
- import { $ as buildTokenUrl, 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, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureStringCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, et as generateId, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as secureCompare, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as hashToken, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, q as revokeApiToken, r as completeEmailVerification, rt as parseTokenUrl, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-BXcHQwHf.js";
1
+ import { $ as buildTokenUrl, 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, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureStringCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, et as generateId, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as secureCompare, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as hashToken, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, q as revokeApiToken, r as completeEmailVerification, rt as parseTokenUrl, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-CjE2oO50.js";
2
2
  export { API_TOKEN_KEY, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, ScryptHasher, SessionGuard, TokenGuard, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildTokenUrl, buildVerificationUrl, completeEmailVerification, completePasswordReset, createApiToken, createBearerTokenMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createOAuthManager, createOAuthState, createPasswordResetToken, exchangeOAuthCode, fetchOAuthUserProfile, generateId, generateToken, getApiToken, getApiTokenOrFail, getUserApiTokens, hashToken, isEmailVerified, parseApiToken, parseOAuthRedirectUrl, parsePasswordResetUrl, parseTokenUrl, parseVerificationUrl, readBearerToken, requireVerifiedEmail, revokeAllApiTokens, revokeApiToken, sanitizeOAuthRedirect, secureCompare, secureStringCompare, tokenCan, tokenCanAll, tokenCanAny, verifyApiToken, verifyEmailToken, verifyOAuthState, verifyPasswordResetToken };
@@ -9,6 +9,7 @@ import type { PasswordHasher } from './PasswordHasher.js';
9
9
  export declare class DefaultHasher implements PasswordHasher {
10
10
  private readonly bun;
11
11
  private readonly node;
12
+ private readonly testing;
12
13
  constructor();
13
14
  hash(plain: string): Promise<string>;
14
15
  verify(hashed: string, plain: string): Promise<boolean>;
@@ -637,6 +637,21 @@ var NodeHasher = class {
637
637
  //#endregion
638
638
  //#region src/auth/password/DefaultHasher.ts
639
639
  /**
640
+ * Parameters used while `GUREN_TESTING` is set (by `TestApp` and `guren tool:call --as`).
641
+ * The production defaults cost ~136 ms per hash (Bun 1.3, Apple M-series), the whole
642
+ * 180 ms of every test creating a user; these measure ~1 ms. Verification reads the
643
+ * parameters the hash carries, so a hash written here verifies at that cost anywhere.
644
+ */
645
+ const TESTING_ARGON2_OPTIONS = {
646
+ memoryCost: 1024,
647
+ timeCost: 1
648
+ };
649
+ const TESTING_SCRYPT_COST = 1024;
650
+ /** Read per call, not at construction: the provider owning this hasher is built at boot, and `TestApp` may set the variable later. */
651
+ function testingHashCost() {
652
+ return typeof process !== "undefined" && Boolean(process.env.GUREN_TESTING);
653
+ }
654
+ /**
640
655
  * Runtime-detecting password hasher behind `Hash`, the default for
641
656
  * `AuthenticatableModel` and `ModelUserProvider`: `Bun.password` on Bun (Argon2id,
642
657
  * despite `ScryptHasher`'s name), `crypto.scrypt` otherwise. **Verification routes
@@ -646,18 +661,22 @@ var NodeHasher = class {
646
661
  var DefaultHasher = class {
647
662
  bun;
648
663
  node;
664
+ testing;
649
665
  constructor() {
650
- this.bun = typeof Bun !== "undefined" ? new ScryptHasher() : null;
666
+ const onBun = typeof Bun !== "undefined";
667
+ this.bun = onBun ? new ScryptHasher() : null;
651
668
  this.node = new NodeHasher();
669
+ this.testing = onBun ? new ScryptHasher(TESTING_ARGON2_OPTIONS) : new NodeHasher({ cost: TESTING_SCRYPT_COST });
652
670
  }
653
671
  hash(plain) {
654
- return (this.bun ?? this.node).hash(plain);
672
+ return (testingHashCost() ? this.testing : this.bun ?? this.node).hash(plain);
655
673
  }
656
674
  verify(hashed, plain) {
657
675
  return this.delegateFor(hashed).verify(hashed, plain);
658
676
  }
659
677
  needsRehash(hashed) {
660
678
  if (hashed.startsWith("$scrypt$") !== (this.bun === null)) return true;
679
+ if (!this.testing.needsRehash(hashed)) return !testingHashCost();
661
680
  return this.delegateFor(hashed).needsRehash(hashed);
662
681
  }
663
682
  delegateFor(hashed) {
@@ -1,2 +1,2 @@
1
- import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-DUhlolkJ.js";
1
+ import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-DikxP7Bk.js";
2
2
  export { CacheManager, FileStore, MemoryStore, RedisStore, TaggedCache, createCacheManager };
@@ -1,8 +1,8 @@
1
- import { r as isPromiseLike } from "./Logger-DFifRAtc.js";
1
+ import { r as isPromiseLike } from "./Logger-DWXdtLSJ.js";
2
2
  import { n as isHotReloadRuntime, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
3
3
  import { createHash } from "node:crypto";
4
- import { mkdir, readFile, readdir, rm, unlink, writeFile } from "node:fs/promises";
5
4
  import { dirname, join } from "node:path";
5
+ import { mkdir, readFile, readdir, rm, unlink, writeFile } from "node:fs/promises";
6
6
  import { existsSync } from "node:fs";
7
7
  //#region src/redis/lazy-client.ts
8
8
  /**
@@ -46,10 +46,10 @@ export interface ServiceBindings {
46
46
  'inertia.sharedProps': SharedInertiaPropsRegistry;
47
47
  /**
48
48
  * How an agent surface records what it did (RFC 0016 §5.2). Bound by
49
- * `@guren/plugin-mcp` at boot, absent when no MCP plugin is registered. The
50
- * binding is the *emitter*, not the sink, so every surface's records reach
51
- * the same place the same way. The runtime spelling of this name lives in
52
- * `AGENT_AUDIT_BINDING` — rename here and there together.
49
+ * `@guren/plugin-mcp` at boot, absent without it; the *emitter*, not the sink,
50
+ * so every surface's records reach one place. It defers nothing: on Workers a
51
+ * sink it starts inside a request is abandoned with that context. The runtime
52
+ * spelling lives in `AGENT_AUDIT_BINDING` — rename here and there together.
53
53
  */
54
54
  'agent.audit': AgentAuditEmitter;
55
55
  'exception.handler': ExceptionHandler;
@@ -1,6 +1,7 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { MiddlewareHandler, ExecutionContext } from 'hono';
3
3
  import { Router } from '../mvc/Router.js';
4
+ import { type PrototypeFixtureLoader } from '../mvc/prototype.js';
4
5
  import { Container, type GurenModule } from '../container/index.js';
5
6
  import { type ServiceProviderConstructor } from '../container/ServiceProvider.js';
6
7
  import { AuthManager } from '../auth/AuthManager.js';
@@ -67,6 +68,12 @@ export interface ApplicationOptions {
67
68
  readonly securityHeaders?: SecurityHeadersOptions | false;
68
69
  /** DNS rebinding protection. Off unless configured; the template configures it. */
69
70
  readonly hostAuthorization?: HostAuthorizationOptions | false;
71
+ /**
72
+ * The fixture module routes registered with the `prototype` handler answer
73
+ * from (RFC 0021): `() => import('../resources/js/prototype/index.js')`.
74
+ * Loaded at boot only when such a route exists.
75
+ */
76
+ readonly prototype?: PrototypeFixtureLoader;
70
77
  }
71
78
  export interface I18nPluginOptions {
72
79
  /** Detection only resolves to one of these; all are preloaded during `boot()`. */
@@ -164,6 +171,14 @@ export declare class Application {
164
171
  /** Matched by exact path — see {@link declareCookielessAuthPath}. */
165
172
  getCookielessAuthPaths(): ReadonlySet<string>;
166
173
  mountRoutes(): Promise<void>;
174
+ /**
175
+ * Every failure here is one a request would otherwise surface as a 500:
176
+ * an unnamed prototype route cannot be looked up, a named one the fixture
177
+ * does not answer, no loader to answer from at all. Process-shared fixture
178
+ * state is a developer's own `bun run dev`, not a deployment, hence the
179
+ * production refusal; `GUREN_PROTOTYPE_ROUTES=1` overrides it deliberately.
180
+ */
181
+ private preparePrototypeRoutes;
167
182
  use(path: string, ...middleware: MiddlewareHandler[]): void;
168
183
  /**
169
184
  * Registers providers, runs the boot callback, mounts routes, boots providers.
@@ -3,7 +3,7 @@ export type Middleware = MiddlewareHandler;
3
3
  export declare function defineMiddleware(handler: MiddlewareHandler): MiddlewareHandler;
4
4
  export declare function jsonResponse(data: unknown, status?: number): Response;
5
5
  export { createSessionMiddleware, MemorySessionStore, getSessionFromContext } from './session.js';
6
- export { DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, SessionManager } from './session-manager.js';
6
+ export { BUILT_IN_SESSION_DRIVERS, DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, SessionManager } from './session-manager.js';
7
7
  export { CookieSessionStore } from './cookie-session-store.js';
8
8
  export type { CookieSessionStoreOptions } from './cookie-session-store.js';
9
9
  export type { CookieSessionDriverOptions, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, MemorySessionDriverOptions, RedisSessionDriverOptions, } from './session-manager.js';
@@ -41,6 +41,13 @@ export type SessionStoreConfig = {
41
41
  /** The store `SessionConfig.default` names when it names none, and the one driver that shares no state between requests. */
42
42
  export declare const DEFAULT_SESSION_STORE_NAME = "memory";
43
43
  export declare const PER_PROCESS_SESSION_DRIVERS: ReadonlySet<string>;
44
+ /**
45
+ * Every driver the framework itself registers, and whether it survives a
46
+ * runtime that shares no memory between requests. Read by static checks that
47
+ * cannot boot the app; a plugin's driver is declared in its `gurenPlugin`
48
+ * manifest instead, and a name in neither is unverifiable, not absent.
49
+ */
50
+ export declare const BUILT_IN_SESSION_DRIVERS: ReadonlyMap<string, boolean>;
44
51
  /** Cookie and TTL settings plus the named stores one of which is the default. */
45
52
  export interface SessionConfig extends SessionCookieOptions {
46
53
  /** @default 'memory' */
@@ -1,2 +1,2 @@
1
- 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";
1
+ 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-BZ2VrSud.js";
2
2
  export { I18nManager, JsonLoader, MemoryLoader, Translator, createI18n, getI18n, getPluralizationRule, pluralizationRules, selectPluralForm, setI18n, t, tc, tryGetI18n };
package/dist/index.d.ts CHANGED
@@ -10,12 +10,14 @@ export type { ContentfulStatusCode } from 'hono/utils/http-status';
10
10
  export { viteAsset } from './http/vite-assets.js';
11
11
  export type { ViteAssetOptions } from './http/vite-assets.js';
12
12
  export { Router } from './mvc/Router.js';
13
+ export { prototype } from './mvc/prototype.js';
14
+ export type { PrototypeFixture, PrototypeFixtureLoader, PrototypeResult, PrototypeRouteHandler, PrototypeServerContext, } from './mvc/prototype.js';
13
15
  export type { BindableModel, AgentRouteMetadata, RouteBuilder, RouteContractOptions, RouteDefinition, RouteMiddlewareInput, RouteModelBinding, RouteOpenApiMetadata, ResourceAction as RouteResourceAction, ResourceResponseHint, ResourceResponseShape, ResourceRouteOptions, } from './mvc/Router.js';
14
16
  export { deriveAgentTools } from './agent/derive.js';
15
17
  export type { AgentToolInputSource, AgentToolSchema, DeriveAgentToolsResult, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, } from './agent/derive.js';
16
18
  export { advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse, PREFLIGHT_ARGUMENT, } from './agent/dispatch.js';
17
19
  export type { BuildToolRequestOptions, BuiltToolRequest, ToolCallOutcome, ToolRequestBuildFailure, } from './agent/dispatch.js';
18
- export { APPROVAL_STATUS_TOOL_NAME, isReservedAgentToolName, PREFLIGHT_TOOL_NAME, RESERVED_AGENT_TOOL_NAMES, } from './agent/meta-tools.js';
20
+ export { APPROVAL_STATUS_TOOL_NAME, isReservedAgentToolName, PORTABLE_AGENT_TOOL_NAME_PATTERN, PREFLIGHT_TOOL_NAME, RESERVED_AGENT_TOOL_NAMES, } from './agent/meta-tools.js';
19
21
  export { AGENT_TOOL_NAME_PATTERN, classifyRegistrationScope, expandToolScopes, parseToolScope, scopesAllowTool, } from './agent/scopes.js';
20
22
  export type { ParsedToolScope, RegistrationScopeVerdict, ScopedTool } from './agent/scopes.js';
21
23
  export { AgentToolDenied, AgentToolInvoked } from './agent/events.js';
@@ -24,7 +26,7 @@ export { AGENT_REDACTED, redactAgentArguments } from './agent/redact.js';
24
26
  export { DEFAULT_AGENT_AUDIT_PATH, parseAuditRecord, toAuditRecord } from './agent/audit.js';
25
27
  export type { AgentAuditDeniedRecord, AgentAuditInvokedRecord, AgentAuditRecord, } from './agent/audit.js';
26
28
  export { AGENT_AUDIT_BINDING, createAuditEmitter } from './agent/audit-emitter.js';
27
- export type { AgentAuditEmitter, AgentAuditSink } from './agent/audit-emitter.js';
29
+ export type { AgentAuditEmitter, AgentAuditSink, AuditEmitterOptions } from './agent/audit-emitter.js';
28
30
  export { AGENT_APPROVAL_CONFIG_KEY, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, buildAgentApprovalRequest, canonicalizeAgentApprovalInput, DEFAULT_AGENT_APPROVAL_TTL_MS, } from './agent/approval.js';
29
31
  export type { AgentApprovalMatch, AgentApprovalRequest, AgentApprovalRequestInput, AgentApprovalStatus, AgentApprovalStore, } from './agent/approval.js';
30
32
  export { AgentApprovalRequested } from './agent/AgentApprovalRequested.js';
@@ -43,7 +45,7 @@ export { InertiaServiceProvider, AuthServiceProvider, OAuthServiceProvider, Even
43
45
  export { FormRequest } from './http/FormRequest.js';
44
46
  export { AuthManager, SessionGuard, TokenGuard, ModelUserProvider, BaseUserProvider, AuthenticatableModel, ScryptHasher, createPasswordResetToken, verifyPasswordResetToken, completePasswordReset, buildPasswordResetUrl, parsePasswordResetUrl, MemoryPasswordResetStore, createEmailVerificationToken, verifyEmailToken, completeEmailVerification, buildVerificationUrl, parseVerificationUrl, isEmailVerified, requireVerifiedEmail, MemoryEmailVerificationStore, createApiToken, parseApiToken, readBearerToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, OAuthManager, MemoryOAuthStateStore, createOAuthManager, createOAuthState, verifyOAuthState, sanitizeOAuthRedirect, OAUTH_SESSION_BINDING_KEY, buildOAuthAuthorizeUrl, exchangeOAuthCode, fetchOAuthUserProfile, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createDiscordOAuthProviderConfig, buildOAuthRedirectUrl, parseOAuthRedirectUrl, } from './auth/index.js';
45
47
  export type { AuthContext as AuthRuntimeContext, AuthCredentials, AuthManagerOptions, Authenticatable, Guard, GuardContext, GuardFactory, UserProvider, ProviderFactory, DefaultSanitizedKeys, Sanitized, PasswordResetConfig, PasswordResetTokenStore, PasswordResetTokenResult, EmailVerificationConfig, EmailVerificationTokenStore, EmailVerificationToken, EmailVerificationTokenResult, ApiToken, ApiTokenGuardOptions, ApiTokenStore, CreateApiTokenOptions, CreateApiTokenResult, BearerTokenMiddlewareOptions, VerifiedApiToken, TokenGuardOptions, OAuthProviderConfig, OAuthTokenResult, OAuthUserProfile, OAuthFallbackEmail, OAuthStatePayload, OAuthStateStore, OAuthStateConfig, OAuthAuthorizeOptions, OAuthCallbackPayload, OAuthManagerOptions, OAuthProviderFactoryInput, OAuthBindingSession, } from './auth/index.js';
46
- export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, SessionManager, CookieSessionStore, DEFAULT_SESSION_STORE_NAME, PER_PROCESS_SESSION_DRIVERS, getSessionFromContext, requireAuthenticated, requireGuest, attachAuthContext, createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, createSecurityHeaders, createCspMiddleware, getCspNonce, CSP_NONCE_KEY, createHostAuthorizationMiddleware, createCorsMiddleware, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
48
+ export { defineMiddleware, jsonResponse, createSessionMiddleware, MemorySessionStore, SessionManager, CookieSessionStore, DEFAULT_SESSION_STORE_NAME, BUILT_IN_SESSION_DRIVERS, PER_PROCESS_SESSION_DRIVERS, getSessionFromContext, requireAuthenticated, requireGuest, attachAuthContext, createCsrfMiddleware, getCsrfToken, csrfField, verifyCsrfToken, CSRF_TOKEN_KEY, CSRF_HEADER_NAME, CSRF_FORM_FIELD, validateRequest, validateRequestWith, getValidatedData, validate, validateSafe, VALIDATED_DATA_KEY, createRateLimitMiddleware, getRateLimitInfo, resetRateLimit, MemoryRateLimitStore, SlidingWindowRateLimitStore, createSecurityHeaders, createCspMiddleware, getCspNonce, CSP_NONCE_KEY, createHostAuthorizationMiddleware, createCorsMiddleware, createRedirectSafetyMiddleware, isSafeRedirectUrl, createForceHttpsMiddleware, requestIdMiddleware, requestLoggingMiddleware, detectLocaleMiddleware, LOCALE_CONTEXT_KEY, getRequestLocale, getRequestTranslator, } from './http/middleware/index.js';
47
49
  export { AUTH_CONTEXT_KEY } from './http/middleware/auth.js';
48
50
  export type { Middleware, Session, SessionData, SessionStore, SessionConfig, SessionDrivers, SessionStoreConfig, SessionDriverFactory, SessionCookieOptions, SessionInlineCodec, CookieSessionStoreOptions, CookieSessionDriverOptions, MemorySessionDriverOptions, RedisSessionDriverOptions, AuthContext, RequireAuthOptions, CsrfOptions, CookielessAuthEndpoints, ValidationSchema, ValidateRequestOptions, RateLimitOptions, RateLimitStore, RateLimitEntry, RateLimitInfo, SecurityHeadersOptions, HstsOptions, CspOptions, CspDirectives, HostAuthorizationOptions, CorsOptions, RedirectSafetyOptions, ForceHttpsOptions, DetectLocaleOptions, DetectLocaleVariables, TranslatorBinding, LocaleSource, } from './http/middleware/index.js';
49
51
  export { Validator, FieldValidator, createValidator, quickValidate, quickValidateOrThrow, required, nullable, requiredIf, requiredUnless, requiredWith, requiredWithout, string as stringRule, numeric, integer, boolean as booleanRule, array as arrayRule, object as objectRule, email as emailRule, url as urlRule, uuid as uuidRule, ip, ipv4, ipv6, json as jsonRule, alpha, alphaNum, alphaDash, regex, min, max, between, size, inValues, notIn, confirmed, same, different, date as dateRule, dateFormat, after, afterOrEqual, before, beforeOrEqual, startsWith, endsWith, file as fileRule, image as imageRule, mimes, maxFileSize, minFileSize, custom, unique, exists, } from './http/validation/index.js';