@guren/server 2.21.0 → 2.23.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 (115) hide show
  1. package/dist/Job-BxioDEcS.js +165 -0
  2. package/dist/{Logger-DFifRAtc.js → Logger-DWXdtLSJ.js} +62 -2
  3. package/dist/agent/approval-status.d.ts +1 -1
  4. package/dist/agent/approval.d.ts +2 -2
  5. package/dist/agent/audit-emitter.d.ts +11 -1
  6. package/dist/agent/gate.d.ts +10 -8
  7. package/dist/agent/meta-tools.d.ts +13 -5
  8. package/dist/agent/pipeline.d.ts +10 -9
  9. package/dist/auth/AuthManager.d.ts +29 -0
  10. package/dist/auth/AuthenticatableModel.d.ts +15 -0
  11. package/dist/auth/RequestAuthContext.d.ts +10 -1
  12. package/dist/auth/SessionGuard.d.ts +2 -0
  13. package/dist/auth/api-token.d.ts +6 -0
  14. package/dist/auth/context.d.ts +32 -0
  15. package/dist/auth/index.d.ts +7 -0
  16. package/dist/auth/index.js +2 -2
  17. package/dist/auth/model-capability.d.ts +8 -0
  18. package/dist/auth/oauth/index.d.ts +5 -0
  19. package/dist/auth/password/DefaultHasher.d.ts +17 -6
  20. package/dist/auth/password/configured-hasher.d.ts +23 -0
  21. package/dist/auth/providers/ModelUserProvider.d.ts +3 -0
  22. package/dist/auth/providers/unconfigured-user-provider.d.ts +12 -0
  23. package/dist/auth/types.d.ts +9 -0
  24. package/dist/{auth-CjE2oO50.js → auth-D_W1cJp3.js} +279 -84
  25. package/dist/authorization/Gate.d.ts +12 -0
  26. package/dist/authorization/index.js +1 -1
  27. package/dist/{authorization-CdEWZZw3.js → authorization-0mCGUFoI.js} +58 -12
  28. package/dist/broadcasting/BroadcastManager.d.ts +10 -0
  29. package/dist/broadcasting/index.js +1 -1
  30. package/dist/{broadcasting-B5RzB0A2.js → broadcasting-BdJnaq1O.js} +17 -3
  31. package/dist/cache/index.js +1 -1
  32. package/dist/{cache-thXRnaju.js → cache-DikxP7Bk.js} +1 -1
  33. package/dist/container/Container.d.ts +18 -1
  34. package/dist/container/bindings.d.ts +9 -4
  35. package/dist/container/index.d.ts +4 -2
  36. package/dist/container/resolve-optional.d.ts +10 -0
  37. package/dist/context-af2n5abO.js +91 -0
  38. package/dist/{Job-CvDwk2Gj.js → default-application-Chbrul_m.js} +126 -82
  39. package/dist/encryption/Encrypter.d.ts +10 -0
  40. package/dist/encryption/index.js +1 -1
  41. package/dist/{encryption-uwP3Di4D.js → encryption-BRjZnshr.js} +23 -5
  42. package/dist/errors/ExceptionHandler.d.ts +10 -0
  43. package/dist/events/Event.d.ts +18 -0
  44. package/dist/events/EventManager.d.ts +56 -4
  45. package/dist/events/index.d.ts +2 -1
  46. package/dist/events/index.js +2 -2
  47. package/dist/events/queued.d.ts +8 -0
  48. package/dist/events/serialize.d.ts +8 -0
  49. package/dist/events/types.d.ts +19 -2
  50. package/dist/events-C86rS63h.js +428 -0
  51. package/dist/health/checks/CacheCheck.d.ts +3 -5
  52. package/dist/health/checks/StorageCheck.d.ts +3 -5
  53. package/dist/health/index.js +1 -1
  54. package/dist/{health-DQSvUplL.js → health-CB0oS_UE.js} +2 -2
  55. package/dist/http/Application.d.ts +28 -0
  56. package/dist/http/default-application.d.ts +33 -0
  57. package/dist/http/middleware/detect-locale.d.ts +2 -1
  58. package/dist/http/request-container.d.ts +25 -0
  59. package/dist/i18n/I18nManager.d.ts +16 -3
  60. package/dist/i18n/index.d.ts +1 -1
  61. package/dist/i18n/index.js +2 -2
  62. package/dist/{i18n-BZ2VrSud.js → i18n-DRo1g0AN.js} +34 -10
  63. package/dist/index.d.ts +16 -11
  64. package/dist/index.js +248 -129
  65. package/dist/lambda/index.js +1 -1
  66. package/dist/logging/LogManager.d.ts +9 -0
  67. package/dist/logging/index.js +2 -2
  68. package/dist/{logging-DXmqqUl4.js → logging-CXotojgW.js} +17 -4
  69. package/dist/mail/Mail.d.ts +14 -1
  70. package/dist/mail/MailManager.d.ts +10 -2
  71. package/dist/mail/index.js +1 -1
  72. package/dist/{mail-9CrvJyBZ.js → mail-CmxO2Ttx.js} +42 -11
  73. package/dist/mvc/Controller.d.ts +1 -1
  74. package/dist/mvc/Router.d.ts +16 -5
  75. package/dist/mvc/inertia/InertiaEngine.d.ts +24 -3
  76. package/dist/mvc/inertia/shared.d.ts +7 -0
  77. package/dist/notifications/NotificationManager.d.ts +15 -0
  78. package/dist/notifications/index.js +1 -1
  79. package/dist/{notifications-D0VXkFLF.js → notifications-CE3U7uyg.js} +24 -5
  80. package/dist/providers/AuthServiceProvider.d.ts +5 -4
  81. package/dist/providers/AuthorizationServiceProvider.d.ts +2 -2
  82. package/dist/providers/BroadcastServiceProvider.d.ts +4 -1
  83. package/dist/providers/EncryptionServiceProvider.d.ts +7 -1
  84. package/dist/providers/EventServiceProvider.d.ts +1 -0
  85. package/dist/providers/LogServiceProvider.d.ts +6 -1
  86. package/dist/providers/MailServiceProvider.d.ts +7 -1
  87. package/dist/providers/NotificationServiceProvider.d.ts +4 -1
  88. package/dist/queue/Job.d.ts +39 -0
  89. package/dist/queue/QueueManager.d.ts +14 -5
  90. package/dist/queue/Worker.d.ts +2 -1
  91. package/dist/queue/index.d.ts +1 -1
  92. package/dist/queue/index.js +3 -3
  93. package/dist/queue/types.d.ts +7 -0
  94. package/dist/{queue-zPPYZdif.js → queue-B3x_RKnB.js} +24 -10
  95. package/dist/redis/RedisSchedulerLock.d.ts +17 -0
  96. package/dist/redis/index.d.ts +2 -0
  97. package/dist/redis/index.js +21 -1
  98. package/dist/runtime/index.js +1 -1
  99. package/dist/scheduling/MemorySchedulerLock.d.ts +16 -0
  100. package/dist/scheduling/ScheduledTask.d.ts +19 -2
  101. package/dist/scheduling/Scheduler.d.ts +25 -0
  102. package/dist/scheduling/index.d.ts +2 -1
  103. package/dist/scheduling/index.js +2 -2
  104. package/dist/scheduling/types.d.ts +26 -2
  105. package/dist/{scheduling-C6tcOtUl.js → scheduling-DudNXGnh.js} +178 -20
  106. package/dist/storage/index.js +1 -1
  107. package/dist/{storage-D_yNe54O.js → storage-6HLaUf9j.js} +2 -13
  108. package/dist/support/deprecate.d.ts +16 -0
  109. package/dist/support/keep-alive.d.ts +26 -0
  110. package/dist/support/request-deferrer.d.ts +10 -0
  111. package/dist/{vite-manifest-CdfPfQdj.js → vite-manifest-B8720V7w.js} +1 -1
  112. package/dist/warn-once-p-IlMjra.js +13 -0
  113. package/package.json +3 -2
  114. package/dist/context-CXk_umpT.js +0 -21
  115. package/dist/events-DOmAHDeP.js +0 -230
@@ -0,0 +1,165 @@
1
+ import { h as warnDeprecatedSetter, m as warnDeprecatedGetter, n as ambientBinding, o as defaultContainer, r as ambientContainer } from "./default-application-Chbrul_m.js";
2
+ import { randomBytes } from "node:crypto";
3
+ //#region src/container/resolve-optional.ts
4
+ function resolveOptional(container, key) {
5
+ if (!container) return;
6
+ const optional = container.makeOptional;
7
+ if (typeof optional === "function") return optional.call(container, key);
8
+ return container.has?.(key) ? container.make(key) : void 0;
9
+ }
10
+ //#endregion
11
+ //#region src/queue/Job.ts
12
+ /**
13
+ * The pin `setQueueDriver()` writes, and nothing else does. A manager that
14
+ * published its own driver here pinned the first booted app's queue for every
15
+ * later `Application` in the process.
16
+ */
17
+ let globalDriver = null;
18
+ /**
19
+ * Pins the driver `Job.dispatch()` sends through, ahead of the container's
20
+ * `queue` manager. An explicit override rather than a fallback: `@guren/testing`'s
21
+ * `fakeQueue()` and the tutorial's queue test inject through it (RFC 0023 §3).
22
+ * The pin survives its deprecation window because nothing else expresses it; it
23
+ * goes with this setter in Part 3.
24
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Bind the manager on the
25
+ * app's container — `QueueServiceProvider` already does — and inject a fake with
26
+ * `app.container.fake('queue', manager)`.
27
+ */
28
+ function setQueueDriver(driver) {
29
+ warnDeprecatedSetter("setQueueDriver");
30
+ globalDriver = driver;
31
+ }
32
+ /** Drops the pin, so `getQueueDriver()` falls back to the container again. */
33
+ function clearQueueDriver() {
34
+ globalDriver = null;
35
+ }
36
+ /** @internal The driver `setQueueDriver()` pinned, for a dispatcher with a container of its own to honour first. */
37
+ function pinnedQueueDriver() {
38
+ return globalDriver;
39
+ }
40
+ /** The `queue` manager bound in the default application, or null when there is neither. */
41
+ function boundQueueManager() {
42
+ return ambientBinding("queue") ?? null;
43
+ }
44
+ /**
45
+ * The driver `Job.dispatch()` sends through: the pin when set, else the default
46
+ * driver of the `queue` manager the default application binds, else null.
47
+ * Total by contract — every caller treats it as `QueueDriver | null`, so a
48
+ * manager bound with no factory for its default must read as absent rather
49
+ * than throw.
50
+ * @deprecated since 2.23.0, removed in 3.0.0 (RFC 0023). Resolve the manager
51
+ * from the container that owns the call — `this.make('queue')` in a controller,
52
+ * job or command — and take `manager.driver()`.
53
+ */
54
+ function getQueueDriver() {
55
+ warnDeprecatedGetter("getQueueDriver");
56
+ return resolveQueueDriver();
57
+ }
58
+ /** @internal `getQueueDriver()` without the warning, for the framework's own dispatch paths. */
59
+ function resolveQueueDriver() {
60
+ if (globalDriver) return globalDriver;
61
+ const manager = boundQueueManager();
62
+ if (!manager || !manager.hasDriver(manager.getDefaultDriverName())) return null;
63
+ return manager.driver();
64
+ }
65
+ /** Why `getQueueDriver()` came back null: a manager bound with no driver reads differently from no manager at all. */
66
+ function missingQueueDriverMessage() {
67
+ const manager = boundQueueManager();
68
+ if (manager) return `Queue driver not configured: the "queue" manager has no driver named "${manager.getDefaultDriverName()}". Register one with manager.registerDriver(name, factory), or pass createQueueManager({ drivers }) a factory for it.`;
69
+ return "Queue driver not configured. Register a provider that binds a QueueManager as \"queue\" (QueueServiceProvider, or your own), or call setQueueDriver() first.";
70
+ }
71
+ function generateJobId() {
72
+ return randomBytes(16).toString("hex");
73
+ }
74
+ /**
75
+ * The one enqueue behind `Job.dispatch()` and `QueueManager.dispatch()`, so the
76
+ * two forms cannot write different messages.
77
+ */
78
+ async function enqueueJob(driver, JobClass, payload, options = {}) {
79
+ const jobId = generateJobId();
80
+ const now = /* @__PURE__ */ new Date();
81
+ const delay = options.delay ?? 0;
82
+ const job = {
83
+ id: jobId,
84
+ name: resolveJobName(JobClass),
85
+ payload,
86
+ queue: options.queue ?? JobClass.queue,
87
+ attempts: 0,
88
+ maxAttempts: options.maxAttempts ?? JobClass.maxAttempts,
89
+ availableAt: new Date(now.getTime() + delay),
90
+ createdAt: now,
91
+ reservedAt: null
92
+ };
93
+ await driver.push(job);
94
+ return jobId;
95
+ }
96
+ var Job = class {
97
+ /**
98
+ * Stable wire name: queued messages record it and the worker resolves the
99
+ * class back from it. Defaults to the class name, which breaks under
100
+ * identifier mangling or a rename with messages still in flight.
101
+ * @default the class name
102
+ */
103
+ static jobName;
104
+ /** @default 'default' */
105
+ static queue = "default";
106
+ /** @default 3 */
107
+ static maxAttempts = 3;
108
+ /**
109
+ * 'exponential' = 2^attempt * 1000ms, 'linear' = attempt * 1000ms, a number
110
+ * is a fixed delay in milliseconds.
111
+ * @default 'exponential'
112
+ */
113
+ static backoff = "exponential";
114
+ container;
115
+ /** @internal Called by the Worker with the container of the app it drains, before `handle()`. */
116
+ setContainer(container) {
117
+ this.container = container;
118
+ }
119
+ make(key) {
120
+ return (this.container ?? defaultContainer()).make(key);
121
+ }
122
+ makeOptional(key) {
123
+ return resolveOptional(this.container ?? ambientContainer(), key);
124
+ }
125
+ static async dispatch(payload, options = {}) {
126
+ const driver = resolveQueueDriver();
127
+ if (!driver) throw new Error(missingQueueDriverMessage());
128
+ return enqueueJob(driver, this, payload, options);
129
+ }
130
+ static async dispatchAfter(delayMs, payload, options = {}) {
131
+ return this.dispatch(payload, {
132
+ ...options,
133
+ delay: delayMs
134
+ });
135
+ }
136
+ static calculateRetryDelay(attempts) {
137
+ if (typeof this.backoff === "number") return this.backoff;
138
+ if (this.backoff === "linear") return attempts * 1e3;
139
+ return Math.pow(2, attempts) * 1e3;
140
+ }
141
+ };
142
+ /**
143
+ * Only an *own* `jobName` counts: statics are inherited, so reading the
144
+ * prototype chain would make every subclass of a pinned job claim its
145
+ * parent's identity and overwrite it in the registry.
146
+ */
147
+ function resolveJobName(jobClass) {
148
+ return (Object.prototype.hasOwnProperty.call(jobClass, "jobName") ? jobClass.jobName : void 0) ?? jobClass.name;
149
+ }
150
+ const jobRegistry = /* @__PURE__ */ new Map();
151
+ function registerJob(jobClass) {
152
+ jobRegistry.set(resolveJobName(jobClass), jobClass);
153
+ }
154
+ function getJob(name) {
155
+ return jobRegistry.get(name);
156
+ }
157
+ function getRegisteredJobs() {
158
+ return new Map(jobRegistry);
159
+ }
160
+ /** Testing only. */
161
+ function clearJobRegistry() {
162
+ jobRegistry.clear();
163
+ }
164
+ //#endregion
165
+ export { getJob as a, pinnedQueueDriver as c, resolveQueueDriver as d, setQueueDriver as f, enqueueJob as i, registerJob as l, clearJobRegistry as n, getQueueDriver as o, resolveOptional as p, clearQueueDriver as r, getRegisteredJobs as s, Job as t, resolveJobName as u };
@@ -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;
@@ -2,7 +2,11 @@ import type { Context } from 'hono';
2
2
  import type { Model, PlainObject } from '@guren/orm';
3
3
  import { type ModelUserProviderOptions } from './providers/ModelUserProvider.js';
4
4
  import { type ApiTokenStore } from './api-token.js';
5
+ import type { PasswordHasher } from './password/PasswordHasher.js';
5
6
  import type { AttachContextOptions, AuthContext, AuthManagerContract, AuthManagerOptions, AuthCredentials, Guard, GuardContext, GuardFactory, ProviderFactory, UserProvider } from './types.js';
7
+ /** The guard and provider names an app gets without naming either: `createApp()` registers them, `useModel()` fills them. */
8
+ export declare const DEFAULT_GUARD = "web";
9
+ export declare const DEFAULT_PROVIDER = "users";
6
10
  /** How `useTokens()` configures the guard it registers. */
7
11
  export interface ApiTokenGuardOptions {
8
12
  /** Registered provider name that loads the full user record from a token's userId. */
@@ -19,9 +23,21 @@ export declare class AuthManager implements AuthManagerContract {
19
23
  private tokenGuard;
20
24
  private apiTokenStore;
21
25
  private apiTokenOptions;
26
+ private readonly passwordHasher;
22
27
  constructor(options?: AuthManagerOptions);
28
+ /**
29
+ * The one password hasher this app writes with: `AuthPluginOptions.hasher`
30
+ * resolved, scrypt by default. `useModel()` hands it to the provider, and
31
+ * `AuthenticatableModel` reads it through the container, so a row the model
32
+ * hashes and a login the provider verifies never disagree on the format.
33
+ */
34
+ hasher(): PasswordHasher;
23
35
  registerGuard<User>(name: string, factory: GuardFactory<User>): void;
24
36
  registerProvider<User>(name: string, factory: ProviderFactory<User>): void;
37
+ /** The guard `useTokens()` registered, or null. On this class rather than the contract, like `getApiTokenOptions()`. */
38
+ getTokenGuard(): string | null;
39
+ /** Whether a provider factory is registered under `name`; `getProvider()` throws where this is false. */
40
+ hasProvider(name: string): boolean;
25
41
  getProvider<User>(name: string): UserProvider<User>;
26
42
  createGuard<User>(name: string, context: GuardContext): Guard<User>;
27
43
  guardNames(): string[];
@@ -36,6 +52,19 @@ export declare class AuthManager implements AuthManagerContract {
36
52
  */
37
53
  resolveGuardName(ctx: Context, name?: string): string;
38
54
  createAuthContext(ctx: Context, options?: AttachContextOptions): AuthContext;
55
+ /**
56
+ * The user provider `useTokens({ provider })` configured, and no other.
57
+ * Every surface that turns a token's or a principal's id into a user record
58
+ * reads this one: a second rule would mean a policy reading a user field
59
+ * behaved differently depending on which surface the call arrived on.
60
+ */
61
+ private tokenUserProvider;
62
+ /**
63
+ * The principal a middleware resolved for this request, sanitized the way the
64
+ * token guard sanitizes its own. Read at call time, so a context built before
65
+ * the authenticating middleware ran still answers with it.
66
+ */
67
+ private resolvePrincipal;
39
68
  attempt(name: string, ctx: Context, credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
40
69
  /**
41
70
  * Register a model-based authentication provider and session guard — the
@@ -20,6 +20,21 @@ export declare abstract class AuthenticatableModel<TRecord extends PlainObject =
20
20
  * values such as `passwordHash: 'oauth:...'`.
21
21
  */
22
22
  protected static deniedFields(): string[];
23
+ /** The model author's own choice, read by `ModelUserProvider` so one model and its provider cannot write at different parameters. */
24
+ static explicitPasswordHasher(): PasswordHasher | null;
25
+ /**
26
+ * Assigned by `AuthManager.useModel()` at bind time, never by the model's
27
+ * author. A class evaluating before `createApp()` therefore pins nothing, and
28
+ * a model no app ever bound falls through to scrypt (a seeder run bare, a unit test).
29
+ */
30
+ static configuredPasswordHasher: PasswordHasher | null;
23
31
  protected static resolvePasswordHasher(): PasswordHasher;
32
+ /**
33
+ * Persist an already-hashed password without hashing it again. A model that
34
+ * hashes in place (`passwordField === passwordHashField`) cannot tell a hash
35
+ * from a plaintext by column name, so a rehash written through `update()`
36
+ * would be hashed a second time and lock the account out.
37
+ */
38
+ static storePasswordHash(where: PlainObject, column: string, hash: string): Promise<void>;
24
39
  protected static preparePersistencePayload(data: PlainObject): Promise<PlainObject>;
25
40
  }
@@ -1,14 +1,17 @@
1
1
  import type { Context } from 'hono';
2
2
  import type { Session } from '../http/middleware/index.js';
3
3
  import type { AuthContext, AuthCredentials, Guard } from './types.js';
4
+ import { type ResolvedPrincipal } from './context.js';
4
5
  export type GuardResolver = (resolvedName: string) => Guard<unknown>;
6
+ export type PrincipalResolver = () => ResolvedPrincipal | undefined;
5
7
  export declare class RequestAuthContext implements AuthContext {
6
8
  private readonly resolveName;
7
9
  private readonly ctx;
8
10
  private readonly resolveSession;
9
11
  private readonly resolveGuard;
12
+ private readonly resolvePrincipal;
10
13
  private readonly guardCache;
11
- constructor(resolveName: (name?: string) => string, ctx: Context, resolveSession: () => Session | undefined, resolveGuard: GuardResolver);
14
+ constructor(resolveName: (name?: string) => string, ctx: Context, resolveSession: () => Session | undefined, resolveGuard: GuardResolver, resolvePrincipal?: PrincipalResolver);
12
15
  guard<T = unknown>(name?: string): Guard<T>;
13
16
  session<T extends Session = Session>(): T | undefined;
14
17
  check(): Promise<boolean>;
@@ -19,4 +22,10 @@ export declare class RequestAuthContext implements AuthContext {
19
22
  login<T = unknown>(user: T, remember?: boolean): Promise<void>;
20
23
  attempt(credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
21
24
  logout(): Promise<void>;
25
+ /**
26
+ * The request's identity is whatever just logged in, so a principal a
27
+ * middleware resolved stops answering. A later `logout()` therefore ends the
28
+ * new session rather than revoking the credential the request arrived with.
29
+ */
30
+ private forgetPrincipal;
22
31
  }
@@ -26,5 +26,7 @@ export declare class SessionGuard<User extends Authenticatable = Authenticatable
26
26
  logout(): Promise<void>;
27
27
  attempt(credentials: AuthCredentials, remember?: boolean): Promise<boolean>;
28
28
  validate(credentials: AuthCredentials): Promise<User | null>;
29
+ /** Never the plaintext or the hash: a warning is a log line, and both belong in neither. */
30
+ private describeUser;
29
31
  session<T extends Session = Session>(): T | undefined;
30
32
  }
@@ -144,6 +144,12 @@ export declare function getUserApiTokens(userId: string | number, store: ApiToke
144
144
  * Context key for storing the authenticated token.
145
145
  */
146
146
  export declare const API_TOKEN_KEY = "guren:api-token";
147
+ /**
148
+ * Revoke the token a request presented, and clear it from the request context
149
+ * so `getApiToken()` / `getApiTokenOrFail()` cannot succeed after a logout on
150
+ * the same request. The slot is cleared whether or not a token still verified.
151
+ */
152
+ export declare function revokePresentedToken(ctx: Context, tokenId: string | undefined, store: ApiTokenStore): Promise<void>;
147
153
  /**
148
154
  * Options for the bearer token middleware.
149
155
  */
@@ -1,3 +1,4 @@
1
+ import type { Context } from 'hono';
1
2
  import type { AuthContext } from './types.js';
2
3
  /**
3
4
  * Context key the framework auth context is stored under.
@@ -7,6 +8,26 @@ import type { AuthContext } from './types.js';
7
8
  * re-exports it, and it stays a public root export.
8
9
  */
9
10
  export declare const AUTH_CONTEXT_KEY = "guren:auth";
11
+ /**
12
+ * Context key the principal a middleware already resolved is stored under.
13
+ *
14
+ * The framework auth context answers from this slot before it reaches a guard,
15
+ * so a middleware that authenticates a request (the bearer-token middleware,
16
+ * or an app's own) reaches the Gate whatever order it is mounted in.
17
+ */
18
+ export declare const RESOLVED_PRINCIPAL_KEY = "guren:resolved-principal";
19
+ /**
20
+ * An identity a middleware established for this one request.
21
+ *
22
+ * `user` is null when the credential verified but its user cannot be loaded:
23
+ * the request is then unauthenticated, not merely unresolved.
24
+ */
25
+ export interface ResolvedPrincipal {
26
+ user: unknown;
27
+ id: unknown;
28
+ /** Invalidate the presented credential. `logout()` calls it. */
29
+ revoke?: () => Promise<void>;
30
+ }
10
31
  /**
11
32
  * Read the framework auth context off a request context. `ctx.get` returns
12
33
  * arbitrary values for unknown keys, so the cast is a claim, not a check. A
@@ -17,3 +38,14 @@ export declare const AUTH_CONTEXT_KEY = "guren:auth";
17
38
  export declare function getAuthContext(ctx: {
18
39
  get: (key: string) => unknown;
19
40
  }): AuthContext | undefined;
41
+ export declare function getResolvedPrincipal(ctx: {
42
+ get: (key: string) => unknown;
43
+ }): ResolvedPrincipal | undefined;
44
+ export declare function setResolvedPrincipal(ctx: Context, principal: ResolvedPrincipal | undefined): void;
45
+ /**
46
+ * The auth context a request carries when a middleware resolved a principal and
47
+ * nothing attached a framework context — a bearer-authenticated route on a
48
+ * plain Hono app. Credential flows throw rather than pretending to succeed;
49
+ * `logout()` revokes the presented credential.
50
+ */
51
+ export declare function createPrincipalAuthContext(ctx: Context): AuthContext;
@@ -5,12 +5,19 @@ export { TokenGuard } from './TokenGuard.js';
5
5
  export type { TokenGuardOptions } from './TokenGuard.js';
6
6
  export { BaseUserProvider } from './providers/UserProvider.js';
7
7
  export { ModelUserProvider } from './providers/ModelUserProvider.js';
8
+ export { ScryptHasher as Argon2Hasher } from './password/ScryptHasher.js';
9
+ /**
10
+ * @deprecated Renamed to `Argon2Hasher`, which is what it writes: `Bun.password`'s
11
+ * Argon2id, never scrypt. The name predates the implementation. Removed in 3.0.0.
12
+ */
8
13
  export { ScryptHasher } from './password/ScryptHasher.js';
9
14
  export { NodeHasher } from './password/NodeHasher.js';
10
15
  export { AuthenticatableModel } from './AuthenticatableModel.js';
11
16
  export { createPasswordResetToken, verifyPasswordResetToken, completePasswordReset, buildPasswordResetUrl, parsePasswordResetUrl, MemoryPasswordResetStore, } from './password-reset.js';
12
17
  export { createEmailVerificationToken, verifyEmailToken, completeEmailVerification, buildVerificationUrl, parseVerificationUrl, isEmailVerified, requireVerifiedEmail, MemoryEmailVerificationStore, } from './email-verification.js';
13
18
  export type { PasswordHasher } from './password/PasswordHasher.js';
19
+ export type { PasswordHasherOption } from './password/configured-hasher.js';
20
+ export type { PasswordHashAlgorithm, DefaultHasherOptions } from './password/DefaultHasher.js';
14
21
  export type { PasswordResetConfig, PasswordResetTokenStore, PasswordResetTokenResult, } from './password-reset.js';
15
22
  export type { EmailVerificationConfig, EmailVerificationTokenStore, EmailVerificationToken, EmailVerificationTokenResult, } from './email-verification.js';
16
23
  export { createApiToken, parseApiToken, readBearerToken, verifyApiToken, tokenCan, tokenCanAll, tokenCanAny, revokeApiToken, revokeAllApiTokens, getUserApiTokens, createBearerTokenMiddleware, getApiToken, getApiTokenOrFail, MemoryApiTokenStore, API_TOKEN_KEY, } from './api-token.js';