@guren/server 2.21.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.
@@ -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 { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, t as CacheManager } from "../cache-thXRnaju.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,4 +1,4 @@
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
4
  import { dirname, join } from "node:path";
@@ -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;
package/dist/index.d.ts CHANGED
@@ -17,7 +17,7 @@ export { deriveAgentTools } from './agent/derive.js';
17
17
  export type { AgentToolInputSource, AgentToolSchema, DeriveAgentToolsResult, DerivedAgentTool, DerivedAgentToolAnnotations, DerivedAgentToolExposure, } from './agent/derive.js';
18
18
  export { advertisesStructuredOutput, buildToolRequest, describeBuildFailure, mapToolResponse, PREFLIGHT_ARGUMENT, } from './agent/dispatch.js';
19
19
  export type { BuildToolRequestOptions, BuiltToolRequest, ToolCallOutcome, ToolRequestBuildFailure, } from './agent/dispatch.js';
20
- 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';
21
21
  export { AGENT_TOOL_NAME_PATTERN, classifyRegistrationScope, expandToolScopes, parseToolScope, scopesAllowTool, } from './agent/scopes.js';
22
22
  export type { ParsedToolScope, RegistrationScopeVerdict, ScopedTool } from './agent/scopes.js';
23
23
  export { AgentToolDenied, AgentToolInvoked } from './agent/events.js';
@@ -26,7 +26,7 @@ export { AGENT_REDACTED, redactAgentArguments } from './agent/redact.js';
26
26
  export { DEFAULT_AGENT_AUDIT_PATH, parseAuditRecord, toAuditRecord } from './agent/audit.js';
27
27
  export type { AgentAuditDeniedRecord, AgentAuditInvokedRecord, AgentAuditRecord, } from './agent/audit.js';
28
28
  export { AGENT_AUDIT_BINDING, createAuditEmitter } from './agent/audit-emitter.js';
29
- export type { AgentAuditEmitter, AgentAuditSink } from './agent/audit-emitter.js';
29
+ export type { AgentAuditEmitter, AgentAuditSink, AuditEmitterOptions } from './agent/audit-emitter.js';
30
30
  export { AGENT_APPROVAL_CONFIG_KEY, agentApprovalExpiredAt, agentApprovalFingerprint, agentApprovalPrincipalKey, agentApprovalStatusAt, agentApprovalUsableAt, agentApprovalVisibleTo, buildAgentApprovalRequest, canonicalizeAgentApprovalInput, DEFAULT_AGENT_APPROVAL_TTL_MS, } from './agent/approval.js';
31
31
  export type { AgentApprovalMatch, AgentApprovalRequest, AgentApprovalRequestInput, AgentApprovalStatus, AgentApprovalStore, } from './agent/approval.js';
32
32
  export { AgentApprovalRequested } from './agent/AgentApprovalRequested.js';
package/dist/index.js CHANGED
@@ -8,13 +8,13 @@ import { PATH_PARAM_PATTERN, extractPathParamNames } from "./internal/route-path
8
8
  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";
9
9
  import { n as detectServerlessRuntime, t as SERVERLESS_RUNTIME_LABELS } from "./serverless-D96rJb6x.js";
10
10
  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, _t as getSessionFromContext, 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 defaultCookieSecure, 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-CjE2oO50.js";
11
- 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-CdfPfQdj.js";
11
+ 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-D295_7-_.js";
12
12
  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-CvDwk2Gj.js";
13
13
  import { n as ProviderManager, r as ServiceProvider } from "./loopback-guard-DT9gHF0F.js";
14
14
  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";
15
15
  import { n as getAuthContext, t as AUTH_CONTEXT_KEY } from "./context-CXk_umpT.js";
16
- import { n as filterSensitiveData, t as Logger } from "./Logger-DFifRAtc.js";
17
- import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-thXRnaju.js";
16
+ import { a as runInRequestScope, i as keepAlive, n as filterSensitiveData, t as Logger } from "./Logger-DWXdtLSJ.js";
17
+ import { a as RedisStore, i as FileStore, n as createCacheManager, o as MemoryStore, r as TaggedCache, s as resolveLazyRedisClient, t as CacheManager } from "./cache-DikxP7Bk.js";
18
18
  import { n as createRedisClient, r as RedisSessionStore } from "./client-C5Wj9P9o.js";
19
19
  import { r as isMcpEndpointEnabled } from "./endpoint-Dsw3Acvq.js";
20
20
  import { n as isHotReloadRuntime, r as matchingOpenParen, t as claimHotDisposable } from "./hot-disposables-B5BXqaIH.js";
@@ -26,7 +26,7 @@ import { a as RequestFinished, c as UserLoggedOut, d as createEventManager, f as
26
26
  import { a as NotificationManager, c as setNotificationManager, d as getNotification, f as registerNotification, i as MailChannel, l as resolveNotifiableType, n as SlackChannel, o as createNotificationManager, p as Notification, r as DatabaseChannel, s as getNotificationManager, t as MemoryChannel, u as clearNotificationRegistry } from "./notifications-D0VXkFLF.js";
27
27
  import { a as processJob, c as RedisDriver$1, i as Worker, l as SyncDriver, n as createQueueManager, o as SqsDriver, r as FailedJobReporter, s as createSqsAdapter, t as QueueManager, u as MemoryDriver$1 } from "./queue-zPPYZdif.js";
28
28
  import { a as MailManager, c as MemoryTransport, i as setMailManager, l as ResendTransport, n as getMailManager, o as createMailManager, r as mail, s as LogTransport, t as Mail, u as SmtpTransport } from "./mail-9CrvJyBZ.js";
29
- import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "./logging-DXmqqUl4.js";
29
+ import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "./logging-Dmzdb6mL.js";
30
30
  import { a as setBroadcastManager, c as PresenceChannel, i as getBroadcastManager, l as PrivateChannel, n as BroadcastManager, o as RedisDriver, r as createBroadcastManager, s as MemoryDriver, t as createTypedBroadcaster, u as Channel } from "./broadcasting-B5RzB0A2.js";
31
31
  import { a as random, c as randomHex, d as sample, f as shuffle, i as pick, l as randomInt, m as uuid, n as generatePassword, o as randomBase64, p as urlSafeToken, r as generateSlug, s as randomBase64Url, t as generateOtp, u as randomString } from "./Random-S0OvCuR8.js";
32
32
  import { a as decrypt, c as getEncrypter, i as createEncrypter, l as setEncrypter, n as verifySignedUrl, o as encrypt, r as Encrypter, s as generateKey, t as signUrl } from "./encryption-uwP3Di4D.js";
@@ -204,26 +204,25 @@ async function renderDocument$1(page, options) {
204
204
  ...options.importMap
205
205
  };
206
206
  const importMap = JSON.stringify({ imports: importMapEntries }, null, 2);
207
- const serializedPage = serializePage(page);
208
207
  const stylesheetLinks = renderStyles(styles);
209
208
  const criticalCss = resolveDocumentValue("criticalCss", options, page.component);
210
209
  const prepaintScript = resolveDocumentValue("prepaintScript", options, page.component);
211
210
  const headMarkup = resolveDocumentValue("head", options, page.component);
212
211
  const ssrResult = await tryRenderSsr(page, options);
213
212
  const headElements = (ssrResult?.head ?? []).map(normalizeHeadElement);
213
+ const hasCustomTitle = headElements.some((element) => /<title\b[^>]*>/iu.test(element));
214
+ const appMarkup = ssrResult === void 0 ? `${pagePayloadElement(page)}<div id="app"></div>` : ssrResult.pageEmbedded ? ssrResult.body : `${ssrResult.body}${pagePayloadElement(page)}`;
214
215
  const headSegments = [
215
216
  "<meta charset=\"utf-8\" />",
216
217
  "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />",
217
- headElements.some((element) => /<title\b[^>]*>/iu.test(element)) ? "" : `<title>${title}</title>`,
218
+ hasCustomTitle ? "" : `<title>${title}</title>`,
218
219
  headMarkup ?? "",
219
220
  criticalCss ? `<style id="guren-critical">${criticalCss}</style>` : "",
220
221
  prepaintScript ? `<script>${prepaintScript}<\/script>` : "",
221
222
  stylesheetLinks,
222
223
  ...headElements,
223
- Object.keys(importMapEntries).length > 0 ? `<script type="importmap">${importMap}<\/script>` : "",
224
- `<script>window.__INERTIA_PAGE__ = ${serializedPage};<\/script>`
224
+ Object.keys(importMapEntries).length > 0 ? `<script type="importmap">${importMap}<\/script>` : ""
225
225
  ].filter((segment) => segment && segment.length > 0);
226
- const appMarkup = ssrResult?.body ?? `<script data-page="app" type="application/json">${serializedPage}<\/script><div id="app"></div>`;
227
226
  const bodyClass = resolveDocumentValue("bodyClass", options, page.component);
228
227
  const bodyAttributes = bodyClass ? ` class="${escapeAttribute(bodyClass)}"` : "";
229
228
  return `<!DOCTYPE html>
@@ -232,11 +231,21 @@ async function renderDocument$1(page, options) {
232
231
  ${headSegments.join("\n ")}
233
232
  </head>
234
233
  <body${bodyAttributes}>
235
- ${appMarkup}
234
+ ${appMarkup}${PAGE_GLOBAL_FROM_ELEMENT}
236
235
  <script type="module" src="${entry}"><\/script>
237
236
  </body>
238
237
  </html>`;
239
238
  }
239
+ function pagePayloadElement(page) {
240
+ return `<script data-page="app" type="application/json">${serializePage(page)}<\/script>`;
241
+ }
242
+ /**
243
+ * `window.__INERTIA_PAGE__` for readers other than the client. Same selector
244
+ * and guards as the client's `getInitialPage` (@guren/inertia-client), so a
245
+ * container carrying a non-payload `data-page` is ignored rather than mounted.
246
+ * A classic inline script, so it has run before the module entry does.
247
+ */
248
+ const PAGE_GLOBAL_FROM_ELEMENT = "<script>try{var e=document.querySelector('script[data-page=\"app\"][type=\"application/json\"]')||document.getElementById(\"app\"),p=JSON.parse(e.tagName===\"SCRIPT\"?e.textContent:e.getAttribute(\"data-page\"));if(p&&p.component)window.__INERTIA_PAGE__=p}catch(_){}<\/script>";
240
249
  async function tryRenderSsr(page, options) {
241
250
  const ssrOptions = options.ssr;
242
251
  if (ssrOptions?.enabled === false) return;
@@ -252,7 +261,8 @@ async function tryRenderSsr(page, options) {
252
261
  if (!result || typeof result.body !== "string") return;
253
262
  return {
254
263
  body: result.body,
255
- head: Array.isArray(result.head) ? result.head : []
264
+ head: Array.isArray(result.head) ? result.head : [],
265
+ pageEmbedded: result.pageEmbedded === true
256
266
  };
257
267
  } catch (error) {
258
268
  console.error("Inertia SSR renderer failed; falling back to client rendering.", error);
@@ -3437,7 +3447,7 @@ var Application = class {
3437
3447
  await provider.boot?.();
3438
3448
  }
3439
3449
  async fetch(request, env, executionCtx) {
3440
- return this.hono.fetch(request, env, executionCtx);
3450
+ return runInRequestScope(executionCtx, () => this.hono.fetch(request, env, executionCtx));
3441
3451
  }
3442
3452
  async listen(options = {}) {
3443
3453
  if (!Bun) throw new Error("Bun runtime is required to call Application.listen");
@@ -4186,21 +4196,29 @@ function deriveAuthorization(definition, method) {
4186
4196
  /**
4187
4197
  * The names a protocol adapter may add to an application's tool catalogue on
4188
4198
  * its own, and which an application route therefore may not claim (RFC 0016
4189
- * §5.4). One rule, two readers: `@guren/plugin-mcp` adds `guren.preflight` to
4199
+ * §5.4). One rule, two readers: `@guren/plugin-mcp` adds `guren_preflight` to
4190
4200
  * the catalogue it serves, `guren check` fails a route whose tool name
4191
4201
  * collides; the CLI cannot import the plugin, hence beside the derivation. A
4192
4202
  * `tools/list` carrying two tools with one name is rejected wholesale by an MCP
4193
- * client, so a collision costs the *entire* catalogue. The `guren.` prefix is
4203
+ * client, so a collision costs the *entire* catalogue. The `guren_` prefix is
4194
4204
  * not reserved wholesale: that would fail routes over collisions that do not exist.
4195
4205
  */
4196
4206
  /**
4207
+ * The grammar every known client accepts: a strict subset of MCP's own
4208
+ * (`AGENT_TOOL_NAME_PATTERN`, which admits `.` and 128 characters). The Claude and
4209
+ * OpenAI tool APIs enforce it; Claude Managed Agents silently skips an MCP tool
4210
+ * outside it (#787). Meta-tools have no `toolName` escape hatch, so the names
4211
+ * below must match; `guren check` warns on a route name that does not.
4212
+ */
4213
+ const PORTABLE_AGENT_TOOL_NAME_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;
4214
+ /**
4197
4215
  * The preflight companion tool (RFC 0016 §5.4). Preflight cannot be an
4198
4216
  * *argument* of the tool being checked: a tool advertising an `outputSchema`
4199
4217
  * must answer with conforming `structuredContent` unless the result is an
4200
4218
  * error, and a verdict conforms to no route's output. One meta-tool for the
4201
4219
  * whole catalogue, not one companion per tool (§5.5).
4202
4220
  */
4203
- const PREFLIGHT_TOOL_NAME = "guren.preflight";
4221
+ const PREFLIGHT_TOOL_NAME = "guren_preflight";
4204
4222
  /**
4205
4223
  * The approval-status companion tool (RFC 0016 §5.4 item 4). A caller handed a
4206
4224
  * request id needs something that can say what became of it, and the gated tool
@@ -4208,12 +4226,12 @@ const PREFLIGHT_TOOL_NAME = "guren.preflight";
4208
4226
  * mode of the first, so neither output schema is the union of two unrelated
4209
4227
  * shapes.
4210
4228
  */
4211
- const APPROVAL_STATUS_TOOL_NAME = "guren.approval_status";
4229
+ const APPROVAL_STATUS_TOOL_NAME = "guren_approval_status";
4212
4230
  /** Every meta-tool name an adapter may occupy. */
4213
4231
  const RESERVED_AGENT_TOOL_NAMES = [PREFLIGHT_TOOL_NAME, APPROVAL_STATUS_TOOL_NAME];
4214
4232
  /**
4215
4233
  * Whether a tool name belongs to the framework rather than the application.
4216
- * Case-sensitive: MCP tool names are matched literally, so `Guren.Preflight` is
4234
+ * Case-sensitive: MCP tool names are matched literally, so `Guren_Preflight` is
4217
4235
  * a different tool and reserving it would take a name away for nothing.
4218
4236
  */
4219
4237
  function isReservedAgentToolName(name) {
@@ -4661,18 +4679,24 @@ const AGENT_AUDIT_BINDING = "agent.audit";
4661
4679
  * emitted for genuine listeners (RFC 0016 §5.2). Neither half may fail the call
4662
4680
  * it records: both are caught, the sink's failure warned rather than swallowed.
4663
4681
  */
4664
- function createAuditEmitter(sink, events, now = () => /* @__PURE__ */ new Date()) {
4682
+ function createAuditEmitter(sink, events, now = () => /* @__PURE__ */ new Date(), options = {}) {
4665
4683
  return (event) => {
4666
- if (sink) try {
4667
- Promise.resolve(sink(toAuditRecord(event, now()))).catch(warnSinkFailure);
4668
- } catch (error) {
4669
- warnSinkFailure(error);
4670
- }
4671
- events?.emit(event).catch((error) => {
4672
- console.warn(`[guren] audit event listener failed: ${String(error)}`);
4673
- });
4684
+ if (sink) keepAlive({
4685
+ run: () => sink(toAuditRecord(event, now())),
4686
+ onFailure: warnSinkFailure,
4687
+ label: LABEL
4688
+ }, options.defer);
4689
+ if (events) keepAlive({
4690
+ run: () => events.emit(event),
4691
+ onFailure: warnListenerFailure,
4692
+ label: LABEL
4693
+ }, options.defer);
4674
4694
  };
4675
4695
  }
4696
+ const LABEL = "agent audit work";
4697
+ function warnListenerFailure(error) {
4698
+ console.warn(`[guren] audit event listener failed: ${String(error)}`);
4699
+ }
4676
4700
  function warnSinkFailure(error) {
4677
4701
  console.warn(`[guren] agent audit sink failed, record dropped: ${String(error)}`);
4678
4702
  }
@@ -4797,7 +4821,7 @@ function agentApprovalUsableAt(request, now) {
4797
4821
  }
4798
4822
  /**
4799
4823
  * Whether `principal` may be told anything at all about `request` — the scope
4800
- * rule of `guren.approval_status` (RFC 0016 §5.4): a caller reads only the
4824
+ * rule of `guren_approval_status` (RFC 0016 §5.4): a caller reads only the
4801
4825
  * status of a request it created, or an agent could walk ids and enumerate
4802
4826
  * other principals' pending actions. A `false` here must be answered *exactly*
4803
4827
  * as an unknown id is: any difference in message, shape or timing reintroduces it.
@@ -4891,19 +4915,19 @@ const DEFAULT_APPROVAL_CONFIGURE_HINT = "an approval queue on the invocation pip
4891
4915
  */
4892
4916
  const DEFAULT_SCOPE_SUBJECT = "The caller's scopes";
4893
4917
  /**
4894
- * Wrap the application's `notify` so a failure can neither fail the tool call nor
4895
- * lose the record: it is already persisted when this runs, so a dead channel costs
4896
- * an approver an email, not a request. The failure is warned about with the request
4897
- * id, which is what finds the record sitting there unannounced. Both shapes are
4898
- * caught — a synchronous throw and a rejected promise.
4918
+ * A failure may neither fail the tool call nor lose the record: it is persisted
4919
+ * before this runs, so a dead channel costs an approver an email. The warning
4920
+ * carries the request id, which is what finds the record sitting there
4921
+ * unannounced. Everything else about invoking a best-effort channel — which
4922
+ * failures are caught, and when `defer` runs — is {@link keepAlive}'s.
4899
4923
  */
4900
- function notifyApprovers(notify) {
4924
+ function notifyApprovers(notify, defer) {
4901
4925
  return (request) => {
4902
- try {
4903
- Promise.resolve(notify(request)).catch((error) => warnNotifyFailure(request, error));
4904
- } catch (error) {
4905
- warnNotifyFailure(request, error);
4906
- }
4926
+ keepAlive({
4927
+ run: () => notify(request),
4928
+ onFailure: (error) => warnNotifyFailure(request, error),
4929
+ label: `approval notification for request ${request.id}`
4930
+ }, defer);
4907
4931
  };
4908
4932
  }
4909
4933
  function warnNotifyFailure(request, error) {
@@ -5010,7 +5034,7 @@ function spentVerdict(tool, request) {
5010
5034
  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);
5011
5035
  }
5012
5036
  /**
5013
- * The scope half alone — what `guren.preflight` checks before rehearsing a call
5037
+ * The scope half alone — what `guren_preflight` checks before rehearsing a call
5014
5038
  * (RFC 0016 §5.4). Checking requires the *same* scope as calling, or the
5015
5039
  * companion becomes a probe of tools the token cannot call. Approval is not
5016
5040
  * applied: a rehearsal executes nothing, and approval gates an ability rather
@@ -5034,13 +5058,13 @@ function scopedShape(tool) {
5034
5058
  //#endregion
5035
5059
  //#region src/agent/pipeline.ts
5036
5060
  /**
5037
- * Build {@link AgentInvocationOptions.approvals} for one caller.
5038
- *
5039
- * The TTL default, the redaction rules and the `notify` wrapping are invariants
5040
- * of an approval record rather than of a protocol. Per caller, because an
5041
- * approval binds to the principal that asked; `undefined` means no queue.
5061
+ * Build {@link AgentInvocationOptions.approvals} for one caller — an approval binds
5062
+ * to the principal that asked; `undefined` means no queue. The TTL default, the
5063
+ * redaction rules and the `notify` wrapping are invariants of an approval record
5064
+ * rather than of a protocol, which is why `defer` arrives here: a `notify` the
5065
+ * pipeline received already wrapped cannot be given a deferrer afterwards.
5042
5066
  */
5043
- function createAgentApprovalContext(config, principal) {
5067
+ function createAgentApprovalContext(config, principal, defer) {
5044
5068
  if (!config) return void 0;
5045
5069
  return {
5046
5070
  store: config.store,
@@ -5048,7 +5072,7 @@ function createAgentApprovalContext(config, principal) {
5048
5072
  now: () => /* @__PURE__ */ new Date(),
5049
5073
  ttlMs: config.ttlMs ?? 36e5,
5050
5074
  redact: (tool, args) => redactAgentArguments(args, tool.redact),
5051
- notify: notifyApprovers(config.notify)
5075
+ notify: notifyApprovers(config.notify, defer)
5052
5076
  };
5053
5077
  }
5054
5078
  /**
@@ -5192,7 +5216,7 @@ function elapsed(startedAt) {
5192
5216
  * clock, no protocol.
5193
5217
  *
5194
5218
  * Here rather than in an adapter because two surfaces answer this question —
5195
- * `guren.approval_status` over MCP and a durable agent's own status check
5219
+ * `guren_approval_status` over MCP and a durable agent's own status check
5196
5220
  * (RFC 0017 §5) — and a record one of them calls "approved" must not be one
5197
5221
  * the other hides.
5198
5222
  */
@@ -7907,4 +7931,4 @@ function renderEnvironmentSection() {
7907
7931
  //#region src/index.ts
7908
7932
  ensureErrorStackTracePolyfill();
7909
7933
  //#endregion
7910
- 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, BUILT_IN_SESSION_DRIVERS, 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, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, 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, PER_PROCESS_SESSION_DRIVERS, 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, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SessionManager, 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, detectServerlessRuntime, 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, prototype, 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 };
7934
+ 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, BUILT_IN_SESSION_DRIVERS, 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, CookieSessionStore, CursorPaginator, CustomCheck, DEFAULT_AGENT_APPROVAL_TTL_MS, DEFAULT_AGENT_AUDIT_PATH, DEFAULT_APPROVAL_CONFIGURE_HINT, DEFAULT_SCOPE_SUBJECT, DEFAULT_SESSION_STORE_NAME, 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, PER_PROCESS_SESSION_DRIVERS, PORTABLE_AGENT_TOOL_NAME_PATTERN, 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, SERVERLESS_RUNTIME_LABELS, Schedule, ScheduledTask, Scheduler, SchedulingServiceProvider, ScryptHasher, SeederRunner, ServiceProvider, SessionGuard, SessionManager, 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, detectServerlessRuntime, 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, prototype, 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 };
@@ -1,3 +1,3 @@
1
- import { n as filterSensitiveData, t as Logger } from "../Logger-DFifRAtc.js";
2
- import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "../logging-DXmqqUl4.js";
1
+ import { n as filterSensitiveData, t as Logger } from "../Logger-DWXdtLSJ.js";
2
+ import { a as DailyFileChannel, c as matchDailyFileDate, d as LOG_LEVEL_PRIORITY, i as setLogManager, l as FileChannel, n as createLogManager, o as dailyFileDateStamp, r as getLogManager, s as dailyFilePath, t as LogManager, u as ConsoleChannel } from "../logging-Dmzdb6mL.js";
3
3
  export { ConsoleChannel, DailyFileChannel, FileChannel, LOG_LEVEL_PRIORITY, LogManager, Logger, createLogManager, dailyFileDateStamp, dailyFilePath, filterSensitiveData, getLogManager, matchDailyFileDate, setLogManager };
@@ -1,4 +1,4 @@
1
- import { r as isPromiseLike, t as Logger } from "./Logger-DFifRAtc.js";
1
+ import { r as isPromiseLike, t as Logger } from "./Logger-DWXdtLSJ.js";
2
2
  import * as path$1 from "node:path";
3
3
  import * as fs from "node:fs";
4
4
  //#region src/logging/types.ts
@@ -33,6 +33,12 @@ export interface InertiaSsrContext {
33
33
  export interface InertiaSsrResult {
34
34
  head: string[];
35
35
  body: string;
36
+ /**
37
+ * True when `body` already carries the page in its `data-page` element, as
38
+ * Inertia's own `createInertiaApp` writes it. Unset, the engine appends its
39
+ * element after the body: a second copy, never a document without a payload.
40
+ */
41
+ pageEmbedded?: boolean;
36
42
  }
37
43
  export type InertiaSsrRenderer = (context: InertiaSsrContext) => Promise<InertiaSsrResult> | InertiaSsrResult;
38
44
  export interface InertiaSsrOptions {
@@ -1,5 +1,5 @@
1
1
  import { n as trimTrailingSlashes } from "../trim-slashes-BLY9hKAa.js";
2
- import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-CdfPfQdj.js";
2
+ import { _ as parseImportMap, a as getManifestCss, c as isViteProduction, d as startViteDevServer, f as GUREN_ASCII_ART, h as logDevServerBanner, i as clientManifestCandidates, l as loadViteManifest, o as getManifestFile, r as PUBLIC_ASSETS_URL_PREFIX, u as normalizeDevServerUrl } from "../vite-manifest-D295_7-_.js";
3
3
  import { n as hash } from "../Hash-D2DFd8xX.js";
4
4
  import { createRequire } from "node:module";
5
5
  import { dirname, extname, join, resolve, sep } from "node:path";
@@ -0,0 +1,26 @@
1
+ /**
2
+ * How a best-effort side channel (an audit sink, an approval notification, an
3
+ * async log channel) is invoked so that it can neither fail the call it was
4
+ * only recording nor be lost by the runtime. Three orderings have to hold
5
+ * together, and each is wrong in a way tests off Workers cannot see: a
6
+ * synchronous throw and a rejection both reach `onFailure`; the `.catch` is
7
+ * attached *before* deferring, since `waitUntil` on a rejecting promise raises
8
+ * an unhandled rejection in workerd; and `defer` itself throws there once the
9
+ * response has settled.
10
+ */
11
+ import { type Deferrer } from './request-deferrer.js';
12
+ export type { Deferrer };
13
+ /** One best-effort side channel, as {@link keepAlive} invokes it. */
14
+ export interface BestEffortChannel {
15
+ run: () => void | PromiseLike<unknown>;
16
+ onFailure: (error: unknown) => void;
17
+ /** Completes "<label> could not be deferred", so pass a noun phrase. */
18
+ label: string;
19
+ }
20
+ /**
21
+ * `defer` defaults to the deferrer of the Workers request being served, where
22
+ * an undeferred channel is abandoned with the request context; `waitUntil`
23
+ * keeps it alive past the response. Outside a request, and on every other
24
+ * runtime, there is none and the channel is fire-and-forget.
25
+ */
26
+ export declare function keepAlive(channel: BestEffortChannel, defer?: Deferrer | undefined): void;
@@ -0,0 +1,10 @@
1
+ /** `ExecutionContext.waitUntil`, bound to its context. */
2
+ export type Deferrer = (work: Promise<unknown>) => void;
3
+ /**
4
+ * `ctx` is typed `unknown` because `app.fetch`'s third argument is a cast
5
+ * wherever it arrives from. One without a callable `waitUntil` (every runtime
6
+ * but Workers) enters no scope, so a nested call keeps the outer request's.
7
+ */
8
+ export declare function runInRequestScope<T>(ctx: unknown, fn: () => T): T;
9
+ /** The deferrer of the request this code runs for, when one was entered. */
10
+ export declare function requestDeferrer(): Deferrer | undefined;
@@ -34,7 +34,7 @@ function parseImportMap(value, options = {}) {
34
34
  const DEFAULT_DEV_STYLES_ENTRY = "/resources/css/app.css";
35
35
  //#endregion
36
36
  //#region package.json
37
- var version = "2.21.0";
37
+ var version = "2.22.0";
38
38
  //#endregion
39
39
  //#region src/http/dev-banner.ts
40
40
  figlet.parseFont("Standard", standard);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guren/server",
3
- "version": "2.21.0",
3
+ "version": "2.22.0",
4
4
  "type": "module",
5
5
  "sideEffects": false,
6
6
  "license": "MIT",
@@ -142,7 +142,7 @@
142
142
  "test": "bun test"
143
143
  },
144
144
  "dependencies": {
145
- "@guren/orm": "^2.7.1",
145
+ "@guren/orm": "^2.8.0",
146
146
  "@modelcontextprotocol/sdk": "^1.30.0",
147
147
  "chalk": "^5.3.0",
148
148
  "consola": "^3.4.2",
@@ -176,6 +176,7 @@
176
176
  "@types/ioredis": "^5.0.0",
177
177
  "@types/node": "^20.14.10",
178
178
  "@types/nodemailer": "^8.0.1",
179
+ "miniflare": "5.20260801.1-alpha",
179
180
  "tsdown": "^0.22.14",
180
181
  "typescript": "^7.0.2",
181
182
  "vite": "^8.0.0"