@guren/server 2.16.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -127,6 +127,30 @@ function createMcpServer(options) {
127
127
  text: JSON.stringify(report, null, 2)
128
128
  }] };
129
129
  });
130
+ server.tool("guren_gate", "Run every verification stage the scaffolded CI runs (codegen, typecheck, lint, check, audit, test) and report each; `ok` is the one verdict on whether the change is done. A stage that cannot run fails rather than skips.", {
131
+ changed: z.boolean().default(false).describe("Narrow check and lint to files changed vs. the merge base with main"),
132
+ deps: z.boolean().default(false).describe("Scan dependencies in the audit stage (needs registry access)")
133
+ }, async ({ changed, deps }) => {
134
+ if (!cli.runGate) return {
135
+ content: [{
136
+ type: "text",
137
+ text: "guren_gate needs a @guren/cli that ships `guren gate`; upgrade the app (bunx guren upgrade)."
138
+ }],
139
+ isError: true
140
+ };
141
+ const report = await cli.runGate({
142
+ cwd,
143
+ changed,
144
+ deps
145
+ });
146
+ return {
147
+ content: [{
148
+ type: "text",
149
+ text: JSON.stringify(report, null, 2)
150
+ }],
151
+ isError: !report.ok
152
+ };
153
+ });
130
154
  server.tool("guren_list_models", "List all models with their table names, relationships, authentication trait, and soft deletes status.", {}, async () => {
131
155
  const models = await cli.listModels({ appRoot: cwd });
132
156
  return { content: [{
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Reading one approval record as an answer for the caller that asked
3
+ * (RFC 0016 §5.4 item 4). Pure derivation, like `approval.ts`: no store, no
4
+ * clock, no protocol.
5
+ *
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
8
+ * (RFC 0017 §5) — and a record one of them calls "approved" must not be one
9
+ * the other hides.
10
+ */
11
+ import { type AgentApprovalRequest } from './approval.js';
12
+ import type { AgentPrincipal } from './events.js';
13
+ /** One answer about one request. */
14
+ export interface ApprovalStatusReport {
15
+ [key: string]: unknown;
16
+ requestId: string;
17
+ status: string;
18
+ tool: string;
19
+ requestedAt: string;
20
+ expiresAt: string;
21
+ executed: false;
22
+ resolvedAt?: string;
23
+ resolvedBy?: string;
24
+ /**
25
+ * When the approval was spent, if it has been. An approved record carrying
26
+ * this authorizes nothing further — the one call it permitted has run, and
27
+ * repeating that call files a fresh request rather than reusing this one.
28
+ */
29
+ consumedAt?: string;
30
+ }
31
+ /**
32
+ * The one message for "there is no such request *for you*". One function for
33
+ * both branches because an unknown id and another principal's id must be the
34
+ * same answer byte for byte: any difference turns the check into a way to
35
+ * enumerate other principals' pending actions. The audit trail is where the
36
+ * distinction is kept, for the operator.
37
+ */
38
+ export declare function approvalStatusNotFoundMessage(requestId: string): string;
39
+ export type ApprovalStatusOutcome = {
40
+ report: ApprovalStatusReport;
41
+ }
42
+ /**
43
+ * Unknown, or not this caller's — one answer to the caller. `foreign` is the
44
+ * half the *operator* gets: it rides beside the message, for the audit event,
45
+ * and must never reach the result.
46
+ */
47
+ | {
48
+ notFound: string;
49
+ foreign: boolean;
50
+ };
51
+ /**
52
+ * Read a stored record as an answer for `principal` at `now`. `record === null`
53
+ * and "not visible to this principal" converge here rather than at two call
54
+ * sites, so their sameness is structural.
55
+ */
56
+ export declare function toApprovalStatusReport(requestId: string, record: AgentApprovalRequest | null, principal: AgentPrincipal | null, now: Date): ApprovalStatusOutcome;
@@ -21,11 +21,13 @@ export interface AgentPrincipal {
21
21
  abilities?: string[];
22
22
  }
23
23
  /**
24
- * The protocol surface an invocation arrived on. `'mcp'` is the application's
25
- * own MCP endpoint, `'dev-mcp'` the development one, `'cli'` a
26
- * `guren tool:call`, `'webmcp'` an in-browser session-authenticated call.
24
+ * The protocol surface an invocation arrived on: `'mcp'` the application's own
25
+ * endpoint, `'dev-mcp'` the development one, `'cli'` a `guren tool:call`,
26
+ * `'webmcp'` an in-browser session call, `'durable'` an agent the application
27
+ * hosts itself (RFC 0017 §4). Every consumer enumerates these as a *total* map,
28
+ * so adding one fails to compile rather than silently failing to parse.
27
29
  */
28
- export type AgentSurface = 'mcp' | 'dev-mcp' | 'cli' | 'webmcp';
30
+ export type AgentSurface = 'mcp' | 'dev-mcp' | 'cli' | 'webmcp' | 'durable';
29
31
  /**
30
32
  * Emitted when an agent tool invocation completed — successfully or not.
31
33
  * `status` carries the HTTP status the dispatch resolved to, so an error
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The adapter-level checks a tool call passes before any HTTP request is
3
+ * synthesized (RFC 0016 §5); what happens *inside* the dispatched request is
4
+ * the application's verdict, reported as an invocation with its HTTP status and
5
+ * never re-judged here. {@link gateToolCall} is synchronous and free of side
6
+ * effects because `tools/list` calls it for every tool on every listing — an
7
+ * approval check there would create a pending record and notify approvers once
8
+ * per tool per client connect. The approval half is {@link gateApproval},
9
+ * reached only from the call path.
10
+ */
11
+ import { type AgentApprovalRequest, type AgentApprovalStore } from './approval.js';
12
+ import type { DerivedAgentTool } from './derive.js';
13
+ import type { AgentPrincipal, AgentToolDenialReason } from './events.js';
14
+ export type GateVerdict = {
15
+ allowed: true;
16
+ } | {
17
+ allowed: false;
18
+ reason: AgentToolDenialReason;
19
+ message: string;
20
+ /**
21
+ * Rendered as the error result's JSON content. Only approval refusals
22
+ * carry one: a caller told "this is pending" needs the id to poll with.
23
+ * Measured against the SDK client, an `isError: true` result keeps its
24
+ * `content` even for a tool declaring an `outputSchema` — which is what
25
+ * makes a pending answer expressible on this protocol (RFC 0016 §5.4).
26
+ */
27
+ body?: Record<string, unknown>;
28
+ };
29
+ /**
30
+ * How an unconfigured approval queue is described when no surface says it
31
+ * better. The pipeline cannot know whether it was reached over MCP, from a
32
+ * durable agent or from a test harness, and naming one surface's configuration
33
+ * call would send most readers to a package they do not install. A surface that
34
+ * knows says so through {@link ScopeGateOptions.configureHint}.
35
+ */
36
+ export declare const DEFAULT_APPROVAL_CONFIGURE_HINT = "an approval queue on the invocation pipeline (approvals: { store, notify })";
37
+ /**
38
+ * Whose scopes a refusal names when no surface says it better. Neutral because
39
+ * a scope denial is not always about a token: a durable agent's principal is
40
+ * minted from its registration and holds no credential, so naming "the token's
41
+ * scopes" would send its operator looking for a token to widen.
42
+ */
43
+ export declare const DEFAULT_SCOPE_SUBJECT = "The caller's scopes";
44
+ /** What {@link gateToolCall} and {@link gatePreflight} need beyond the scopes. */
45
+ export interface ScopeGateOptions {
46
+ /** Whether an approval queue exists to turn a gated call into a request. */
47
+ approvalsConfigured?: boolean;
48
+ /**
49
+ * How *this* surface configures a queue, named in the fail-closed refusal —
50
+ * `'mcpPlugin({ approvals: { store, notify } })'` for the App MCP endpoint,
51
+ * else {@link DEFAULT_APPROVAL_CONFIGURE_HINT}. The trailing period belongs
52
+ * to the sentence: pass the expression, not a sentence.
53
+ */
54
+ configureHint?: string;
55
+ /**
56
+ * What a scope refusal calls the thing whose scopes fell short — `"The
57
+ * token's scopes"` on a bearer surface, else {@link DEFAULT_SCOPE_SUBJECT}.
58
+ * The subject of a sentence completed with " do not grant the tool …", so
59
+ * pass a noun phrase and no trailing punctuation.
60
+ */
61
+ scopeSubject?: string;
62
+ }
63
+ /** What {@link gateApproval} needs to answer for one call. */
64
+ export interface ApprovalGateContext {
65
+ store: AgentApprovalStore;
66
+ principal: AgentPrincipal | null;
67
+ /** How long a new pending record stays answerable. */
68
+ ttlMs?: number;
69
+ now: () => Date;
70
+ /**
71
+ * `redactAgentArguments(args, tool.redact)`, passed in so this module runs
72
+ * exactly one redaction rule and defines none.
73
+ */
74
+ redact(args: Record<string, unknown>): Record<string, unknown>;
75
+ /**
76
+ * Called once, only for a record this call created, and **never awaited**: a
77
+ * channel that is down must not fail the call or lose the persisted record.
78
+ * Implementations report their own failures; see {@link notifyApprovers}.
79
+ */
80
+ notify(request: AgentApprovalRequest): void;
81
+ }
82
+ /**
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.
88
+ */
89
+ export declare function notifyApprovers(notify: (request: AgentApprovalRequest) => void | Promise<void>): (request: AgentApprovalRequest) => void;
90
+ /**
91
+ * Scope and approval, in that order — a caller learns a tool needs approval only
92
+ * once its token could invoke it, so an unauthorized probe cannot map which
93
+ * tools are approval-gated. `approvalsConfigured` is synchronous because
94
+ * `tools/list` asks it: with a queue an approval-gated tool *is* callable (the
95
+ * call queues) and belongs in the catalogue; without one, listing it invites a refusal.
96
+ */
97
+ export declare function gateToolCall(tool: DerivedAgentTool, abilities: readonly string[], options?: ScopeGateOptions): GateVerdict;
98
+ /**
99
+ * The approval half (RFC 0016 §5.4 item 4). One lookup on tool + *raw* arguments'
100
+ * fingerprint + principal: a pending or rejected match refuses without a second
101
+ * record or notification (polling by re-calling would page approvers per poll);
102
+ * a rejection blocks only while its record is live. Consumed *before* dispatch,
103
+ * one attempt not one success: else concurrent calls pass and a crash is replayable.
104
+ */
105
+ export declare function gateApproval(tool: DerivedAgentTool, args: Record<string, unknown>, context: ApprovalGateContext): Promise<GateVerdict>;
106
+ /**
107
+ * The scope half alone — what `guren.preflight` checks before rehearsing a call
108
+ * (RFC 0016 §5.4). Checking requires the *same* scope as calling, or the
109
+ * companion becomes a probe of tools the token cannot call. Approval is not
110
+ * applied: a rehearsal executes nothing, and approval gates an ability rather
111
+ * than knowledge; never reaching {@link gateApproval}, it files and pages nothing.
112
+ */
113
+ export declare function gatePreflight(tool: DerivedAgentTool, abilities: readonly string[], options?: ScopeGateOptions): GateVerdict;
114
+ /** The two fields the scope grammar judges a tool by. */
115
+ export declare function scopedShape(tool: DerivedAgentTool): {
116
+ name: string;
117
+ readOnly: boolean;
118
+ };
@@ -0,0 +1,234 @@
1
+ /**
2
+ * The invocation pipeline (RFC 0017 §1): scope gate → interposition → approval
3
+ * gate → dispatch → redact → audit, in one protocol-neutral place. `app.fetch`
4
+ * alone only executes, so a surface dispatching without these would bypass
5
+ * scopes, approvals and the trail while looking exactly like a gated call.
6
+ * One function with option hooks, not a middleware chain (RFC 0017 Open
7
+ * Question 1): a chain would publish an ordering vocabulary, and the ordering
8
+ * is the part that must not be negotiable. Nothing here imports an MCP type;
9
+ * the result is a union each adapter maps onto its own shapes.
10
+ */
11
+ import type { ExecutionContext } from 'hono';
12
+ import { type AgentApprovalRequest, type AgentApprovalStore } from './approval.js';
13
+ import type { AgentAuditEmitter } from './audit-emitter.js';
14
+ import type { DerivedAgentTool } from './derive.js';
15
+ import { type ToolCallOutcome } from './dispatch.js';
16
+ import { type AgentPrincipal, type AgentSurface, type AgentToolDenialReason } from './events.js';
17
+ import { type ApprovalGateContext } from './gate.js';
18
+ /**
19
+ * What the audit hooks need from a tool: its name, and the redaction rules its
20
+ * arguments are recorded under. Narrower than {@link DerivedAgentTool} because
21
+ * one audited call has no route behind it: a `guren.preflight` invocation is
22
+ * recorded under the meta-tool's name with the *checked* tool's `redact` list,
23
+ * the meta-tool's own being empty.
24
+ */
25
+ export interface AuditedTool {
26
+ toolName: string;
27
+ redact?: readonly string[];
28
+ }
29
+ /**
30
+ * What the pipeline hands to `app.fetch`. Structural rather than
31
+ * `Application`, so the pipeline stays a leaf of the agent layer and a test
32
+ * can drive it with a bare `fetch`.
33
+ */
34
+ export interface AgentDispatchTarget {
35
+ fetch(request: Request, env?: unknown, executionCtx?: ExecutionContext): Promise<Response>;
36
+ }
37
+ /** A refusal, in the one shape every surface renders. */
38
+ export interface AgentInvocationDenial {
39
+ reason: AgentToolDenialReason;
40
+ message: string;
41
+ /**
42
+ * A machine-readable body riding alongside the message. Only the approval
43
+ * refusals carry one — a caller told "this is pending" needs the id to poll
44
+ * with (see {@link GateVerdict}).
45
+ */
46
+ body?: Record<string, unknown>;
47
+ }
48
+ /**
49
+ * What one call through the pipeline came to. Three variants, because a
50
+ * dispatch that *threw* is not one that answered: it is audited as an
51
+ * invocation, but the caller has no response to map, only a message.
52
+ * Collapsing it into `executed` would make every adapter invent an outcome,
53
+ * and they would invent different ones.
54
+ */
55
+ export type AgentInvocationResult =
56
+ /** The request reached (or was refused by) the application. */
57
+ {
58
+ status: 'executed';
59
+ outcome: ToolCallOutcome;
60
+ }
61
+ /** A gate or the interposition hook refused before any HTTP happened. */
62
+ | {
63
+ status: 'denied';
64
+ denial: AgentInvocationDenial;
65
+ }
66
+ /** The dispatch itself broke. Audited as a 500 invocation. */
67
+ | {
68
+ status: 'failed';
69
+ message: string;
70
+ };
71
+ /** The call the interposition hook is asked about. */
72
+ export interface InterposedAgentCall {
73
+ tool: DerivedAgentTool;
74
+ args: Record<string, unknown>;
75
+ /** True for a rehearsal (`guren.preflight`), which executes nothing. */
76
+ preflight: boolean;
77
+ }
78
+ /**
79
+ * The one seam a surface may put its own check in, **after the scope gate and
80
+ * before the approval gate**: after scope so an unauthorized prober cannot
81
+ * drain a budget on ungranted calls, before approval because that gate writes
82
+ * a record and notifies humans, deduplicating only on *identical* arguments —
83
+ * a caller varying one field files unbounded requests. A denial dispatches nothing.
84
+ */
85
+ export type AgentInterposition = (call: InterposedAgentCall) => AgentInvocationDenial | undefined | Promise<AgentInvocationDenial | undefined>;
86
+ /**
87
+ * Everything the pipeline needs that is settled once per caller, not per call.
88
+ */
89
+ export interface AgentInvocationOptions {
90
+ /** The application the dispatched request re-enters. */
91
+ app: AgentDispatchTarget;
92
+ /**
93
+ * Who is calling. **Resolved by the caller**, never by the pipeline: how a
94
+ * principal is established is the surface's business (a verified bearer, an
95
+ * OAuth grant presented over a seam, a registered durable agent), and a
96
+ * pipeline that guessed would be a second authentication rule.
97
+ */
98
+ principal: AgentPrincipal | null;
99
+ /** The scope grammar's input — the abilities the scope gate judges by. */
100
+ abilities: readonly string[];
101
+ /**
102
+ * Which surface this is, for the audit trail. Caller-supplied and never
103
+ * invented: the trail's whole value is that a record says where a call came
104
+ * from, and a default would make the commonest surface absorb every one that
105
+ * forgot to say.
106
+ */
107
+ surface: AgentSurface;
108
+ /**
109
+ * Where invocations and denials are recorded. Undefined records nothing —
110
+ * the call still works, exactly as an application with no audit sink
111
+ * configured behaves today.
112
+ */
113
+ audit?: AgentAuditEmitter;
114
+ /**
115
+ * The approval queue (RFC 0016 §5.4 item 4). Absent, a tool declaring
116
+ * `approval: 'required'` is refused **fail-closed**: nothing is dispatched
117
+ * and the denial is audited, so an unconfigured queue never looks like a
118
+ * working one. `redact` takes the tool as well as the arguments, one context
119
+ * serving every tool with each route's own masking rules.
120
+ */
121
+ approvals?: Omit<ApprovalGateContext, 'redact'> & {
122
+ redact(tool: DerivedAgentTool, args: Record<string, unknown>): Record<string, unknown>;
123
+ };
124
+ /**
125
+ * How *this* surface configures an approval queue, named in the fail-closed
126
+ * refusal. See {@link import('./gate').ScopeGateOptions.configureHint}.
127
+ */
128
+ approvalConfigureHint?: string;
129
+ /**
130
+ * What a scope refusal calls the thing whose scopes fell short —
131
+ * `"The token's scopes"` on a bearer surface. Defaults to the neutral
132
+ * {@link DEFAULT_SCOPE_SUBJECT}, because a durable agent's principal is
133
+ * minted from its registration and holds no token anyone could widen.
134
+ */
135
+ scopeSubject?: string;
136
+ /** The one interposition seam. See {@link AgentInterposition}. */
137
+ interpose?: AgentInterposition;
138
+ /**
139
+ * Origin the synthesized request is built on, so host-authorization
140
+ * middleware sees the real Host the caller reached this surface on.
141
+ */
142
+ origin?: string;
143
+ /**
144
+ * `Authorization` to forward verbatim, for a surface whose credential the
145
+ * application's own guards can verify. **Mutually exclusive with
146
+ * {@link handoff}, and enforced**: setting both puts two answers to "who is
147
+ * this" on one request, which guard-resolution order would then settle
148
+ * rather than anything the surface said, so the factory throws.
149
+ */
150
+ authorization?: string;
151
+ /**
152
+ * `'seam'` installs {@link AgentInvocationOptions.principal} on the exact
153
+ * `Request` handed to `app.fetch`, so `requireAuthenticated()`,
154
+ * `Controller.auth` and `Gate` answer for it (RFC 0017 §2). Not a token:
155
+ * `createBearerTokenMiddleware` and `tokenCan*` judge one and there is none,
156
+ * so a route behind those refuses. Omitted, nothing is installed.
157
+ */
158
+ handoff?: 'seam';
159
+ /** Forwarded to `app.fetch` — D1/R2 bindings on Workers (RFC 0016 §3.1). */
160
+ env?: unknown;
161
+ /** Forwarded to `app.fetch` — `waitUntil` on Workers. */
162
+ executionCtx?: ExecutionContext;
163
+ }
164
+ /**
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.
170
+ */
171
+ export declare function createAgentApprovalContext(config: {
172
+ store: AgentApprovalStore;
173
+ notify: (request: AgentApprovalRequest) => void | Promise<void>;
174
+ ttlMs?: number;
175
+ } | undefined, principal: AgentPrincipal | null): NonNullable<AgentInvocationOptions['approvals']> | undefined;
176
+ /** What {@link createAgentAuditRecorder} needs, settled once per caller. */
177
+ export interface AgentAuditRecorderOptions {
178
+ audit?: AgentAuditEmitter;
179
+ principal: AgentPrincipal | null;
180
+ surface: AgentSurface;
181
+ }
182
+ /** The two records a surface writes. See {@link createAgentAuditRecorder}. */
183
+ export interface AgentAuditRecorder {
184
+ invoked(audited: AuditedTool, args: Record<string, unknown>, status: number, durationMs: number): void;
185
+ denied(audited: AuditedTool, args: Record<string, unknown>, reason: AgentToolDenialReason): void;
186
+ }
187
+ /**
188
+ * How a call is written down: principal, surface, and argument masking.
189
+ *
190
+ * Exported because a durable agent's approval-status check reaches the store
191
+ * without dispatching a tool (RFC 0017 §5), and a second copy of this rule is
192
+ * how one surface records an argument the other masks.
193
+ */
194
+ export declare function createAgentAuditRecorder(options: AgentAuditRecorderOptions): AgentAuditRecorder;
195
+ /** One call, as the pipeline is asked to run it. */
196
+ export interface AgentInvocation {
197
+ /** The tool the request is built from. */
198
+ tool: DerivedAgentTool;
199
+ /** The arguments the request is built from. */
200
+ args: Record<string, unknown>;
201
+ /**
202
+ * Ask the route for a verdict instead of an execution (RFC 0016 §5.4). The
203
+ * scope half still runs — checking a tool requires the same scope as calling
204
+ * it — but the **approval gate is skipped**: an approval-gated tool is the
205
+ * one a caller most needs to rehearse, and a rehearsal executes nothing.
206
+ */
207
+ preflight?: boolean;
208
+ /**
209
+ * 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
+ * the meta-tool's name, the checked tool's redaction rules.
212
+ */
213
+ audited?: AuditedTool;
214
+ /**
215
+ * The arguments written down, when they are not {@link args}. Separate
216
+ * because the preflight path dispatches the *checked* tool's input while
217
+ * recording the *meta-tool's* own arguments, so the record shows what the
218
+ * agent actually asked. Collapsing the two silently changes what an audit
219
+ * trail says a caller passed.
220
+ */
221
+ auditedArguments?: Record<string, unknown>;
222
+ }
223
+ /** What {@link createAgentInvocationPipeline} returns. */
224
+ export interface AgentInvocationPipeline {
225
+ invoke(call: AgentInvocation): Promise<AgentInvocationResult>;
226
+ }
227
+ /**
228
+ * Build the pipeline for one caller. A factory because everything in
229
+ * {@link AgentInvocationOptions} is settled per caller and read per call — the
230
+ * principal an approval binds to, the abilities the gate judges by, the surface
231
+ * the trail records — and hoisting any of it would carry whichever caller
232
+ * arrived first.
233
+ */
234
+ export declare function createAgentInvocationPipeline(options: AgentInvocationOptions): AgentInvocationPipeline;
@@ -54,6 +54,38 @@ export interface ScopedTool {
54
54
  * (`tools:`, `tools:.*`, `tools:*.store`): both mean "grants no tool", on purpose.
55
55
  */
56
56
  export declare function parseToolScope(entry: string): ParsedToolScope | null;
57
+ /**
58
+ * The scope forms a **registration** may declare (RFC 0017 §3): the narrower
59
+ * half of the grammar above, because a registration grants an *unattended*
60
+ * principal and is outlived by the route graph, so a set grant would acquire
61
+ * consent to tools that did not yet exist. One rule, shared with `guren check`.
62
+ */
63
+ export type RegistrationScopeVerdict =
64
+ /** The entry is a legal registration scope. */
65
+ {
66
+ allowed: true;
67
+ scope: Extract<ParsedToolScope, {
68
+ kind: 'tool';
69
+ } | {
70
+ kind: 'read';
71
+ }>;
72
+ }
73
+ /**
74
+ * The entry may not be registered. `message` states the reason and the fix,
75
+ * and is what both the plugin's throw and the check's finding say — so a
76
+ * developer reads the same sentence whichever surface catches it first.
77
+ */
78
+ | {
79
+ allowed: false;
80
+ reason: 'wildcard' | 'prefix' | 'not-a-tool-scope';
81
+ message: string;
82
+ };
83
+ /**
84
+ * Judge one `scopes` entry of an agent registration.
85
+ *
86
+ * @param entry The scope as written in the config.
87
+ */
88
+ export declare function classifyRegistrationScope(entry: string): RegistrationScopeVerdict;
57
89
  /**
58
90
  * Whether a token's abilities grant a tool. Any one entry suffices — scopes
59
91
  * are additive, and there is no deny form.
@@ -0,0 +1,49 @@
1
+ import type { Session } from '../http/middleware/index.js';
2
+ import type { InstalledAgentPrincipal } from '../internal/agent-principal.js';
3
+ import type { AuthCredentials, Guard, UserProvider } from './types.js';
4
+ export interface AgentPrincipalGuardOptions<User = unknown> {
5
+ /** The principal the invocation pipeline installed on this request. */
6
+ installed: InstalledAgentPrincipal;
7
+ /**
8
+ * Resolves a `kind: 'user'` principal's id to a full user record, the same
9
+ * provider `useTokens({ provider })` names. Without one the guard still
10
+ * authenticates: `user()` resolves to a minimal `{ id }` record so
11
+ * Gate/policy evaluation (which keys on `id`) works out of the box — the
12
+ * shape `TokenGuard` returns for a token with no provider configured.
13
+ */
14
+ provider?: UserProvider<User>;
15
+ }
16
+ /**
17
+ * The guard answering for a principal the pipeline installed (RFC 0017 §2), for
18
+ * an **unqualified** lookup on a seam-marked request; explicit `guard('web')` /
19
+ * `guard('token')` is untouched, and `guardNames()` never lists this one. It
20
+ * satisfies `requireAuthenticated()`, `Controller.auth` and `Gate`, but not
21
+ * `createBearerTokenMiddleware` / `tokenCan*`, which judge an `ApiToken`.
22
+ */
23
+ export declare class AgentPrincipalGuard<User = unknown> implements Guard<User> {
24
+ private readonly installed;
25
+ private readonly provider?;
26
+ private resolvedUser?;
27
+ constructor(options: AgentPrincipalGuardOptions<User>);
28
+ /**
29
+ * `user() !== null`, the predicate `TokenGuard` answers `check()` with: true
30
+ * in every case but one, a `kind: 'user'` principal a configured provider
31
+ * cannot resolve. Answering true there would admit a request whose
32
+ * `Controller.auth.userOrFail()` then throws.
33
+ */
34
+ check(): Promise<boolean>;
35
+ guest(): Promise<boolean>;
36
+ /**
37
+ * `kind: 'service'` is always the minimal `{ id }`: a service principal names
38
+ * no user, so a lookup would resolve an id in a table it does not belong to.
39
+ * `kind: 'user'` goes through the provider when one is configured.
40
+ */
41
+ user<T = User>(): Promise<T | null>;
42
+ id(): Promise<unknown>;
43
+ login(): Promise<void>;
44
+ attempt(_credentials: AuthCredentials, _remember?: boolean): Promise<boolean>;
45
+ validate(_credentials: AuthCredentials): Promise<User | null>;
46
+ /** Nothing to end: no session, and no stored credential to revoke. */
47
+ logout(): Promise<void>;
48
+ session<T extends Session = Session>(): T | undefined;
49
+ }
@@ -28,11 +28,11 @@ export declare class AuthManager implements AuthManagerContract {
28
28
  setDefaultGuard(name: string): void;
29
29
  getDefaultGuard(): string;
30
30
  /**
31
- * The guard name an unqualified `auth.guard()` / `auth.user()` call resolves
32
- * to for this request. Explicit names always win; otherwise a registered
33
- * token guard is selected when the request carries a Bearer Authorization
34
- * header, falling back to the default (session) guard — the composite-guard
35
- * rule from RFC 0016.
31
+ * The guard an unqualified `auth.guard()` / `auth.user()` resolves to.
32
+ * Explicit names win; otherwise a principal the pipeline installed on this
33
+ * exact request answers first, then a token guard for a Bearer header, then
34
+ * the default — RFC 0016's composite rule with RFC 0017 §2's seam in front,
35
+ * so a header cannot win over an identity the framework itself established.
36
36
  */
37
37
  resolveGuardName(ctx: Context, name?: string): string;
38
38
  createAuthContext(ctx: Context, options?: AttachContextOptions): AuthContext;
@@ -1,2 +1,2 @@
1
- import { $ as buildTokenUrl, A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureStringCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, d as completePasswordReset, et as generateId, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as secureCompare, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as NodeHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as hashToken, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, q as revokeApiToken, r as completeEmailVerification, rt as parseTokenUrl, s as requireVerifiedEmail, st as BaseUserProvider, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, ut as ScryptHasher, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-CbdPH4Cd.js";
1
+ import { $ as buildTokenUrl, A as verifyOAuthState, B as getApiToken, C as createGoogleOAuthProviderConfig, D as fetchOAuthUserProfile, E as exchangeOAuthCode, F as TokenGuard, G as readBearerToken, H as getUserApiTokens, I as API_TOKEN_KEY, J as tokenCan, K as revokeAllApiTokens, L as MemoryApiTokenStore, O as parseOAuthRedirectUrl, P as AuthManager, Q as SessionGuard, R as createApiToken, S as createGitHubOAuthProviderConfig, T as createOAuthState, V as getApiTokenOrFail, W as parseApiToken, X as tokenCanAny, Y as tokenCanAll, Z as verifyApiToken, _ as OAUTH_SESSION_BINDING_KEY, a as isEmailVerified, at as secureStringCompare, b as buildOAuthRedirectUrl, c as verifyEmailToken, ct as NodeHasher, d as completePasswordReset, dt as BaseUserProvider, et as generateId, f as createPasswordResetToken, g as MemoryOAuthStateStore, h as AuthenticatableModel, i as createEmailVerificationToken, it as secureCompare, k as sanitizeOAuthRedirect, l as MemoryPasswordResetStore, lt as ScryptHasher, m as verifyPasswordResetToken, n as buildVerificationUrl, nt as hashToken, o as parseVerificationUrl, ot as ModelUserProvider, p as parsePasswordResetUrl, q as revokeApiToken, r as completeEmailVerification, rt as parseTokenUrl, s as requireVerifiedEmail, t as MemoryEmailVerificationStore, tt as generateToken, u as buildPasswordResetUrl, v as OAuthManager, w as createOAuthManager, x as createDiscordOAuthProviderConfig, y as buildOAuthAuthorizeUrl, z as createBearerTokenMiddleware } from "../auth-Gg54ppQi.js";
2
2
  export { API_TOKEN_KEY, AuthManager, AuthenticatableModel, BaseUserProvider, MemoryApiTokenStore, MemoryEmailVerificationStore, MemoryOAuthStateStore, MemoryPasswordResetStore, ModelUserProvider, NodeHasher, OAUTH_SESSION_BINDING_KEY, OAuthManager, ScryptHasher, SessionGuard, TokenGuard, buildOAuthAuthorizeUrl, buildOAuthRedirectUrl, buildPasswordResetUrl, buildTokenUrl, buildVerificationUrl, completeEmailVerification, completePasswordReset, createApiToken, createBearerTokenMiddleware, createDiscordOAuthProviderConfig, createEmailVerificationToken, createGitHubOAuthProviderConfig, createGoogleOAuthProviderConfig, createOAuthManager, createOAuthState, createPasswordResetToken, exchangeOAuthCode, fetchOAuthUserProfile, generateId, generateToken, getApiToken, getApiTokenOrFail, getUserApiTokens, hashToken, isEmailVerified, parseApiToken, parseOAuthRedirectUrl, parsePasswordResetUrl, parseTokenUrl, parseVerificationUrl, readBearerToken, requireVerifiedEmail, revokeAllApiTokens, revokeApiToken, sanitizeOAuthRedirect, secureCompare, secureStringCompare, tokenCan, tokenCanAll, tokenCanAny, verifyApiToken, verifyEmailToken, verifyOAuthState, verifyPasswordResetToken };