@lumoauth/agent 0.0.0-stage → 1.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LumoAuth LLC
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,390 @@
1
- # Temporary Holding Version
1
+ # @lumoauth/agent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@lumoauth/agent.svg)](https://www.npmjs.com/package/@lumoauth/agent)
4
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
5
+
6
+ > The LumoAuth SDK for AI agents that run on Node 18 or newer. `LumoAgent`
7
+ > signs the agent in, checks permissions before it acts, asks people for
8
+ > approval, requests just-in-time permissions and gets MCP tokens.
9
+ > `AAuthClient` implements the AAuth protocol: a cryptographic agent identity
10
+ > with RFC 9421 HTTP message signatures.
11
+
12
+ This package is part of the [LumoAuth JavaScript SDK](../../README.md). Not
13
+ sure that it is the package that you need? See
14
+ [Which package do I need?](../../README.md#which-package-do-i-need).
15
+
16
+ ## Contents
17
+
18
+ - [Is this the right package?](#is-this-the-right-package)
19
+ - [Install](#install)
20
+ - [Quick start](#quick-start)
21
+ - [Configuration](#configuration)
22
+ - [Guides](#guides)
23
+ - [`LumoAgent` reference](#lumoagent-reference)
24
+ - [AAuth: cryptographic agent identity](#aauth-cryptographic-agent-identity)
25
+ - [Errors](#errors)
26
+ - [Troubleshooting](#troubleshooting)
27
+ - [Related packages](#related-packages)
28
+ - [Learn more](#learn-more)
29
+ - [License](#license)
30
+
31
+ ## Is this the right package?
32
+
33
+ | You are… | Use |
34
+ |---|---|
35
+ | Writing an agent (LangChain.js, Vercel AI SDK, your own loop) that signs in **as itself**, asks before acting, and gets a person's approval for risky actions | **This package**, `LumoAgent` |
36
+ | Building or calling an agent that needs a verifiable cryptographic identity, signed requests, or delegation between agents | **This package**, `AAuthClient` |
37
+ | Building a resource server that must verify incoming AAuth tokens | **This package**, `verifyAuthToken` |
38
+ | Starting a new agent app | [`npx create-lumo-agent`](../create-lumo-agent/README.md) |
39
+ | Writing an ordinary backend that acts for a user, not as an agent | [`@lumoauth/backend`](../backend/README.md) |
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ npm install @lumoauth/agent
45
+ ```
46
+
47
+ **This package needs Node 18 or newer.** The AAuth part uses `node:crypto`, so
48
+ the package never runs in a browser.
49
+
50
+ ## Quick start
51
+
52
+ Create the agent in the LumoAuth portal first. You need its client ID, its
53
+ client secret and your organization slug.
54
+
55
+ ```bash
56
+ export LUMOAUTH_ORG_ID=acme-corp
57
+ export AGENT_CLIENT_ID=…
58
+ export AGENT_CLIENT_SECRET=…
59
+ ```
60
+
61
+ ```ts
62
+ import { LumoAgent } from '@lumoauth/agent';
63
+
64
+ const agent = new LumoAgent(); // reads the variables above
65
+
66
+ // 1. Check first: may this agent do this, in this context?
67
+ if (!(await agent.isAllowed('document.read', { id: 'doc_99' }))) {
68
+ throw new Error('not allowed');
69
+ }
70
+
71
+ // 2. Ask a person before an action that cannot be undone. A push arrives on
72
+ // the user's phone, and the promise resolves when they answer or time runs out.
73
+ const approval = await agent.approvals.require({
74
+ taskId: 'wire-001',
75
+ reason: 'Wire $4,500 to vendor INV-7741',
76
+ impact: 'high',
77
+ onBehalfOf: 'ada@acme.com',
78
+ });
79
+ if (approval.status !== 'approved') throw new Error(`not approved: ${approval.status}`);
80
+
81
+ // 3. Get a short-lived token for a secured MCP server.
82
+ // The server ID is the MCP server's https URL. It becomes the token's `aud`.
83
+ const mcpToken = await agent.mcp.getToken('https://mcp.example.com/mcp');
84
+ ```
85
+
86
+ Sign-in is automatic. The first call runs the OAuth 2.0 client credentials
87
+ grant. The SDK refreshes the token 60 seconds before it expires.
88
+
89
+ ## Configuration
90
+
91
+ `new LumoAgent(options?)`. Every option falls back to an environment variable.
92
+
93
+ | Option | Environment variable | Default | Description |
94
+ |---|---|---|---|
95
+ | `baseUrl` | `LUMOAUTH_URL` | `https://app.lumoauth.dev` | The LumoAuth host. Use `https://eu.app.lumoauth.dev` for the EU region |
96
+ | `orgId` | `LUMOAUTH_ORG_ID` | none | The organization slug. Every namespace needs it |
97
+ | `clientId` | `AGENT_CLIENT_ID` | required | The agent's OAuth client ID |
98
+ | `clientSecret` | `AGENT_CLIENT_SECRET` | required | The agent's OAuth client secret |
99
+ | `scopes` | none | the agent's defaults | Scopes to request |
100
+ | `redirectUri` | none | none | The callback URL of the delegation consent flow |
101
+ | `timeout` | none | 30 000 ms | Request timeout |
102
+ | `fetch` | none | global `fetch` | A custom `fetch` |
103
+
104
+ The constructor throws `LumoAuthConfigError` when the client ID or the client
105
+ secret is missing. It does not call the server.
106
+
107
+ ## Guides
108
+
109
+ ### Check before acting
110
+
111
+ `ask()` returns the decision and the reason. `isAllowed()` returns only the
112
+ boolean.
113
+
114
+ ```ts
115
+ const decision = await agent.ask('tickets.write', { ticket: 'T-42' });
116
+ // decision.allowed, decision.action, decision.reason, decision.audit_id
117
+ ```
118
+
119
+ The decision comes from the agent's capabilities and the organization's
120
+ policies. The server always sets `ip`, `userAgent`, `requestMethod` and
121
+ `requestPath` in the context from the real request. Values that you send under
122
+ those names move to `pep`.
123
+
124
+ ### Ask a person for approval
125
+
126
+ ```ts
127
+ const approval = await agent.approvals.require({
128
+ taskId: 'delete-42',
129
+ reason: 'Delete 1,204 archived invoices',
130
+ impact: 'critical', // 'low' | 'medium' | 'high' | 'critical'; default 'medium'
131
+ onBehalfOf: 'ada@acme.com', // email or user ID
132
+ meta: { count: 1204 }, // shown to the user
133
+ timeoutMs: 120_000, // default 90 000
134
+ });
135
+ ```
136
+
137
+ `approval.status` is `approved`, `denied`, `expired` or `pending`. `pending`
138
+ means that the wait ended before the user answered. `approval.token` lets you
139
+ check again later with `agent.approvals.getStatus(token)` or
140
+ `agent.approvals.wait(token)`.
141
+
142
+ When the user has no enrolled push device, no prompt is sent. `require()`
143
+ then throws `LumoAuthApprovalNotDeliveredError`. It never returns
144
+ `approved` in this case. Check `err.reason`:
145
+
146
+ - `email_fallback_sent`: the server emailed the user a notice with no
147
+ approval link. There is no token, so the SDK does not poll. An unknown
148
+ user gets the same answer.
149
+ - `no_enrolled_device`: the email could not be sent either.
150
+
151
+ ```ts
152
+ import { LumoAuthApprovalNotDeliveredError } from '@lumoauth/agent';
153
+
154
+ try {
155
+ await agent.approvals.require({ taskId: 'delete-42', reason: 'Delete invoices', onBehalfOf: 'ada@acme.com' });
156
+ } catch (err) {
157
+ if (err instanceof LumoAuthApprovalNotDeliveredError) {
158
+ // Ask the user to check their email, or to enrol the LumoAuth app.
159
+ } else throw err;
160
+ }
161
+ ```
162
+
163
+ `agent.approvals.create()` sends the request without waiting. It returns
164
+ `status: 'pending'` and a `token` when a prompt was sent. Otherwise it
165
+ returns `status: 'email_fallback_sent'` and `token: null`, without throwing.
166
+
167
+ ### Request just-in-time permissions
168
+
169
+ ```ts
170
+ await agent.jit.createTask({ name: 'Analyse the Q4 report', onBehalfOf: 'ada@acme.com' });
171
+
172
+ const result = await agent.jit.requestPermission(
173
+ { type: 'file_access', actions: ['read'], identifier: 'report_q4.pdf' },
174
+ { justification: 'The user asked for Q4 revenue', ttl: 300 },
175
+ );
176
+
177
+ if (result.status === 'approved') {
178
+ const token = await agent.jit.getToken(result.request_id);
179
+ // Call the resource with `Authorization: Bearer ${token}`.
180
+ }
181
+
182
+ await agent.jit.completeTask(); // ends the task and revokes its tokens
183
+ ```
184
+
185
+ When a request needs approval, `requestPermission()` keeps polling until a
186
+ person answers. It polls every 5 seconds for up to 5 minutes; pass `waitForApproval: false` to
187
+ return at once. A JIT token lasts at most 900 seconds.
188
+
189
+ ### Act for a user
190
+
191
+ ```ts
192
+ const agent = new LumoAgent({ redirectUri: 'https://agent.example.com/callback' });
193
+
194
+ const url = agent.delegation.getConsentUrl('session-1', ['read:documents']);
195
+ // …the user consents and returns with ?code=…
196
+ await agent.delegation.handleConsentCallback('session-1', code);
197
+
198
+ const delegated = await agent.delegation.exchange('session-1', ['read:documents'], {
199
+ resource: 'https://api.example.com', // becomes the token's aud
200
+ });
201
+ ```
202
+
203
+ When you already hold the user's access token, call
204
+ `agent.delegation.setUserToken('session-1', accessToken)` instead of the
205
+ consent steps. The token types and the `resource` option are explained in the
206
+ [workspace guide](../../README.md#act-on-a-users-behalf-delegation).
207
+
208
+ ## `LumoAgent` reference
209
+
210
+ ### Properties and methods
211
+
212
+ | Member | Returns | Description |
213
+ |---|---|---|
214
+ | `authenticate(scopes?)` | `Promise<string>` | Runs the client credentials grant now. You rarely need it, because every call signs in when needed |
215
+ | `getAccessToken()` | `Promise<string>` | The current access token, refreshed when it is about to expire |
216
+ | `tokenScopes` | `string[]` | The scopes that the server granted to the current token |
217
+ | `ask(action, context?)` | `Promise<AgentAskResult>` | The full decision for an action |
218
+ | `isAllowed(action, context?)` | `Promise<boolean>` | `ask()` reduced to a boolean |
219
+ | `getCurrentAgent()` | `Promise<AgentIdentity>` | The agent's identity, capabilities and workspace |
220
+ | `capabilities()` | `Promise<string[]>` | The agent's capabilities |
221
+ | `budget()` | `Promise<AgentBudget>` | The agent's budget policy, or `{}` when none is set |
222
+ | `baseUrl`, `orgId`, `clientId` | `string` | The resolved configuration |
223
+
224
+ ### Namespaces
225
+
226
+ | Namespace | What it does | Methods |
227
+ |---|---|---|
228
+ | `agents` | Agent identity | `ask`, `isAllowed`, `me`, `getCurrentAgent`, `capabilities`, `budget`, `register` |
229
+ | `approvals` | Push approval for agent actions | `require`, `create`, `getStatus`, `wait` |
230
+ | `jit` | Just-in-time permissions | `createTask`, `requestPermission`, `getRequestStatus`, `getToken`, `evaluateTask`, `completeTask`. `listPendingRequests` is the human reviewer's view. It needs a user token with `jit:approve`, so the server rejects an agent's own token |
231
+ | `delegation` | Act for a user, or hand work to a sub-agent, with RFC 8693 token exchange | `getConsentUrl`, `handleConsentCallback`, `setUserToken`, `exchange`, `request`, `delegateToSubAgent`, `revoke`, `revokeAll`, `hasDelegation`, `activeSessions` |
232
+ | `mcp` | Token exchange for secured MCP servers | `getToken`, `getTokenDetailed`. Pass the MCP server's https URL, such as `https://mcp.example.com/mcp`. The SDK sends it as the RFC 8707 `resource`, so the token's `aud` is that URL. Any other ID throws `LumoAuthValidationError` |
233
+
234
+ The parameters of each method are in the
235
+ [workspace API reference](../../README.md#api-reference).
236
+
237
+ ## AAuth: cryptographic agent identity
238
+
239
+ AAuth gives an agent an identity that a resource server can verify without a
240
+ shared secret. The agent holds an Ed25519 or RSA key pair. It signs each
241
+ request with RFC 9421 HTTP message signatures and presents
242
+ proof-of-possession tokens. The protocol has four token requests (`auth`,
243
+ `code`, `exchange` and `refresh`), which support user consent and delegation
244
+ across several agents.
245
+
246
+ ### Set up the key
247
+
248
+ ```ts
249
+ import { generateKeypair } from '@lumoauth/agent';
250
+
251
+ const { privateKeyPem, jwks } = generateKeypair(); // Ed25519, kid "key-1"
252
+ // Store privateKeyPem in your secret manager. Register jwks with your organization.
253
+ ```
254
+
255
+ ### Agent side
256
+
257
+ ```ts
258
+ import { AAuthClient } from '@lumoauth/agent';
259
+
260
+ const aauth = new AAuthClient({
261
+ agentIdentifier: 'https://my-agent.example.com', // an HTTPS URL that names the agent
262
+ privateKeyPem: process.env.AGENT_PRIVATE_KEY!,
263
+ orgId: 'acme-corp',
264
+ });
265
+
266
+ const result = await aauth.requestAuthToken({ resourceToken, agentToken, scope: 'read write' });
267
+
268
+ if ('authorizationRequired' in result) {
269
+ // The user has to consent first. Send them to result.authorizationUri,
270
+ // then call aauth.exchangeCode({ code, redirectUri, agentToken }).
271
+ } else {
272
+ const res = await aauth.signedRequest('GET', 'https://api.example.com/v1/data', {
273
+ authToken: result.authToken,
274
+ });
275
+ }
276
+ ```
277
+
278
+ `resourceToken` is the resource token that the target resource issued to the
279
+ agent. `agentToken` is the agent's own `agent+jwt`, sent in the `Agent-Auth`
280
+ header.
281
+
282
+ ### `AAuthClient` options
283
+
284
+ | Option | Default | Description |
285
+ |---|---|---|
286
+ | `agentIdentifier` | required | The HTTPS URL that names the agent |
287
+ | `privateKeyPem` | required | A PEM Ed25519 (PKCS#8) or RSA private key |
288
+ | `baseUrl` | `LUMOAUTH_URL`, then `https://app.lumoauth.dev` | The LumoAuth host |
289
+ | `orgId` | `LUMOAUTH_ORG_ID` | The organization slug |
290
+ | `kid` | `key-1` | The key ID. It must match the registered JWKS entry |
291
+ | `fetch` | global `fetch` | A custom `fetch` |
292
+ | `timeout` | 30 000 ms | Request timeout |
293
+
294
+ ### `AAuthClient` methods
295
+
296
+ | Method | What it does |
297
+ |---|---|
298
+ | `requestAuthToken({ resourceToken, agentToken, scope?, redirectUri? })` | Requests an auth token. Returns the token, or `{ authorizationRequired: true, requestToken, authorizationUri }` when the user must consent |
299
+ | `buildConsentUrl(requestToken)` | Builds the consent URL for a pending request token |
300
+ | `exchangeCode({ code, redirectUri, agentToken })` | Exchanges the consent code for an auth token |
301
+ | `exchangeToken({ authToken, resourceToken, agentToken })` | Exchanges an upstream auth token for a downstream one, which adds to the `act` chain |
302
+ | `refresh({ refreshToken, resourceToken, scope?, agentToken })` | Refreshes an auth token. It needs a fresh resource token |
303
+ | `revoke({ token, tokenType?, agentToken })` | Revokes an auth token by its `jti`, or a refresh token by value |
304
+ | `signRequest(method, url, options?)` | Returns RFC 9421 signature headers for a request |
305
+ | `signedRequest(method, url, { authToken, data?, headers? })` | Sends a signed request with the auth token, and returns the `fetch` `Response` |
306
+ | `verifyAuthToken(token, { resource, jwks?, clockSkew?, issuer? })` | Verifies a token. The issuer defaults to this organization's issuer |
307
+ | `discoverIssuer()`, `discoverAgents()`, `discoverResource(url)` | Read the AAuth metadata documents |
308
+ | `issuer`, `publicJwk`, `publicJwkThumbprint` | The issuer URL and the agent's public key |
309
+
310
+ ### Resource-server side
311
+
312
+ ```ts
313
+ import { verifyAuthToken } from '@lumoauth/agent';
314
+
315
+ const claims = await verifyAuthToken(bearer, {
316
+ issuer: 'https://app.lumoauth.dev/orgs/acme-corp/api/v1',
317
+ resource: 'https://api.example.com', // must equal the token's aud
318
+ });
319
+ // Then check the request signature against claims.cnf.jwk.
320
+ ```
321
+
322
+ `verifyAuthToken()` fetches the issuer's keys unless you pass `jwks`. It
323
+ accepts only asymmetric algorithms, so `HS*` and `none` always fail. It allows
324
+ no clock skew on `exp` unless you set `clockSkew` in seconds. It throws
325
+ `AAuthError` when a check fails.
326
+
327
+ ### Exports
328
+
329
+ | Group | Exports |
330
+ |---|---|
331
+ | Client | `AAuthClient` |
332
+ | Keys | `generateKeypair`, `publicJwkFromPrivateKey`, `jwkThumbprint` |
333
+ | Signing primitives (RFC 9421) | `signRequest`, `buildSignatureBase`, `signatureParams`, `signSignatureBase`, `verifySignatureBase`, `contentDigestSha256`, `generateNonce`, `AAUTH_COVERED_COMPONENTS` |
334
+ | Verification | `verifyAuthToken`, `decodeJwt` |
335
+ | Errors | `AAuthError` |
336
+
337
+ The signing code is tested byte for byte against the shared test vector in
338
+ [`sdk-contract`](https://github.com/LumoAuth/sdk-contract). Signatures made
339
+ here therefore verify in the Python, Go, PHP, Java and .NET SDKs, and the
340
+ other way round.
341
+
342
+ ## Errors
343
+
344
+ This package re-exports the error classes of
345
+ [`@lumoauth/shared`](../shared/README.md#errors). The ones that agents meet
346
+ most often are:
347
+
348
+ | Class | When |
349
+ |---|---|
350
+ | `LumoAuthConfigError` | The client ID, client secret or `orgId` is missing |
351
+ | `LumoAuthApiError` | Sign-in failed: the server rejected the client credentials. `statusCode` holds the HTTP status |
352
+ | `LumoAuthAuthenticationError` | A later call got 401, for example because the agent was suspended |
353
+ | `LumoAuthPermissionDeniedError` | The server rejected the call. `requiredScopes` names a missing scope, when there is one |
354
+ | `LumoAuthRateLimitError` | Too many requests. `retryAfter` holds the wait in seconds |
355
+ | `LumoAuthApprovalDeniedError`, `LumoAuthApprovalTimeoutError` | A person declined, or nobody answered in time |
356
+ | `LumoAuthApprovalNotDeliveredError` | The approval prompt reached no device. `reason` is `email_fallback_sent` or `no_enrolled_device`, and `taskId` names the task |
357
+ | `LumoAuthBudgetExceededError` | The agent ran out of budget |
358
+ | `AAuthError` | An AAuth request or a token check failed |
359
+
360
+ ## Troubleshooting
361
+
362
+ | Symptom | Cause | Fix |
363
+ |---|---|---|
364
+ | `LumoAuthConfigError` at construction | `AGENT_CLIENT_ID` or `AGENT_CLIENT_SECRET` is not set | Set both, or pass `clientId` and `clientSecret` |
365
+ | `LumoAuthConfigError` that mentions `orgId` | `LUMOAUTH_ORG_ID` is not set | Set it, or pass `orgId` |
366
+ | 403 `test_token_not_accepted` from approvals, or 401 on a JIT route | The call used a portal test token | Use the agent's real credentials |
367
+ | 403 on `jit.listPendingRequests()` | It is the reviewer's view and needs a user token with `jit:approve` | Call it from the reviewer's app |
368
+ | `invalid_grant` from `delegation.exchange()` | The declared token type does not match, the user is no longer active, or the subject is a JIT token | Fix `subjectTokenType`, and use an active user token |
369
+ | 401 from an API with a delegated token | The token's `aud` is the agent ID | Pass `resource` to `exchange()` |
370
+ | `approvals.require()` throws `LumoAuthApprovalNotDeliveredError` | The user has no enrolled push device. With `reason` `email_fallback_sent`, the server emailed them a notice | Ask the user to enrol the LumoAuth app, then ask again |
371
+ | `mcp.getToken()` throws `LumoAuthValidationError` | The server ID is not an https URL, for example `urn:mcp:…` | Pass the MCP server's URL |
372
+
373
+ ## Related packages
374
+
375
+ | Package | How it relates |
376
+ |---|---|
377
+ | [`create-lumo-agent`](../create-lumo-agent/README.md) | Creates a complete agent app with one command |
378
+ | [`@lumoauth/backend`](../backend/README.md) | The same namespaces for a server that holds a user's token instead of agent credentials |
379
+ | [`@lumoauth/shared`](../shared/README.md) | The core that this package re-exports |
380
+ | [Workspace README](../../README.md) | How all of the packages fit together, with guides and the full API reference |
381
+
382
+ ## Learn more
383
+
384
+ - [Enable security for AI agents](https://docs.lumoauth.dev/quickstarts/ai-agent-security/)
385
+ - [AAuth quickstart](https://docs.lumoauth.dev/agents/aauth-quickstart/)
386
+ - [SDK overview](https://docs.lumoauth.dev/developer/sdks/)
387
+
388
+ ## License
389
+
390
+ [MIT](./LICENSE)