@guren/server 2.12.0 → 2.14.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 (45) hide show
  1. package/dist/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
  2. package/dist/agent/derive.d.ts +155 -0
  3. package/dist/agent/dispatch.d.ts +123 -0
  4. package/dist/agent/events.d.ts +80 -0
  5. package/dist/agent/redact.d.ts +55 -0
  6. package/dist/agent/scopes.d.ts +115 -0
  7. package/dist/auth/AuthManager.d.ts +64 -0
  8. package/dist/auth/RequestAuthContext.d.ts +3 -5
  9. package/dist/auth/TokenGuard.d.ts +61 -0
  10. package/dist/auth/api-token.d.ts +25 -5
  11. package/dist/auth/context.d.ts +24 -0
  12. package/dist/auth/index.d.ts +5 -2
  13. package/dist/auth/index.js +2 -2
  14. package/dist/auth/providers/UserProvider.d.ts +7 -0
  15. package/dist/auth/types.d.ts +6 -0
  16. package/dist/{auth-C7sVmYgc.js → auth-BSUc14CD.js} +313 -122
  17. package/dist/authorization/index.js +1 -1
  18. package/dist/authorization/middleware.d.ts +28 -1
  19. package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
  20. package/dist/broadcasting/index.js +1 -1
  21. package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BxU-LIfF.js} +2 -45
  22. package/dist/context-DoD0c7J_.js +26 -0
  23. package/dist/http/middleware/auth.d.ts +2 -2
  24. package/dist/http/middleware/capabilities.d.ts +57 -0
  25. package/dist/http/middleware/csrf.d.ts +3 -0
  26. package/dist/http/request.d.ts +51 -2
  27. package/dist/index.d.ts +12 -3
  28. package/dist/index.js +1015 -84
  29. package/dist/internal/agent-preflight.d.ts +28 -0
  30. package/dist/internal/request.d.ts +19 -0
  31. package/dist/internal/request.js +2 -0
  32. package/dist/internal/route-path.d.ts +28 -0
  33. package/dist/internal/route-path.js +33 -0
  34. package/dist/internal/zod-compat.d.ts +201 -0
  35. package/dist/internal/zod-compat.js +193 -0
  36. package/dist/internal/zod-json-schema.d.ts +102 -0
  37. package/dist/internal/zod-json-schema.js +461 -0
  38. package/dist/mcp/create-mcp-server.d.ts +29 -0
  39. package/dist/mcp/index.js +1 -1
  40. package/dist/mvc/Controller.d.ts +46 -0
  41. package/dist/mvc/Router.d.ts +53 -0
  42. package/dist/request-CRVuIiQr.js +78 -0
  43. package/dist/runtime/index.js +5 -2
  44. package/dist/{vite-manifest-BKuV1kfv.js → vite-manifest-BGfWbPYp.js} +1 -1
  45. package/package.json +17 -1
@@ -4,6 +4,35 @@ import { n as createMcpAccessGuard, r as isMcpEndpointEnabled, t as MCP_ENDPOINT
4
4
  import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
5
5
  import { z } from "zod";
6
6
  //#region src/mcp/create-mcp-server.ts
7
+ function isAgentRoute(route) {
8
+ if (!route || typeof route !== "object") return false;
9
+ const { agent, method, path } = route;
10
+ return typeof method === "string" && typeof path === "string" && typeof agent === "object" && agent !== null;
11
+ }
12
+ /**
13
+ * One tool as an agent editing the app should see it. Annotations are
14
+ * reported **as declared**, with no defaults filled in: the derivation layer
15
+ * owns the GET/QUERY → readOnlyHint rule, and restating it here would be a
16
+ * second copy of it that can disagree.
17
+ */
18
+ function describeAgentRoute(route) {
19
+ const { agent } = route;
20
+ return {
21
+ toolName: agent.toolName ?? route.name,
22
+ routeName: route.name,
23
+ method: route.method,
24
+ path: route.path,
25
+ description: agent.description ?? route.description ?? route.summary,
26
+ expose: agent.expose,
27
+ annotations: {
28
+ readOnlyHint: agent.readOnlyHint,
29
+ destructiveHint: agent.destructiveHint,
30
+ idempotentHint: agent.idempotentHint
31
+ },
32
+ approval: agent.approval ?? "not-required",
33
+ authorization: route.authorization
34
+ };
35
+ }
7
36
  function createMcpServer(options) {
8
37
  const { cwd, cli, version = "0.2.0" } = options;
9
38
  const server = new McpServer({
@@ -59,6 +88,39 @@ function createMcpServer(options) {
59
88
  }] };
60
89
  });
61
90
  }
91
+ server.tool("guren_agent_surface", "The app's agent-facing tool surface (RFC 0016): every route that declares agent metadata, with its tool name, method and path, description, exposed surfaces, MCP annotations as declared, and whether invocations need approval. Call it BEFORE editing a route or its controller to find out whether an autonomous agent can already invoke it — renaming such a route renames a tool, and loosening its authorization loosens the tool's.", {}, async () => {
92
+ if (!cli.CONTEXT_ROUTE_FEATURES?.includes("agent")) return { content: [{
93
+ type: "text",
94
+ text: JSON.stringify({
95
+ supported: false,
96
+ reason: "The @guren/cli installed in this app predates agent route metadata, so the agent surface cannot be read. This is not the same as the app exposing no tools — the answer is unknown. Upgrade @guren/cli (bunx guren upgrade) to query it."
97
+ }, null, 2)
98
+ }] };
99
+ const loadErrors = [];
100
+ let routes;
101
+ if (cli.loadContextRoutes) routes = await cli.loadContextRoutes(cwd, void 0, loadErrors);
102
+ else {
103
+ const context = await cli.generateContext({ cwd });
104
+ routes = context.routes;
105
+ if (context.routesError) loadErrors.push(context.routesError);
106
+ }
107
+ const tools = routes.filter(isAgentRoute).map(describeAgentRoute);
108
+ const payload = loadErrors.length > 0 ? {
109
+ supported: true,
110
+ routesLoaded: false,
111
+ loadErrors,
112
+ note: "The route graph failed to load, so this list is incomplete — it is not evidence that the app exposes no agent tools.",
113
+ tools
114
+ } : {
115
+ supported: true,
116
+ routesLoaded: true,
117
+ tools
118
+ };
119
+ return { content: [{
120
+ type: "text",
121
+ text: JSON.stringify(payload, null, 2)
122
+ }] };
123
+ });
62
124
  server.tool("guren_check", "Validate route-to-controller-to-page consistency, check for empty controller methods, missing test files, and missing generated manifests.", {}, async () => {
63
125
  const report = await cli.runCheck({ cwd });
64
126
  return { content: [{
@@ -195,6 +257,16 @@ function createMcpServer(options) {
195
257
  await run([".guren/pages.gen.ts"], () => cli.generatePageTypes(options));
196
258
  const data = await run([".guren/data.gen.ts"], () => cli.generateDataTypes(options));
197
259
  await run([".guren/channels.gen.ts"], () => cli.generateChannelTypes(options));
260
+ if (cli.generateAgentTypes) {
261
+ const generateAgentTypes = cli.generateAgentTypes.bind(cli);
262
+ await run([".guren/agents.gen.ts"], () => {
263
+ if (!routes?.definitions) throw new Error("route generation produced no manifest to derive agent tools from");
264
+ return generateAgentTypes(routes.definitions, {
265
+ ...options,
266
+ resources: data?.definitions
267
+ });
268
+ });
269
+ }
198
270
  await run([".guren/api-client.gen.ts"], () => {
199
271
  if (!routes?.definitions) throw new Error("route generation produced no manifest to build a client from");
200
272
  return cli.generateApiClientTypes(routes.definitions, {
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Turns registered route definitions into agent tools (RFC 0016 §2).
3
+ *
4
+ * This is the *one* derivation. The runtime protocol adapters and the CLI's
5
+ * `.guren/agents.gen.ts` both call it, so a generated manifest and a live MCP
6
+ * server can differ only in description richness — never in schemas, names, or
7
+ * exposure. Nothing here is restated by hand: the input schema comes from the
8
+ * route's own `params`/`query`/`body` contracts through the shared Zod → JSON
9
+ * Schema walker, the output schema from `output`, the ability from the
10
+ * authorization capability its middleware chain stamped.
11
+ *
12
+ * Two properties this function keeps deliberately:
13
+ *
14
+ * - **Total.** Nothing throws and nothing is silently dropped for being
15
+ * malformed. A contract this cannot express becomes a warning plus a
16
+ * deterministic result, because the same call has to serve a dev server, a
17
+ * codegen step, and a production adapter. `guren check` is what turns those
18
+ * warnings into a failing build (PR-1c).
19
+ * - **Opt-in.** A route becomes a tool only by declaring `.agent()` *and*
20
+ * carrying a name. Auto-exposing endpoints is the anti-pattern RFC 0016
21
+ * opens by rejecting.
22
+ */
23
+ import type { ResourceResponseShape, RouteDefinition } from '../mvc/Router.js';
24
+ import { type JsonSchemaObject } from '../internal/zod-json-schema.js';
25
+ /**
26
+ * A JSON Schema 2020-12 object as an agent tool advertises it. An alias of the
27
+ * shared walker's type rather than a second definition — OpenAPI 3.1's Schema
28
+ * Object is the same dialect, and `@guren/openapi` aliases it the same way, so
29
+ * one definition serves every surface. The name exists so the internal module
30
+ * is not the one a consumer has to import.
31
+ */
32
+ export type AgentToolSchema = JsonSchemaObject;
33
+ /**
34
+ * MCP `ToolAnnotations`, resolved to explicit values — a consumer never has to
35
+ * re-apply a default, and `guren check`'s annotation-honesty rule has one
36
+ * concrete claim to check the controller against.
37
+ *
38
+ * These are hints for client UX, not enforcement. Authorization lives in
39
+ * policies, scopes, and the approval queue.
40
+ */
41
+ export interface DerivedAgentToolAnnotations {
42
+ /** The tool does not modify its environment. */
43
+ readOnlyHint: boolean;
44
+ /** The tool may perform destructive updates. Meaningful only when not read-only. */
45
+ destructiveHint: boolean;
46
+ /** Repeat calls with the same arguments have no additional effect. */
47
+ idempotentHint: boolean;
48
+ }
49
+ /** Protocol surfaces a tool appears on. Both resolved; unset means exposed. */
50
+ export interface DerivedAgentToolExposure {
51
+ mcp: boolean;
52
+ webMcp: boolean;
53
+ }
54
+ export interface DerivedAgentTool {
55
+ /** Tool identity: `agent.toolName` when given, otherwise the route name, verbatim. */
56
+ toolName: string;
57
+ /** The route name this tool was derived from. Equal to `toolName` unless overridden. */
58
+ routeName: string;
59
+ /** Uppercased HTTP method the tool dispatches to. */
60
+ method: string;
61
+ /** Route path pattern, `:param` tokens intact. */
62
+ path: string;
63
+ /**
64
+ * `agent.description`, else the route's OpenAPI `description`, else its
65
+ * `summary`. Absent when the route declares none — nothing is invented here;
66
+ * the CLI appends resource type text at codegen time, and `guren check`
67
+ * warns about a tool with no description at all.
68
+ */
69
+ description?: string;
70
+ /** Merged `params` + `query` + `body`, object root (MCP requires one). */
71
+ inputSchema: AgentToolSchema;
72
+ /**
73
+ * Which contract each advertised input property came from — the inverse of
74
+ * the merge, for the adapter that has to take a flat tool call apart again
75
+ * and rebuild the HTTP request: `params`/`path` substitute into the URL
76
+ * path, `query` joins the query string, `body` lands in the JSON body. The
77
+ * schema alone cannot answer this (the merge is flat by design), and an
78
+ * adapter guessing by method would put a POST route's `query` keys in the
79
+ * body, where `validateQuery` never looks.
80
+ */
81
+ inputSources: Record<string, AgentToolInputSource>;
82
+ /**
83
+ * True when the route's `body` schema was not an object and therefore nests
84
+ * under a single `body` property (see {@link buildInputSchema}). The
85
+ * dispatching adapter must then send `arguments.body` *as* the HTTP body,
86
+ * not an object wrapping it — the flat reconstruction would post
87
+ * `{ body: [...] }` to a route that validates an array.
88
+ */
89
+ inputBodyNested: boolean;
90
+ /** Present only when the route binds an `output` schema — the one shape validated at runtime. */
91
+ outputSchema?: AgentToolSchema;
92
+ /**
93
+ * The route's `resource` response hint, as class names — RFC 0016's second
94
+ * output rung, carried rather than resolved. `definitions()` has only the
95
+ * names; the payload type behind them exists solely in the CLI's AST
96
+ * extraction, which is why codegen enriches the description from this and
97
+ * the runtime does not.
98
+ *
99
+ * Absent when the route declares no hint — and, deliberately, whenever the
100
+ * route *declares* an `output` schema, whether or not the walker could
101
+ * render it. The declaration is what the runtime validates against, so it
102
+ * outranks the hint; carrying both would leave two descriptions of one
103
+ * response with nothing keeping them in agreement, and a route whose
104
+ * `output` the walker cannot express would advertise the *unvalidated* one
105
+ * while the enforced contract silently vanished.
106
+ */
107
+ resource?: ResourceResponseShape;
108
+ annotations: DerivedAgentToolAnnotations;
109
+ /**
110
+ * The policy ability guarding this route, when its middleware chain stamped
111
+ * one unambiguously. Absent means "not statically derivable", never "not
112
+ * authorized" — a check reads the absence, it does not assume a verdict.
113
+ */
114
+ authorization?: {
115
+ ability: string;
116
+ };
117
+ /** Declared verbatim: invocations require server-side approval. */
118
+ approval?: 'required';
119
+ /** Declared verbatim: argument fields masked in agent audit logs. */
120
+ redact?: string[];
121
+ expose: DerivedAgentToolExposure;
122
+ /**
123
+ * What could not be expressed while deriving *this* tool, unprefixed. The
124
+ * same lines appear in {@link DeriveAgentToolsResult.warnings} prefixed with
125
+ * the tool name; that aggregate is for printing, this field is for anything
126
+ * that needs to know which tool a warning belongs to. Attributing by parsing
127
+ * the prefix back off would couple every consumer to a message format
128
+ * nothing states. Empty for a tool that derived cleanly.
129
+ */
130
+ warnings: string[];
131
+ }
132
+ export interface DeriveAgentToolsResult {
133
+ tools: DerivedAgentTool[];
134
+ /**
135
+ * Everything the derivation could not express, one line each, prefixed with
136
+ * the tool (or the route, for a route that could not become one). Non-fatal
137
+ * by construction — see the module header. Per-tool lines are also on the
138
+ * tool itself ({@link DerivedAgentTool.warnings}), which is what a consumer
139
+ * needing attribution should read.
140
+ */
141
+ warnings: string[];
142
+ }
143
+ /**
144
+ * Where a merged input property came from — collision reporting inside the
145
+ * merge, request reconstruction outside it ({@link DerivedAgentTool.inputSources}).
146
+ * `params` and `path` both mean URL substitution to an adapter; they stay
147
+ * distinct because a warning should name the schema the author actually wrote.
148
+ */
149
+ export type AgentToolInputSource = 'params' | 'path' | 'query' | 'body';
150
+ /**
151
+ * Derive the agent tools a set of route definitions exposes.
152
+ *
153
+ * @param definitions Registered routes, as `Router.definitions()` hands them out.
154
+ */
155
+ export declare function deriveAgentTools(definitions: RouteDefinition[]): DeriveAgentToolsResult;
@@ -0,0 +1,123 @@
1
+ /**
2
+ * The dispatch contract (RFC 0016 §3): a tool call re-enters the application
3
+ * as a real HTTP request, so validation, policies, and middleware run exactly
4
+ * once, in the app — never re-implemented here.
5
+ *
6
+ * This module is pure request/response plumbing: it rebuilds an HTTP request
7
+ * from a flat tool call and maps the app's response onto an MCP tool result.
8
+ * It never validates arguments (the route does, and the MCP client already
9
+ * saw the JSON Schema) and never decides authorization (the gate and the
10
+ * app's policies do).
11
+ */
12
+ import type { DerivedAgentTool } from './derive.js';
13
+ export interface BuildToolRequestOptions {
14
+ /**
15
+ * Origin the synthesized URL is built on. Never leaves the process — the
16
+ * request goes straight into `app.fetch` — but host-authorization
17
+ * middleware still reads its `Host`, so the default stays on the one name
18
+ * every dev allowlist admits.
19
+ */
20
+ origin?: string;
21
+ /**
22
+ * `Authorization` header to forward verbatim, so the app's own token guard
23
+ * authenticates the same principal the adapter verified. Absent for a
24
+ * surface that authenticates some other way.
25
+ */
26
+ authorization?: string;
27
+ /**
28
+ * Ask for a verdict instead of an execution (RFC 0016 §5.4): the request
29
+ * runs the route's middleware and validates the advertised contract, then
30
+ * stops before the handler. Only routes declaring `.agent()` honour it.
31
+ */
32
+ preflight?: boolean;
33
+ }
34
+ /**
35
+ * The argument-level spelling of a preflight request (RFC 0016 §5.4), for a
36
+ * surface whose callers pass flat arguments rather than dispatch options.
37
+ *
38
+ * No adapter strips it today: MCP does not offer preflight at all (see
39
+ * `mapToolResponse` and the plugin), and the surfaces that do reach the seam
40
+ * ask through `BuildToolRequestOptions.preflight`. A surface that adopts this
41
+ * key owns the stripping — it is an instruction to the adapter, not a field of
42
+ * any route's contract, and forwarding it would fail the very validation the
43
+ * caller asked to rehearse.
44
+ */
45
+ export declare const PREFLIGHT_ARGUMENT = "_preflight";
46
+ export type BuiltToolRequest = {
47
+ request: Request;
48
+ }
49
+ /** Path parameters the call did not supply — the URL cannot be built. */
50
+ | {
51
+ missing: string[];
52
+ }
53
+ /**
54
+ * Path parameter values that are URL dot-segments (`.` / `..`). Rejected,
55
+ * never substituted: `encodeURIComponent` leaves a dot untouched, and the
56
+ * `Request` URL parser then collapses the segment — so `{ name: '..' }` on
57
+ * `/files/:name/meta` would reach `/meta`, a route the scope check never
58
+ * saw. The only ASCII segments the WHATWG parser normalizes are `.` and
59
+ * `..`; every other separator (`/`, `\`) survives `encodeURIComponent`
60
+ * percent-encoded, so this is the complete set.
61
+ */
62
+ | {
63
+ invalidPath: string[];
64
+ };
65
+ /**
66
+ * Rebuild the HTTP request a tool call describes.
67
+ *
68
+ * The flat argument object is taken apart along `tool.inputSources` — the
69
+ * derivation's own record of which contract each property came from — so a
70
+ * POST route's `query` keys land in the query string where `validateQuery`
71
+ * reads them, not in the body. Keys the derivation never advertised are
72
+ * forwarded anyway (body for body-carrying methods, query otherwise): the
73
+ * route's validator is the one place that rejects them, and dropping them
74
+ * here would make this a second, quieter validator.
75
+ *
76
+ * GET and HEAD force everything into the query string whatever its source —
77
+ * `Request` refuses a body on those methods, and a `body` schema on a GET
78
+ * route is a contract defect this adapter cannot repair.
79
+ */
80
+ export declare function buildToolRequest(tool: DerivedAgentTool, args: Record<string, unknown>, options?: BuildToolRequestOptions): BuiltToolRequest;
81
+ /** An MCP tool result, shaped for the SDK's CallToolResult. */
82
+ export interface ToolCallOutcome {
83
+ content: Array<{
84
+ type: 'text';
85
+ text: string;
86
+ }>;
87
+ structuredContent?: Record<string, unknown>;
88
+ isError?: boolean;
89
+ /** The HTTP status the dispatch resolved to, for the audit event. */
90
+ status: number;
91
+ }
92
+ /**
93
+ * Whether the tool advertises an object output schema — the only kind MCP
94
+ * lists, and therefore the only kind that obliges a success result to carry
95
+ * `structuredContent`. A route whose `output` is an array or primitive is not
96
+ * advertised as structured (MCP `outputSchema` must be an object), so its
97
+ * results ride as text. `describeTool` and `mapToolResponse` must agree on
98
+ * this exact predicate, or one advertises a schema the other cannot satisfy.
99
+ */
100
+ export declare function advertisesStructuredOutput(tool: DerivedAgentTool): boolean;
101
+ /**
102
+ * Map the application's response onto an MCP tool result (RFC 0016 §3.4).
103
+ *
104
+ * - 2xx JSON object → serialized text, plus `structuredContent` when the tool
105
+ * advertises an object `outputSchema` (the one shape the route validated).
106
+ * - 2xx Inertia page JSON → unwrapped to `page.props`, only for a tool with
107
+ * no `outputSchema` — unwrap and schema are mutually exclusive by
108
+ * derivation, so the advertised shape can never disagree with the result.
109
+ * - 204 / 3xx → a status line naming the Location; not an error.
110
+ * - 4xx / 5xx → `isError: true` carrying the exception handler's JSON body:
111
+ * a 422's `{ message, errors }` is an application-level failure the agent
112
+ * should read, not a protocol error.
113
+ * - non-JSON → capped text.
114
+ *
115
+ * One MCP invariant overrides the table: a *non-error* result for a tool that
116
+ * advertises an object `outputSchema` must carry `structuredContent`, or the
117
+ * SDK client rejects it after the route has already run. A success response
118
+ * that yields no object to put there (204, 3xx, non-JSON, a non-object body)
119
+ * contradicts the route's own declared output, so it becomes an `isError`
120
+ * result naming the mismatch — which the SDK exempts from the rule — rather
121
+ * than a protocol fault the agent cannot interpret.
122
+ */
123
+ export declare function mapToolResponse(tool: DerivedAgentTool, response: Response): Promise<ToolCallOutcome>;
@@ -0,0 +1,80 @@
1
+ /**
2
+ * The audit trail of the agent surface (RFC 0016 §5.2): every tool invocation
3
+ * and every denial, as framework events, so an application forwards them
4
+ * wherever it already forwards events instead of learning a second logging
5
+ * API.
6
+ *
7
+ * Declarations only. Nothing here emits — the dispatch path does, once, at
8
+ * the one place that knows the verdict — and nothing here redacts:
9
+ * {@link AgentToolInvoked.arguments} is a *contract* that the emitter has
10
+ * already run the arguments through `redactAgentArguments`. An event class
11
+ * that redacted on construction would give a second, quieter redaction rule
12
+ * beside the real one, and a listener has no way to tell a masked payload
13
+ * from an unmasked one.
14
+ */
15
+ import { Event } from '../events/Event.js';
16
+ /**
17
+ * Who invoked a tool (RFC 0016 §4). `kind: 'service'` is an App MCP bearer
18
+ * token with no `userId`; `'user'` is a session (WebMCP) or a user-owned
19
+ * token. `abilities` are the token's, carried for the audit record — the
20
+ * scope verdict itself was already taken by the dispatcher.
21
+ */
22
+ export interface AgentPrincipal {
23
+ kind: 'user' | 'service';
24
+ id: string | number;
25
+ abilities?: string[];
26
+ }
27
+ /**
28
+ * The protocol surface an invocation arrived on. `'mcp'` is the application's
29
+ * own MCP endpoint, `'dev-mcp'` the development one, `'cli'` a
30
+ * `guren tool:call`, `'webmcp'` an in-browser session-authenticated call.
31
+ */
32
+ export type AgentSurface = 'mcp' | 'dev-mcp' | 'cli' | 'webmcp';
33
+ /**
34
+ * Emitted when an agent tool invocation completed — successfully or not.
35
+ * `status` carries the HTTP status the dispatch resolved to, so an error
36
+ * response is one of these rather than a separate event; a call that never
37
+ * reached the handler is an {@link AgentToolDenied} instead.
38
+ */
39
+ export declare class AgentToolInvoked extends Event {
40
+ readonly principal: AgentPrincipal | null;
41
+ readonly tool: string;
42
+ readonly status: number;
43
+ readonly durationMs: number;
44
+ readonly surface: AgentSurface;
45
+ /**
46
+ * The invocation arguments **already redacted** by the emitter (see the
47
+ * module header). Assigned in the body rather than declared as a
48
+ * constructor parameter property: `arguments` is not a legal binding
49
+ * identifier in strict mode, which every ES module is, though it is a
50
+ * perfectly legal property name.
51
+ */
52
+ readonly arguments: Record<string, unknown>;
53
+ constructor(principal: AgentPrincipal | null, tool: string, redactedArguments: Record<string, unknown>, status: number, durationMs: number, surface: AgentSurface);
54
+ }
55
+ /**
56
+ * Why a tool invocation was refused before it reached the route handler.
57
+ *
58
+ * Deliberately no `'policy'`: `Gate` policies evaluate *inside* the
59
+ * dispatched request, so a policy denial is an execution that returned 403 —
60
+ * an {@link AgentToolInvoked} with that status — not an adapter-level
61
+ * refusal. The reasons here are exactly the checks the adapter runs before
62
+ * synthesizing the request, which is also why a denial carries no HTTP
63
+ * status: no HTTP happened.
64
+ */
65
+ export type AgentToolDenialReason = 'auth' | 'scope' | 'approval' | 'rate-limit';
66
+ /**
67
+ * Emitted when an agent tool invocation was refused. Carries no status or
68
+ * duration: nothing ran, and {@link AgentToolDenialReason} is the finding.
69
+ * `'approval'` covers a tool declaring `approval: 'required'` whose call
70
+ * became a pending record instead of an execution.
71
+ */
72
+ export declare class AgentToolDenied extends Event {
73
+ readonly principal: AgentPrincipal | null;
74
+ readonly tool: string;
75
+ readonly reason: AgentToolDenialReason;
76
+ readonly surface: AgentSurface;
77
+ /** Redacted by the emitter, exactly as on {@link AgentToolInvoked}. */
78
+ readonly arguments: Record<string, unknown>;
79
+ constructor(principal: AgentPrincipal | null, tool: string, redactedArguments: Record<string, unknown>, reason: AgentToolDenialReason, surface: AgentSurface);
80
+ }
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Argument masking for the agent audit trail (RFC 0016 §5.2).
3
+ *
4
+ * Agent tool arguments are logged by default, which is only safe if the
5
+ * logging path masks the fields that must not be written down. Two sources,
6
+ * unioned: a fixed list of sensitive key *fragments* every application gets
7
+ * without asking, and the route's own `.agent({ redact })` metadata.
8
+ *
9
+ * The rule is deliberately blunt — a key matches when its lowercased name
10
+ * *contains* a fragment, and that applies to the declared `redact` entries
11
+ * too, not just the built-ins. So `redact: ['id']` also masks `userId`, and
12
+ * the built-in `session` masks `sessionCount`. Over-redaction is the safe
13
+ * direction for a log: a masked field that did not need masking costs a
14
+ * debugging round trip, an unmasked credential costs a rotation.
15
+ *
16
+ * The walk is total for the same reason the derivation is: it runs while
17
+ * *recording* what happened, including a denial taken before the route's own
18
+ * validation, so it must not be the thing that throws. A cycle and a payload
19
+ * nested past {@link MAX_DEPTH} both terminate with a marker.
20
+ */
21
+ /**
22
+ * The replacement written in place of a masked value. A string, so a redacted
23
+ * record still serializes as JSON and reads the same in every sink.
24
+ */
25
+ export declare const AGENT_REDACTED = "[REDACTED]";
26
+ /**
27
+ * Written in place of a value that closes a cycle, so a self-referencing
28
+ * argument object produces a finite record instead of throwing or hanging.
29
+ * Distinct from {@link AGENT_REDACTED} on purpose: one says "we would not show
30
+ * you", the other "there is nothing further here to show".
31
+ */
32
+ export declare const AGENT_CIRCULAR = "[Circular]";
33
+ /**
34
+ * Written in place of a value nested deeper than {@link MAX_DEPTH}.
35
+ */
36
+ export declare const AGENT_TRUNCATED = "[Truncated]";
37
+ /**
38
+ * Mask the sensitive fields of an agent tool's arguments.
39
+ *
40
+ * Returns a deep copy: the input is never mutated, and a caller may keep
41
+ * holding the unredacted original. The copy is deep only through the
42
+ * structures this walks — plain objects and arrays. Anything else (a `Date`,
43
+ * a `Map`, a `Set`, a class instance) is carried across as the *same
44
+ * reference*, because copying it would need a rule per type and would still
45
+ * get the exotic cases wrong; nothing below such a value is inspected, so a
46
+ * credential hidden inside a class instance is masked only if the key holding
47
+ * that instance matches. Tool arguments arrive as parsed JSON on every
48
+ * surface, where this case does not occur; a caller synthesizing arguments in
49
+ * process is the one that can hit it.
50
+ *
51
+ * @param args The invocation arguments. Walked as a record whatever its
52
+ * prototype, so the return is always a fresh plain object.
53
+ * @param redact Extra key fragments from the route's `.agent({ redact })`.
54
+ */
55
+ export declare function redactAgentArguments(args: Record<string, unknown>, redact?: readonly string[]): Record<string, unknown>;
@@ -0,0 +1,115 @@
1
+ /**
2
+ * The scope grammar an API token's `abilities` use to reach agent tools
3
+ * (RFC 0016 §5.1).
4
+ *
5
+ * Four forms, and deliberately no more — a grammar an agent-facing consent
6
+ * screen has to render is only useful if a human can read a scope and say
7
+ * which tools it grants:
8
+ *
9
+ * - `tool:<name>` one tool, by exact name
10
+ * - `tools:read` every tool whose resolved `readOnlyHint` is true
11
+ * - `tools:*` every tool
12
+ * - `tools:<prefix>.*` every tool named `<prefix>.…`
13
+ *
14
+ * **Only `tool:` / `tools:` entries are considered.** Every other ability an
15
+ * `ApiToken` carries — including the store's default `['*']` — is ignored, so
16
+ * it matches nothing. This is the fail-closed half of a deliberate split:
17
+ *
18
+ * - A token issued before agent tools existed, for an app's own API, holds
19
+ * `['*']`. Reading that as "all agent tools" would silently hand every
20
+ * already-issued token the whole agent surface the moment an app declares
21
+ * its first `.agent()` route. Access to the agent surface is granted by an
22
+ * explicit tool scope or not at all (default deny, RFC §5.1); `tools:*` is
23
+ * the explicit way to say "everything".
24
+ * - A malformed entry is likewise ignored here rather than throwing: this
25
+ * module judges an already-issued token, and a token that cannot be parsed
26
+ * must grant less, never more. Rejecting a bad scope belongs to the
27
+ * *issuer* (`token:issue`, a later PR), which runs {@link parseToolScope}
28
+ * over what it was asked for and refuses a `null`.
29
+ *
30
+ * Matching is case-sensitive and entries are not trimmed. A stored ability
31
+ * with stray whitespace is an issuance bug; normalizing it here would make
32
+ * the judge more permissive than the issuer, which is the wrong direction.
33
+ */
34
+ /**
35
+ * The MCP tool-name grammar (SEP-986), which a `tool:` scope names and a
36
+ * `tools:<prefix>.*` scope has to stay inside — a scope that could not
37
+ * possibly name a legal tool is not a scope.
38
+ *
39
+ * `packages/cli/src/agent-route-check.ts` holds the same pattern for the
40
+ * check that fails a build over an illegal tool name. Collapsing the two onto
41
+ * this export is a later change, not this one: the CLI reaches `@guren/server`
42
+ * through `dist/`, so the collapse needs a built server and belongs with the
43
+ * PR that does the build-order work.
44
+ *
45
+ * Note what the charset gives for free: `*` is not in it, so `tool:posts.*`
46
+ * fails the test and needs no special case to be rejected.
47
+ */
48
+ export declare const AGENT_TOOL_NAME_PATTERN: RegExp;
49
+ /** One well-formed scope entry, discriminated by what it grants. */
50
+ export type ParsedToolScope =
51
+ /** `tool:<name>` — exactly the tool with this name. */
52
+ {
53
+ kind: 'tool';
54
+ name: string;
55
+ }
56
+ /** `tools:read` — every tool whose resolved `readOnlyHint` is true. */
57
+ | {
58
+ kind: 'read';
59
+ }
60
+ /** `tools:*` — every tool. */
61
+ | {
62
+ kind: 'all';
63
+ }
64
+ /** `tools:<prefix>.*` — every tool named `<prefix>.…`. `prefix` excludes the dot. */
65
+ | {
66
+ kind: 'prefix';
67
+ prefix: string;
68
+ };
69
+ /**
70
+ * The shape a tool has to present to be judged: its name, and whether it
71
+ * resolved to read-only. Deliberately not `DerivedAgentTool` — the token
72
+ * guard, the consent screen and a test fixture all supply this, and none of
73
+ * them should have to build a whole derived tool to ask a question about two
74
+ * fields. `DerivedAgentTool` is structurally compatible via
75
+ * `{ name: tool.toolName, readOnly: tool.annotations.readOnlyHint }`.
76
+ */
77
+ export interface ScopedTool {
78
+ name: string;
79
+ readOnly: boolean;
80
+ }
81
+ /**
82
+ * Parse one `abilities` entry.
83
+ *
84
+ * @returns The scope it denotes, or `null` for an entry that is not a tool
85
+ * scope at all (`'*'`, an app's own ability name) and for one that is
86
+ * malformed (`tools:`, `tools:.*`, `tools:*.store`, a prefix outside the
87
+ * tool-name grammar). Callers cannot tell those apart on purpose: both mean
88
+ * "grants no tool", and a judge that distinguished them would be inventing
89
+ * a third answer for a two-valued question.
90
+ *
91
+ * Note the two reserved `tools:` words are matched before the wildcard form,
92
+ * so a tool family literally named `read.…` is still reachable as
93
+ * `tools:read.*`, while a tool named exactly `read` is reachable only as
94
+ * `tool:read` — the reserved word wins its own spelling.
95
+ */
96
+ export declare function parseToolScope(entry: string): ParsedToolScope | null;
97
+ /**
98
+ * Whether a token's abilities grant a tool. Any one entry suffices — scopes
99
+ * are additive, and there is no deny form.
100
+ */
101
+ export declare function scopesAllowTool(abilities: readonly string[], tool: ScopedTool): boolean;
102
+ /**
103
+ * The concrete tool names a token's abilities grant, for the surfaces that
104
+ * have to show a human what a scope means: the OAuth consent screen, the
105
+ * `token:issue` confirmation, and the issuance-time lint.
106
+ *
107
+ * Literally a filter over {@link scopesAllowTool}, and it must stay one. A
108
+ * second matcher that walked entries and accumulated names is how a consent
109
+ * screen comes to list a tool the dispatcher then denies — the two answers
110
+ * have to be the same answer, not two implementations of one rule.
111
+ *
112
+ * @returns Names in the order the tools were given, so a caller controls the
113
+ * display order by ordering its input.
114
+ */
115
+ export declare function expandToolScopes(abilities: readonly string[], tools: readonly ScopedTool[]): string[];