@guren/server 2.13.0 → 2.15.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 (68) hide show
  1. package/dist/{Hash-CzrwKeDp.js → Hash-C8aejmi8.js} +5 -0
  2. package/dist/{McpServiceProvider-D6D9nhgn.js → McpServiceProvider-BawsYjgN.js} +72 -0
  3. package/dist/agent/AgentApprovalRequested.d.ts +59 -0
  4. package/dist/agent/approval.d.ts +295 -0
  5. package/dist/agent/audit-emitter.d.ts +64 -0
  6. package/dist/agent/audit.d.ts +103 -0
  7. package/dist/agent/derive.d.ts +155 -0
  8. package/dist/agent/dispatch.d.ts +165 -0
  9. package/dist/agent/events.d.ts +80 -0
  10. package/dist/agent/meta-tools.d.ts +62 -0
  11. package/dist/agent/public.d.ts +33 -0
  12. package/dist/agent/public.js +2 -0
  13. package/dist/agent/redact.d.ts +55 -0
  14. package/dist/agent/scopes.d.ts +115 -0
  15. package/dist/auth/AuthManager.d.ts +64 -0
  16. package/dist/auth/RequestAuthContext.d.ts +3 -5
  17. package/dist/auth/TokenGuard.d.ts +61 -0
  18. package/dist/auth/api-token.d.ts +25 -5
  19. package/dist/auth/context.d.ts +24 -0
  20. package/dist/auth/index.d.ts +5 -2
  21. package/dist/auth/index.js +2 -2
  22. package/dist/auth/password/DefaultHasher.d.ts +18 -5
  23. package/dist/auth/password/PasswordHasher.d.ts +15 -0
  24. package/dist/auth/password/hash-format.d.ts +19 -0
  25. package/dist/auth/providers/UserProvider.d.ts +7 -0
  26. package/dist/auth/types.d.ts +6 -0
  27. package/dist/{auth-C7sVmYgc.js → auth-DkYoAPVn.js} +431 -151
  28. package/dist/authorization/index.js +1 -1
  29. package/dist/authorization/middleware.d.ts +28 -1
  30. package/dist/{authorization-Dbcuc5ZK.js → authorization-CdfbCj8J.js} +119 -12
  31. package/dist/broadcasting/index.js +1 -1
  32. package/dist/{broadcasting-Dw-FhyjN.js → broadcasting-BwodCA4q.js} +2 -45
  33. package/dist/container/bindings.d.ts +19 -0
  34. package/dist/context-DoD0c7J_.js +26 -0
  35. package/dist/dispatch-erOS9epZ.js +285 -0
  36. package/dist/encryption/index.js +2 -2
  37. package/dist/{encryption-DJtkkhiw.js → encryption-D99Vmls3.js} +4 -1
  38. package/dist/http/dev-assets.d.ts +16 -0
  39. package/dist/http/middleware/auth.d.ts +2 -2
  40. package/dist/http/middleware/capabilities.d.ts +57 -0
  41. package/dist/http/middleware/csrf.d.ts +3 -0
  42. package/dist/http/public-assets.d.ts +10 -0
  43. package/dist/http/request.d.ts +139 -3
  44. package/dist/http/static-documents.d.ts +31 -0
  45. package/dist/index.d.ts +21 -4
  46. package/dist/index.js +1302 -118
  47. package/dist/internal/agent-preflight.d.ts +28 -0
  48. package/dist/internal/request.d.ts +25 -0
  49. package/dist/internal/request.js +2 -0
  50. package/dist/internal/route-path.d.ts +28 -0
  51. package/dist/internal/route-path.js +33 -0
  52. package/dist/internal/zod-compat.d.ts +201 -0
  53. package/dist/internal/zod-compat.js +193 -0
  54. package/dist/internal/zod-json-schema.d.ts +102 -0
  55. package/dist/internal/zod-json-schema.js +461 -0
  56. package/dist/logging/channels/DailyFileChannel.d.ts +0 -2
  57. package/dist/logging/daily-file-path.d.ts +24 -0
  58. package/dist/logging/index.d.ts +1 -0
  59. package/dist/logging/index.js +2 -2
  60. package/dist/{logging-CPaRMuPP.js → logging-B-kngi3q.js} +61 -18
  61. package/dist/mcp/create-mcp-server.d.ts +29 -0
  62. package/dist/mcp/index.js +1 -1
  63. package/dist/mvc/Controller.d.ts +20 -0
  64. package/dist/mvc/Router.d.ts +53 -0
  65. package/dist/request-CVQwpu2J.js +129 -0
  66. package/dist/runtime/index.js +94 -15
  67. package/dist/{vite-manifest-gdONBsM3.js → vite-manifest-w_RSOvQW.js} +1 -1
  68. package/package.json +22 -2
@@ -91,6 +91,8 @@ async function verifyPassword(password, hash) {
91
91
  }
92
92
  const salt = Buffer.from(saltB64, "base64");
93
93
  const expectedHash = Buffer.from(hashB64, "base64");
94
+ if (salt.length === 0 || expectedHash.length === 0) throw new Error("Invalid password hash format.");
95
+ if (!isPositiveInteger(params.N) || !isPositiveInteger(params.r) || !isPositiveInteger(params.p ?? 1)) throw new Error("Invalid password hash format.");
94
96
  const derived = await scryptAsync(password, salt, expectedHash.length, {
95
97
  N: params.N,
96
98
  r: params.r,
@@ -98,6 +100,9 @@ async function verifyPassword(password, hash) {
98
100
  });
99
101
  return timingSafeEqual(derived, expectedHash);
100
102
  }
103
+ function isPositiveInteger(value) {
104
+ return Number.isInteger(value) && value > 0;
105
+ }
101
106
  /**
102
107
  * Check if a password needs to be rehashed (parameters changed).
103
108
  */
@@ -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,59 @@
1
+ /**
2
+ * The notification an application sends its approvers when an agent tool call
3
+ * becomes a pending approval request (RFC 0016 §5.4 item 4).
4
+ *
5
+ * A ready-made {@link Notification} rather than a message the adapter composes,
6
+ * so "notify approvers through the existing notifications system" is one line
7
+ * in an application's configuration:
8
+ *
9
+ * ```typescript
10
+ * mcpPlugin({
11
+ * approvals: {
12
+ * store,
13
+ * notify: (request) => notifications.sendToMany(admins, new AgentApprovalRequested(request)),
14
+ * },
15
+ * })
16
+ * ```
17
+ *
18
+ * **Who the approvers are is never the framework's decision**, which is why
19
+ * this class takes a request and not a recipient. The plugin hands the request
20
+ * over; the application picks who hears about it, over which channels, with
21
+ * whatever escalation it already has. An adapter that chose recipients would be
22
+ * choosing them from a list it cannot see.
23
+ *
24
+ * Deliberately in its own module, and deliberately not imported by
25
+ * `approval.ts`: the store interface and its derivations stay declaration-only
26
+ * and free of the notifications subsystem, so a runtime that never notifies
27
+ * never pulls it into the graph.
28
+ *
29
+ * Not queued (`shouldQueue` stays false). An approval request is answered by a
30
+ * human in the next few minutes or it expires, and a queue worker that is
31
+ * behind — or absent, which is the common case in the small deployments this
32
+ * endpoint targets — turns "notify approvers" into "notify approvers
33
+ * eventually", after the window closed.
34
+ */
35
+ import { Notification } from '../notifications/Notification.js';
36
+ import type { Notifiable, NotificationMailMessage, SlackMessage } from '../notifications/types.js';
37
+ import type { AgentApprovalRequest } from './approval.js';
38
+ export declare class AgentApprovalRequested extends Notification {
39
+ readonly request: AgentApprovalRequest;
40
+ constructor(request: AgentApprovalRequest);
41
+ /**
42
+ * Mail and database by default — the two channels an application configures
43
+ * first, and the pair that covers "tell someone now" and "there is a list of
44
+ * things waiting". An application overrides by subclassing, exactly as it
45
+ * would for any other notification.
46
+ */
47
+ via(_notifiable: Notifiable): string[];
48
+ toMail(_notifiable: Notifiable): NotificationMailMessage;
49
+ /**
50
+ * The record's own fields, minus the fingerprint.
51
+ *
52
+ * The fingerprint is a hash of the *raw* arguments (see `approval.ts`), and
53
+ * a database notification is read by more people, and kept longer, than the
54
+ * approval store itself. It decides nothing an approver looks at: the
55
+ * arguments they judge are `input`, already masked.
56
+ */
57
+ toDatabase(_notifiable: Notifiable): Record<string, unknown>;
58
+ toSlack(_notifiable: Notifiable): SlackMessage;
59
+ }
@@ -0,0 +1,295 @@
1
+ /**
2
+ * The agent approval queue (RFC 0016 §5.4 item 4): a tool declaring
3
+ * `approval: 'required'` does not execute on request. The call becomes a
4
+ * pending record, approvers are notified, and only a *human* decision turns
5
+ * that record into permission for one later call.
6
+ *
7
+ * Declarations and pure derivation only, exactly as {@link file://./audit.ts}
8
+ * beside it. Nothing here opens a database, reads a clock, or sends a
9
+ * notification — every function that needs the instant takes it as an
10
+ * argument, because this module is reachable from every runtime the framework
11
+ * targets and because a rule that timestamped itself could not be pinned by a
12
+ * test. *Where* records live is the application's decision, made once through
13
+ * {@link AgentApprovalStore}; this module only says what one looks like and
14
+ * what makes one usable.
15
+ *
16
+ * **Redaction is the emitter's contract, and nothing here may re-run it.**
17
+ * {@link AgentApprovalRequest.input} arrives having already been through
18
+ * `redactAgentArguments`, the same contract `events.ts` and `audit.ts` state:
19
+ * a record is shown to a human approver and is persisted, so it carries the
20
+ * masked copy. Masking again here would install a second, quieter redaction
21
+ * rule beside the real one, and nothing reading a record could tell which of
22
+ * them produced a mask it is looking at.
23
+ *
24
+ * That contract is exactly why the *fingerprint* is computed from the **raw**
25
+ * arguments instead (see {@link agentApprovalFingerprint}). Binding an
26
+ * approval to the redacted copy would make approving
27
+ * `users.setPassword {id: 5, password: '…'}` authorize the same call with a
28
+ * different password, since the two redact to the same object — the hole the
29
+ * argument-binding rule exists to close.
30
+ */
31
+ import type { AgentPrincipal } from './events.js';
32
+ /**
33
+ * How long a pending request stays answerable by default: one hour.
34
+ *
35
+ * An approval is permission for one call *now*, not a standing grant. The
36
+ * default is short for the reason the single-use rule exists — an approval
37
+ * granted last month must not let a call through today — and an application
38
+ * that wants longer says so.
39
+ */
40
+ export declare const DEFAULT_AGENT_APPROVAL_TTL_MS: number;
41
+ /**
42
+ * The configuration key an adapter reads the queue out of, as a value.
43
+ *
44
+ * `guren check` fails a route declaring `approval: 'required'` in an app whose
45
+ * `mcpPlugin({ … })` call carries no queue, and it finds that call by looking
46
+ * for this key. The CLI cannot import `@guren/plugin-mcp` — it does not depend
47
+ * on it, and an app that never installs App MCP is still checked — so without
48
+ * this constant the check would restate the string and the two would drift:
49
+ * renaming the option would leave the check passing every app, silently. Same
50
+ * rule, two readers, as {@link file://./meta-tools.ts}.
51
+ */
52
+ export declare const AGENT_APPROVAL_CONFIG_KEY = "approvals";
53
+ /**
54
+ * What a request is waiting for, or what happened to it.
55
+ *
56
+ * `'expired'` is a *stored* status only for a store that sweeps; the framework
57
+ * never depends on one having done so — {@link agentApprovalStatusAt} derives
58
+ * expiry from `expiresAt` against a clock, so a store that never sweeps and one
59
+ * that sweeps hourly answer the same question the same way.
60
+ */
61
+ export type AgentApprovalStatus = 'pending' | 'approved' | 'rejected' | 'expired';
62
+ /** One pending, answered, or spent approval request. */
63
+ export interface AgentApprovalRequest {
64
+ /** Opaque identity, quoted back to the caller so it can poll. */
65
+ id: string;
66
+ /** The tool the call addressed, by its catalogue name. */
67
+ tool: string;
68
+ /**
69
+ * The call's arguments **already redacted** — see the module header. Shown
70
+ * to the approver and persisted; never what the match is computed from.
71
+ */
72
+ input: Record<string, unknown>;
73
+ /**
74
+ * {@link agentApprovalFingerprint} of the *raw* arguments. The record
75
+ * carries the hash and never the canonical string: an approval store holding
76
+ * a reversible copy of every argument an agent ever passed would be a second
77
+ * place secrets live, and the redaction above exists precisely so the first
78
+ * one does not.
79
+ */
80
+ fingerprint: string;
81
+ /** Who asked. `null` for a surface with no verified principal. */
82
+ principal: AgentPrincipal | null;
83
+ /**
84
+ * {@link agentApprovalPrincipalKey} of `principal`, denormalized so a store
85
+ * can index the match without knowing how the key is derived.
86
+ */
87
+ principalKey: string;
88
+ /** ISO 8601, UTC. */
89
+ requestedAt: string;
90
+ /** ISO 8601, UTC. Past this instant the record authorizes nothing. */
91
+ expiresAt: string;
92
+ status: AgentApprovalStatus;
93
+ /** ISO 8601, UTC — when a human answered. Absent while pending. */
94
+ resolvedAt?: string;
95
+ /**
96
+ * Who answered, in whatever vocabulary the application approves in (a user
97
+ * id, an email, a console operator's name). The framework never interprets
98
+ * it; it exists so the audit answer to "who let this through" is in the
99
+ * record rather than only in the approval UI's own logs.
100
+ */
101
+ resolvedBy?: string;
102
+ /** ISO 8601, UTC — when the approval was spent. Set by `consume`. */
103
+ consumedAt?: string;
104
+ }
105
+ /** The three fields that identify *this* call for the store's lookup. */
106
+ export interface AgentApprovalMatch {
107
+ tool: string;
108
+ fingerprint: string;
109
+ principalKey: string;
110
+ }
111
+ /**
112
+ * Where pending approvals live. The application implements it; the framework
113
+ * ships no default, for the reason the audit sink ships none: the runtimes
114
+ * this endpoint serves include Workers and Lambda, and a queue that silently
115
+ * degraded to process memory there would answer "approved" for a record the
116
+ * next isolate has never heard of. An unconfigured queue refuses visibly
117
+ * instead (`gateToolCall`'s fail-closed refusal names the configuration line).
118
+ *
119
+ * Four methods, each one the gate actually reaches for. Deliberately no
120
+ * `list`, `approve`, or `reject`: resolving a request is a human action taken
121
+ * through the application's own interface, over the application's own storage,
122
+ * and a framework interface for it would be a second way to write records that
123
+ * nothing here reads.
124
+ */
125
+ export interface AgentApprovalStore {
126
+ /** Persist a new pending request. */
127
+ create(request: AgentApprovalRequest): Promise<void>;
128
+ /**
129
+ * The request with this id, or `null`. Backs `guren.approval_status`.
130
+ *
131
+ * Takes no principal: the caller-scoping rule is applied by the framework
132
+ * (see {@link agentApprovalVisibleTo}), not by the store, because a store
133
+ * that forgot to filter would leak other principals' pending actions and
134
+ * nothing would fail.
135
+ */
136
+ find(id: string): Promise<AgentApprovalRequest | null>;
137
+ /**
138
+ * The **unconsumed** record matching this exact call, or `null`. When more
139
+ * than one matches, the most recently requested.
140
+ *
141
+ * Deliberately not "the approved one": the gate needs to see a *pending*
142
+ * match too, or an agent that polls by re-calling the tool creates an
143
+ * unbounded number of records and notifies approvers once per poll. It needs
144
+ * to see a *rejected* one for the same reason. Expiry is not filtered here
145
+ * either — see {@link agentApprovalUsableAt}.
146
+ */
147
+ findMatch(match: AgentApprovalMatch): Promise<AgentApprovalRequest | null>;
148
+ /**
149
+ * Spend the approval with this id, returning whether *this* call won it.
150
+ *
151
+ * Must be a compare-and-set: set `consumedAt` only if it is not already set,
152
+ * and answer `false` when it was. Two concurrent calls will find the same
153
+ * approved record — an approval is permission for one call, and a `consume`
154
+ * implemented as an unconditional write hands it to both. The gate treats
155
+ * `false` as "no approval", not as an error, and falls through to creating a
156
+ * new pending record.
157
+ */
158
+ consume(id: string): Promise<boolean>;
159
+ }
160
+ /**
161
+ * A stable key for "the same caller".
162
+ *
163
+ * Kind and id only: a token's *abilities* are not part of the identity,
164
+ * because a token rotated or re-scoped between the approval and the call is
165
+ * still the same principal, and an approval a human granted should not
166
+ * evaporate because an unrelated ability was added. The scope gate has already
167
+ * run by the time this key is used, so the call's own authority is checked
168
+ * regardless.
169
+ *
170
+ * The id's type is part of the key. `id: 5` and `id: '5'` are different
171
+ * principals to every store that distinguishes them, and collapsing the two
172
+ * here would let a service token named `"5"` spend a user 5 approval.
173
+ */
174
+ export declare function agentApprovalPrincipalKey(principal: AgentPrincipal | null): string;
175
+ /**
176
+ * The canonical text of one call's arguments — the *only* rule for deciding
177
+ * that two calls are the same call.
178
+ *
179
+ * One function, two readers: {@link agentApprovalFingerprint} hashes it when a
180
+ * record is created and again when a call looks one up. A second
181
+ * serialization is how approving `posts.destroy {id: 5}` comes to authorize
182
+ * `{id: 9}` — the failure this whole binding exists to prevent — and it would
183
+ * do it silently, because both sides would still produce *a* string.
184
+ *
185
+ * What it normalizes: object key order, at every depth. `{a: 1, b: 2}` and
186
+ * `{b: 2, a: 1}` are the same call, nested or not.
187
+ *
188
+ * What it deliberately does **not** normalize, because each would make two
189
+ * genuinely different calls match:
190
+ *
191
+ * - **Types.** `{id: 5}` and `{id: '5'}` are different calls. A route that
192
+ * coerces them to the same value is coercing *after* the gate; the approver
193
+ * saw one of the two written down.
194
+ * - **Array order.** Order is meaning in a JSON array (`ids: [1, 2]` vs
195
+ * `[2, 1]` may be the same call to one route and not to another) and the
196
+ * framework cannot know which.
197
+ * - **Absent vs. explicitly null.** A dropped key and `null` are different
198
+ * inputs to a schema with a default.
199
+ * - Unicode form, number spelling beyond what JSON already fixes, or
200
+ * whitespace inside strings.
201
+ *
202
+ * Total over JSON, and deliberately *not* total over everything else: a value
203
+ * JSON cannot carry throws rather than serializing to a placeholder. A
204
+ * placeholder would make two distinct inputs canonicalize identically, which
205
+ * is the one failure mode worse than refusing — and refusing is safe here,
206
+ * because the gate turns a throw into a fail-closed refusal. Arguments reach
207
+ * this function parsed from JSON-RPC, so no such value can occur in practice;
208
+ * the rule is written down for the surface that one day passes one.
209
+ */
210
+ export declare function canonicalizeAgentApprovalInput(input: Record<string, unknown>): string;
211
+ /**
212
+ * The fingerprint an approval is bound to: SHA-256 of
213
+ * {@link canonicalizeAgentApprovalInput}, hex.
214
+ *
215
+ * Hashed rather than stored verbatim because the record persists and is shown
216
+ * to a human, while these are the **raw** arguments — the ones the record's
217
+ * own `input` field is redacted precisely to keep out of storage. The hash
218
+ * binds the approval without keeping the secret.
219
+ *
220
+ * Async because `crypto.subtle` is: it is the one digest available unchanged
221
+ * on every runtime the framework targets (Bun, Node, Workers), and the gate is
222
+ * async already.
223
+ */
224
+ export declare function agentApprovalFingerprint(input: Record<string, unknown>): Promise<string>;
225
+ /** What {@link buildAgentApprovalRequest} needs beyond the clock. */
226
+ export interface AgentApprovalRequestInput {
227
+ tool: string;
228
+ /** Already redacted — see the module header. */
229
+ input: Record<string, unknown>;
230
+ /** From {@link agentApprovalFingerprint}, over the *raw* arguments. */
231
+ fingerprint: string;
232
+ principal: AgentPrincipal | null;
233
+ /** Defaults to {@link DEFAULT_AGENT_APPROVAL_TTL_MS}. */
234
+ ttlMs?: number;
235
+ }
236
+ /**
237
+ * Derive a new pending record.
238
+ *
239
+ * `now` is a parameter for the reason `toAuditRecord`'s is: the caller that
240
+ * creates a record also decides whether an existing one has expired, and two
241
+ * clock reads can disagree — a record stamped a millisecond after the instant
242
+ * its own expiry was measured against.
243
+ *
244
+ * The id comes from `crypto.randomUUID()` rather than a parameter, which is
245
+ * not the same compromise: an id needs no seam to be testable, since the
246
+ * caller reads it straight off the returned record, and threading one in from
247
+ * every call site would invite two of them to generate ids differently.
248
+ */
249
+ export declare function buildAgentApprovalRequest(request: AgentApprovalRequestInput, now: Date): AgentApprovalRequest;
250
+ /**
251
+ * Whether a record has passed its expiry at `now`.
252
+ *
253
+ * An unparseable `expiresAt` counts as expired. The alternative — treating a
254
+ * date the framework cannot read as "not expired yet" — is a store bug that
255
+ * fails open into a permanent approval, and this is the one direction of error
256
+ * that cannot be noticed from the outside.
257
+ */
258
+ export declare function agentApprovalExpiredAt(request: AgentApprovalRequest, now: Date): boolean;
259
+ /**
260
+ * The record's status as of `now`, with expiry applied.
261
+ *
262
+ * Expiry is derived here rather than filtered by the store on purpose: a store
263
+ * that judged it would be a second copy of the rule, and the copy that fails
264
+ * open — a store that forgets to compare, or compares in local time, hands out
265
+ * an approval granted last month and nothing anywhere reports it. A resolved
266
+ * record keeps its resolution: a rejection does not become an expiry, and an
267
+ * approval that was already spent is reported by `consumedAt`, not by this.
268
+ */
269
+ export declare function agentApprovalStatusAt(request: AgentApprovalRequest, now: Date): AgentApprovalStatus;
270
+ /**
271
+ * Whether this record authorizes a call at `now`: approved, unexpired, and
272
+ * not already spent.
273
+ *
274
+ * All three are checked here, in framework code, rather than trusted to the
275
+ * store's query — see {@link AgentApprovalStore.findMatch}. `consumedAt` is
276
+ * checked even though `findMatch` promises unconsumed records, because the
277
+ * single-use guarantee must not rest on an application's SQL: the *atomic*
278
+ * half of it is `consume`'s compare-and-set, and this is the cheap half.
279
+ */
280
+ export declare function agentApprovalUsableAt(request: AgentApprovalRequest, now: Date): boolean;
281
+ /**
282
+ * Whether `principal` may be told anything at all about `request`.
283
+ *
284
+ * The scope rule of `guren.approval_status` (RFC 0016 §5.4): a caller reads
285
+ * the status only of a request it created. Without it the tool is a way to
286
+ * enumerate other principals' pending actions — an agent could walk ids and
287
+ * learn what a colleague is waiting to have approved, which is both the
288
+ * content of the request and the fact that it exists.
289
+ *
290
+ * A record this returns `false` for must be answered *exactly* as an unknown
291
+ * id is. Any difference between the two answers — a distinct message, a
292
+ * different error shape, a slower path — is the enumeration the rule forbids,
293
+ * reintroduced.
294
+ */
295
+ export declare function agentApprovalVisibleTo(request: AgentApprovalRequest, principal: AgentPrincipal | null): boolean;
@@ -0,0 +1,64 @@
1
+ /**
2
+ * The one place an agent audit event is announced: to the configured sink, and
3
+ * to the application's event listeners.
4
+ *
5
+ * Here rather than in a protocol adapter because it has two readers and will
6
+ * grow more. `@guren/plugin-mcp` builds one at boot and binds it into the
7
+ * container; `guren tool:call` resolves that binding and records the `'cli'`
8
+ * surface through the very same function. A second copy is how one surface
9
+ * comes to swallow a sink failure the other warns about, or to keep calling a
10
+ * sink as an event listener after the other stopped — and the evidence of
11
+ * either would be a trail that is quietly missing a surface.
12
+ *
13
+ * Its own module so it can be exercised without an endpoint. The alternative
14
+ * is a closure inside the plugin's `boot`, reachable only by standing up a
15
+ * server and making a real tool call — which is worth doing once, and is the
16
+ * wrong price for the several cases that matter here (a sink that throws, a
17
+ * sink beside a listener that throws, a sink with no event manager at all).
18
+ */
19
+ import type { AgentToolDenied, AgentToolInvoked } from './events.js';
20
+ import type { EventManager } from '../events/index.js';
21
+ import { type AgentAuditRecord } from './audit.js';
22
+ /**
23
+ * The container service an application's audit emitter is published under
24
+ * (`ServiceBindings['agent.audit']`).
25
+ *
26
+ * A constant rather than a literal at each site, because this is the first
27
+ * binding written by one package and read by another that cannot import it:
28
+ * `@guren/plugin-mcp` binds it, `@guren/cli` resolves it, and neither depends
29
+ * on the other. Two literals that drifted would break the wiring *silently* —
30
+ * the CLI would resolve nothing and record nothing, which reads exactly like
31
+ * an application that configured no trail. That is the one failure this
32
+ * feature exists to prevent, so it may not be spelled twice.
33
+ */
34
+ export declare const AGENT_AUDIT_BINDING = "agent.audit";
35
+ /** What an application hands each audit event to. */
36
+ export type AgentAuditSink = (record: AgentAuditRecord) => void | Promise<void>;
37
+ /**
38
+ * What every agent surface calls to record one invocation or one denial.
39
+ *
40
+ * Named because it is a container binding (`'agent.audit'`) as well as a return
41
+ * value: a caller resolving it has to be able to say what it expects to find.
42
+ */
43
+ export type AgentAuditEmitter = (event: AgentToolInvoked | AgentToolDenied) => void;
44
+ /**
45
+ * Build the function a surface calls for every invocation and denial.
46
+ *
47
+ * **The sink is called directly, not subscribed as a listener**, and that is
48
+ * the whole reason this function exists rather than an `events.on(...)` pair.
49
+ * `EventManager.emit` awaits its listeners in priority order inside a bare
50
+ * `for` loop, so the first one to throw ends the loop and every listener after
51
+ * it never runs. An unrelated application listener registered at a higher
52
+ * priority would then silence the audit trail, and the only evidence an
53
+ * operator would have of that is an empty file. A record of what agents did
54
+ * cannot be contingent on what else the application happens to listen for.
55
+ *
56
+ * The events are still emitted, unchanged, for every consumer that
57
+ * legitimately is a listener — RFC 0016 §5.2's "forward them wherever you
58
+ * already forward events" is untouched.
59
+ *
60
+ * Neither half may fail the tool call it is recording, so both are caught. The
61
+ * sink's failure is *warned* rather than swallowed: an audit sink dropping
62
+ * records in silence is precisely the failure this feature exists to prevent.
63
+ */
64
+ export declare function createAuditEmitter(sink: AgentAuditSink | undefined, events: EventManager | undefined, now?: () => Date): AgentAuditEmitter;
@@ -0,0 +1,103 @@
1
+ /**
2
+ * The agent audit record (RFC 0016 §5.2): one invocation or one denial, in the
3
+ * one shape a sink writes as a line and `guren tool:log` reads back.
4
+ *
5
+ * Declarations and pure derivation only. Nothing here opens a file or reads a
6
+ * clock — {@link toAuditRecord} takes the instant as an argument — because
7
+ * this module is reachable from every runtime the framework targets, including
8
+ * the ones with no filesystem, and because a record builder that timestamped
9
+ * itself could not be pinned by a test. *Where* records go is a sink's
10
+ * decision, made once by the application (`@guren/plugin-mcp`'s `audit`
11
+ * option); this module only says what one looks like.
12
+ *
13
+ * **Redaction is the emitter's contract, and nothing here may re-run it.**
14
+ * `AgentToolInvoked.arguments` arrives having already been through
15
+ * `redactAgentArguments`, exactly as `events.ts` states, and this module
16
+ * carries it across verbatim. Masking again here would install a second,
17
+ * quieter redaction rule beside the real one — the two would drift, and
18
+ * nothing reading a record could tell which of them produced a mask it is
19
+ * looking at. That is the reasoning `events.ts` used to refuse redacting on
20
+ * construction, and it holds one layer down without change. A sink that wants
21
+ * different masking changes the route's `.agent({ redact })`, which is the
22
+ * one place the rule lives.
23
+ */
24
+ import type { AgentPrincipal, AgentSurface, AgentToolDenialReason, AgentToolDenied, AgentToolInvoked } from './events.js';
25
+ /**
26
+ * Where an application's audit trail is written by default, relative to the
27
+ * app root. `storage/logs/` is the convention `LogManager`'s own examples
28
+ * already use, so an audit trail lands beside the application log rather than
29
+ * inventing a second place to look.
30
+ */
31
+ export declare const DEFAULT_AGENT_AUDIT_PATH = "storage/logs/agent-audit.log";
32
+ /** What every audit record carries, whatever its outcome. */
33
+ interface AgentAuditRecordBase {
34
+ /** ISO 8601, in UTC — the instant the record was made. */
35
+ ts: string;
36
+ surface: AgentSurface;
37
+ tool: string;
38
+ principal: AgentPrincipal | null;
39
+ /** Already redacted by the emitter; see the module header. */
40
+ arguments: Record<string, unknown>;
41
+ }
42
+ /**
43
+ * A tool that ran. `status` and `durationMs` exist here and nowhere else:
44
+ * a denial refuses before any HTTP happens, so there is no status it could
45
+ * honestly report (RFC 0016 §5.2, as amended).
46
+ */
47
+ export interface AgentAuditInvokedRecord extends AgentAuditRecordBase {
48
+ outcome: 'invoked';
49
+ status: number;
50
+ durationMs: number;
51
+ }
52
+ /** A tool call the adapter refused before it reached the application. */
53
+ export interface AgentAuditDeniedRecord extends AgentAuditRecordBase {
54
+ outcome: 'denied';
55
+ reason: AgentToolDenialReason;
56
+ }
57
+ /**
58
+ * One line of the audit trail.
59
+ *
60
+ * A union rather than one interface with optional fields, so a record with a
61
+ * `reason` *and* a `status` cannot be written down: the two outcomes disagree
62
+ * about what happened, and a shape that admits both would let a sink emit that
63
+ * contradiction and a reader believe it.
64
+ */
65
+ export type AgentAuditRecord = AgentAuditInvokedRecord | AgentAuditDeniedRecord;
66
+ /**
67
+ * Derive the record for one audit event.
68
+ *
69
+ * `now` is a parameter rather than a `Date.now()` inside: the sink writing
70
+ * this record also picks the dated file it lands in, and two clock reads can
71
+ * disagree across a midnight boundary — a record stamped just before it,
72
+ * filed just after. One read, used for both.
73
+ *
74
+ * The two events are told apart structurally, not with `instanceof`. The event
75
+ * classes cross a package boundary that this repo resolves twice — `@guren/cli`
76
+ * and the plugins reach `@guren/server` through its `dist`, a test inside
77
+ * `packages/server` through `src` — so an `instanceof` here would answer
78
+ * `false` for a genuine event constructed on the other side of that seam, and
79
+ * would do it by mislabelling the record rather than by failing.
80
+ */
81
+ export declare function toAuditRecord(event: AgentToolInvoked | AgentToolDenied, now: Date): AgentAuditRecord;
82
+ /**
83
+ * Read one line of an audit file back, or `null` if it is not a record.
84
+ *
85
+ * The one parser on the read side. A caller that hand-rolled a second would be
86
+ * the reader half of the drift this whole feature is built to avoid, and would
87
+ * be the half that fails silently: a record it stops recognising reads as an
88
+ * empty trail.
89
+ *
90
+ * Returning `null` rather than throwing is what makes the reader usable
91
+ * against a file that is being appended to right now. The last line of such a
92
+ * file is routinely a *partial* record — an append is not atomic — and a blank
93
+ * line is what a file ends with. Neither is corruption, and neither should
94
+ * take down a command whose whole job is to show what the earlier lines say.
95
+ *
96
+ * Extra keys are ignored, deliberately: the file sink writes through
97
+ * `DailyFileChannel`, whose JSON format wraps the record in a log envelope
98
+ * (`timestamp`, `level`, `message`). Tolerating that envelope is what lets the
99
+ * sink reuse the channel's rotation and retention instead of reimplementing
100
+ * both, and the record's own fields are unambiguous beside it.
101
+ */
102
+ export declare function parseAuditRecord(line: string): AgentAuditRecord | null;
103
+ export {};