@kleora-io/core 0.0.0 → 0.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Kleora
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # `@kleora-io/core`
2
+
3
+ The code the Kleora CLI ([`@kleora-io/cli`](../cli)) and the Kleora MCP server
4
+ (`@kleora-io/mcp`) share:
5
+
6
+ - **the credential store**: the refresh token in the OS keychain (through the
7
+ optional `@napi-rs/keyring`), falling back to a mode-`0600` file under the
8
+ user's config directory. Never an environment variable, never a command-line
9
+ argument;
10
+ - **the device-grant client** (RFC 8628): start an authorization, poll for the
11
+ token, refresh it, revoke it (RFC 7009);
12
+ - **issuer discovery**: the issuer a device grant runs against is what the
13
+ deployment reports at `GET /api/v1/platform`, unless one is given explicitly;
14
+ - **the session**: one profile's credential lifecycle, with the access token
15
+ held in memory only;
16
+ - **a generic management API client**: a thin `fetch` wrapper that calls one
17
+ operation of the management API with the caller's own bearer token, with
18
+ bounded `Retry-After` handling and a cap on concurrent requests;
19
+ - **the error types** both tools throw and render, including the RFC 9457
20
+ problem document as `ApiError`.
21
+
22
+ Each tool keeps its own configuration, `User-Agent`, OAuth client, keychain
23
+ service and config directory. They share the code, never a stored credential.
24
+
25
+ This is a library for building Kleora's own local tools. If you are integrating
26
+ Kleora into an application, you want one of the SDKs instead
27
+ (`@kleora-io/node`, `@kleora-io/browser`, `@kleora-io/nuxt`); Kleora's
28
+ documentation is at https://kleora.io/en/docs.
29
+
30
+ ## Install
31
+
32
+ ```bash
33
+ npm install @kleora-io/core
34
+ ```
35
+
36
+ Node 20 or newer, ESM only.
37
+
38
+ ## Versioning
39
+
40
+ `@kleora-io/core` and `@kleora-io/cli` are released together from
41
+ [`kleora-io/kleora-cli`](https://github.com/kleora-io/kleora-cli) and carry the
42
+ same version.
43
+
44
+ Licensed under Apache-2.0; see `LICENSE`.
@@ -0,0 +1,363 @@
1
+ /**
2
+ * The error shapes the two local tools throw and pass through.
3
+ *
4
+ * Declared here rather than imported from `@kleora-io/node`: neither tool
5
+ * depends on any published SDK. The tools have no database connection and no
6
+ * service credential of their own, and the same isolation argument applies to
7
+ * code: a process that administers a person's whole
8
+ * Account should not inherit behaviour from a package meant for verifying
9
+ * end-user tokens in someone else's backend).
10
+ *
11
+ * One copy, not two, and that is a correctness requirement rather than
12
+ * tidiness: the MCP server and the CLI both render these, and a second
13
+ * `ApiError` in the dependency graph would make `instanceof` lie in whichever
14
+ * of them imported the other's.
15
+ */
16
+ /** Base class for everything these packages throw. */
17
+ declare class KleoraToolError extends Error {
18
+ readonly code: string;
19
+ constructor(code: string, message: string, options?: ErrorOptions);
20
+ }
21
+ /**
22
+ * What `ApiError` carries beyond `type`/`status`/`detail` — the same shape
23
+ * `@kleora-io/node` calls `ProblemDetails`.
24
+ */
25
+ interface ProblemDetails {
26
+ /** The RFC 9457 document exactly as it arrived, extension members included. */
27
+ document: Record<string, unknown>;
28
+ /** `Retry-After` in seconds, falling back to the document's `retry_after`. */
29
+ retryAfter: number | null;
30
+ requestId: string | undefined;
31
+ }
32
+ /**
33
+ * An RFC 9457 problem document from the management API, passed through with
34
+ * its `type`, `title`, `detail` and `status`.
35
+ */
36
+ declare class ApiError extends KleoraToolError {
37
+ readonly type: string;
38
+ readonly title: string | undefined;
39
+ readonly status: number;
40
+ readonly detail: string | undefined;
41
+ readonly problem: ProblemDetails;
42
+ constructor(type: string, status: number, title: string | undefined, detail: string | undefined, problem: ProblemDetails);
43
+ /** The RFC 9457 document, verbatim plus its four standard fields. */
44
+ toProblemDocument(): Record<string, unknown>;
45
+ }
46
+ /**
47
+ * The management API could not be reached at all — refused, timed out, DNS
48
+ * failure. Deliberately distinguishable from a permission failure: an agent
49
+ * or a script must not read an outage as "you cannot do that".
50
+ */
51
+ declare class ManagementApiUnreachable extends KleoraToolError {
52
+ constructor(message: string, options?: ErrorOptions);
53
+ }
54
+ /**
55
+ * The person denied the device approval (RFC 8628 `access_denied`). Surfaced
56
+ * plainly; nothing is stored.
57
+ */
58
+ declare class AuthorizationDenied extends KleoraToolError {
59
+ constructor();
60
+ }
61
+
62
+ /** One stored credential, keyed by profile. */
63
+ interface CredentialStore {
64
+ get(profile: string): Promise<string | null>;
65
+ set(profile: string, refreshToken: string): Promise<void>;
66
+ delete(profile: string): Promise<void>;
67
+ /** For `kleora_whoami` and diagnostics — never the secret itself. */
68
+ readonly backend: 'keychain' | 'file';
69
+ }
70
+ /**
71
+ * Which store a tool is asking for. The two tools deliberately do **not**
72
+ * share a stored credential and cannot: a refresh token is bound to the
73
+ * OAuth client it was issued to, and each tool is its own client. What they
74
+ * share is this code.
75
+ *
76
+ * A single `~/.kleora` directory would be tidier and is deliberately not
77
+ * done — moving a live credential store makes every existing MCP user sign in
78
+ * again for no benefit they can see.
79
+ */
80
+ interface CredentialStoreOptions {
81
+ /** The keychain service name: `kleora-mcp` or `kleora-cli`. */
82
+ service: string;
83
+ /** Where the `0600` fallback lives: `~/.kleora-mcp` or `~/.kleora-cli`. */
84
+ configDir: string;
85
+ }
86
+ /** `~/.<name>`; overridable for tests, never by a flag a person sets. */
87
+ declare function defaultConfigDir(name: string): string;
88
+ /**
89
+ * Tries the OS keychain via `@napi-rs/keyring` (an optional dependency); falls
90
+ * back to the file store the moment
91
+ * loading it, or any one call to it, fails. A Linux box with no secret
92
+ * service running is the ordinary case this exists for, not an edge case:
93
+ * the fallback has to work as well as the keychain does, not merely exist.
94
+ */
95
+ declare function createCredentialStore({ service, configDir, }: CredentialStoreOptions): Promise<CredentialStore>;
96
+ /**
97
+ * A `0600` file per profile under `configDir`. `mode` on `writeFileSync` is
98
+ * still subject to the process umask, so every write is followed by an
99
+ * explicit `chmodSync` — the guarantee is the final permission bits, not
100
+ * merely the flag passed to the syscall that created the file.
101
+ */
102
+ declare class FileCredentialStore implements CredentialStore {
103
+ #private;
104
+ readonly backend = "file";
105
+ constructor(dir: string);
106
+ get(profile: string): Promise<string | null>;
107
+ set(profile: string, refreshToken: string): Promise<void>;
108
+ delete(profile: string): Promise<void>;
109
+ }
110
+
111
+ interface DeviceAuthorization {
112
+ deviceCode: string;
113
+ userCode: string;
114
+ verificationUri: string;
115
+ verificationUriComplete: string;
116
+ expiresIn: number;
117
+ interval: number;
118
+ }
119
+ interface Tokens {
120
+ accessToken: string;
121
+ refreshToken: string | undefined;
122
+ expiresIn: number;
123
+ }
124
+ /** RFC 8628 section 3.2 / RFC 6749 section 5.2 error codes this module distinguishes. */
125
+ type OAuthErrorCode = 'authorization_pending' | 'slow_down' | 'access_denied' | 'expired_token' | 'invalid_grant' | 'unauthorized_client' | 'other';
126
+ declare class OAuthError extends Error {
127
+ readonly code: OAuthErrorCode;
128
+ constructor(code: OAuthErrorCode, description: string | undefined);
129
+ }
130
+ interface DeviceGrantOptions {
131
+ issuer: string;
132
+ clientId: string;
133
+ /**
134
+ * `kleora-mcp/{version}` or `kleora-cli/{version}`. Passed in rather than
135
+ * read from a constant here, because this module is shared and the whole
136
+ * value of the two tools having their own OAuth client is that an audit event
137
+ * can say which of them acted — a shared `User-Agent` would undo half of that
138
+ * in the request log.
139
+ */
140
+ userAgent: string;
141
+ fetch: typeof globalThis.fetch;
142
+ }
143
+ /** RFC 8628 sections 3.1–3.2: `POST /oauth/device_authorization`. */
144
+ declare function startDeviceAuthorization({ issuer, clientId, userAgent, fetch: fetchImpl, }: DeviceGrantOptions): Promise<DeviceAuthorization>;
145
+ /**
146
+ * One poll of `POST /oauth/token` with
147
+ * `urn:ietf:params:oauth:grant-type:device_code`. Throws `OAuthError` for
148
+ * every RFC 8628 poll outcome that is not success — the caller
149
+ * (`session.ts`) is what turns `authorization_pending` into "not an error,
150
+ * this is the sign-in".
151
+ */
152
+ declare function pollDeviceToken({ issuer, clientId, deviceCode, userAgent, fetch: fetchImpl, }: DeviceGrantOptions & {
153
+ deviceCode: string;
154
+ }): Promise<Tokens>;
155
+ /** `grant_type=refresh_token`, for a stored credential. The refresh token rotates on every use. */
156
+ declare function refreshAccessToken({ issuer, clientId, refreshToken, userAgent, fetch: fetchImpl, }: DeviceGrantOptions & {
157
+ refreshToken: string;
158
+ }): Promise<Tokens>;
159
+ /**
160
+ * RFC 7009 section 2.1: `POST /oauth/revoke` with the refresh token, which
161
+ * revokes its whole rotation family and writes one
162
+ * `refresh_token.revoked` audit event.
163
+ *
164
+ * This is the server-side half of "uninstalling leaves no live credential
165
+ * behind": deleting the stored token alone would leave the
166
+ * authorization itself alive and refreshable by anyone who had copied the
167
+ * file. An unknown or already-dead token answers `200` with no effect
168
+ * (RFC 7009 section 2.2), so calling this twice is not an error.
169
+ */
170
+ declare function revokeRefreshToken({ issuer, clientId, refreshToken, userAgent, fetch: fetchImpl, }: DeviceGrantOptions & {
171
+ refreshToken: string;
172
+ }): Promise<void>;
173
+
174
+ declare const PLATFORM_PATH = "/api/v1/platform";
175
+ interface IssuerDiscoveryOptions {
176
+ /** The management API's origin, e.g. `https://api.kleora.io`, no trailing slash. */
177
+ baseUrl: string;
178
+ userAgent: string;
179
+ fetch?: typeof globalThis.fetch;
180
+ }
181
+ /**
182
+ * `GET {baseUrl}/api/v1/platform` → its `issuer`, without a trailing slash.
183
+ *
184
+ * Every failure is a `ManagementApiUnreachable` naming the URL it asked, because
185
+ * the only thing a person can do about any of them is check the base URL or
186
+ * pass the issuer explicitly — and the message says both.
187
+ */
188
+ declare function discoverIssuer({ baseUrl, userAgent, fetch: fetchImpl, }: IssuerDiscoveryOptions): Promise<string>;
189
+ /**
190
+ * The issuer to use, asked for at most once: `explicit` when given, otherwise
191
+ * whatever `discoverIssuer` answers.
192
+ *
193
+ * Lazy on purpose. A command that never reaches the issuer — anything run
194
+ * under an API key, `--help`, a usage error — makes no discovery request, and a
195
+ * long-lived MCP server makes one per process rather than one per tool call. A
196
+ * failed discovery is not remembered, so the next call asks again.
197
+ */
198
+ declare function issuerResolver(explicit: string | undefined, options: IssuerDiscoveryOptions): () => Promise<string>;
199
+
200
+ interface SessionOptions {
201
+ /**
202
+ * The platform issuer, or a function that finds it (`issuerResolver`). A
203
+ * function is called only when a request to the issuer is actually about to
204
+ * be made, so a session that never refreshes never asks.
205
+ */
206
+ issuer: string | (() => Promise<string>);
207
+ clientId: string;
208
+ profile: string;
209
+ store: CredentialStore;
210
+ /** `kleora-mcp/{version}` or `kleora-cli/{version}`. */
211
+ userAgent: string;
212
+ fetch?: typeof globalThis.fetch;
213
+ /** Access tokens are treated as expired this many seconds early. */
214
+ clockSkewSeconds?: number;
215
+ }
216
+ type SessionState = {
217
+ status: 'ready';
218
+ accessToken: string;
219
+ } | {
220
+ status: 'authorization_required';
221
+ verificationUri: string;
222
+ verificationUriComplete: string;
223
+ userCode: string;
224
+ message: string;
225
+ } | {
226
+ status: 'denied';
227
+ };
228
+ type NotReadyState = Exclude<SessionState, {
229
+ status: 'ready';
230
+ }>;
231
+ /**
232
+ * Thrown by the `getAccessToken` callback a `ManagementClient` is built
233
+ * with, when the session is not `ready`. The MCP server catches this and
234
+ * turns it into a tool result that says "not an error — this is the sign-in"
235
+ * rather than letting it surface as a protocol-level failure.
236
+ */
237
+ declare class SessionNotReady extends Error {
238
+ readonly state: NotReadyState;
239
+ constructor(state: NotReadyState);
240
+ }
241
+ declare class Session {
242
+ #private;
243
+ constructor(options: SessionOptions);
244
+ /**
245
+ * The access token to call the management API with, or the instructions to
246
+ * show the person instead of a result: "not an error — this is the
247
+ * sign-in."
248
+ */
249
+ ensureAccessToken(): Promise<SessionState>;
250
+ /**
251
+ * An access token from the **stored** credential only — never starting a
252
+ * device flow.
253
+ *
254
+ * This is the CLI's entry point rather than `ensureAccessToken` above, and
255
+ * the difference is a deliberate behavioural split rather than a
256
+ * convenience. With no credential for the profile, a CLI command says so
257
+ * and names `kleora login`, exiting `3`. **It does not start a device flow
258
+ * unbidden**: an interactive sign-in in the middle of a piped command is a
259
+ * hang.
260
+ *
261
+ * An MCP host, by contrast, has a place to show a verification URL and a
262
+ * turn to show it on, which is why `ensureAccessToken` may begin one there.
263
+ * `null` means "nothing stored, or what was stored is dead and has been
264
+ * deleted" — both of which the caller answers with the same sentence.
265
+ */
266
+ accessTokenFromStoredCredential(): Promise<string | null>;
267
+ /** Forces the next call to re-authorise, even if a token is cached in memory. */
268
+ invalidate(): void;
269
+ }
270
+
271
+ /** What this client needs to know about an operation in order to call it. */
272
+ interface Operation {
273
+ readonly operationId: string;
274
+ readonly method: 'get' | 'post' | 'put' | 'patch' | 'delete';
275
+ readonly path: string;
276
+ readonly pathParams: readonly string[];
277
+ readonly queryParams: readonly string[];
278
+ readonly hasBody: boolean;
279
+ }
280
+ interface ManagementClientOptions {
281
+ baseUrl: string;
282
+ /** Resolves to a fresh bearer token for every call — never cached here. */
283
+ getAccessToken: () => Promise<string>;
284
+ /** `kleora-mcp/{version}` or `kleora-cli/{version}`. */
285
+ userAgent: string;
286
+ fetch?: typeof globalThis.fetch;
287
+ timeoutMs?: number;
288
+ /**
289
+ * Concurrent requests this client will have in flight at once: a small
290
+ * number, deliberately. A host that fires several tool calls at once, or a
291
+ * `--all` walk, must not turn a local tool into a burst against the
292
+ * account's own limits.
293
+ */
294
+ maxConcurrent?: number;
295
+ /**
296
+ * Called once per attempt, for the CLI's `--debug`, which prints the
297
+ * request method, path, status, duration and `X-Request-Id` of every call
298
+ * to stderr. It is
299
+ * handed no credential and no body, which is what makes `--debug` output
300
+ * safe to paste into a support reply.
301
+ */
302
+ onTrace?: (trace: RequestTrace) => void;
303
+ }
304
+ /** What `--debug` prints. Deliberately carries nothing secret. */
305
+ interface RequestTrace {
306
+ method: string;
307
+ /** Path and query only — never the `Authorization` header, never a body. */
308
+ path: string;
309
+ /** `null` when nothing answered at all. */
310
+ status: number | null;
311
+ durationMs: number;
312
+ requestId: string | undefined;
313
+ /** Set when the request failed before a status existed. */
314
+ error?: string;
315
+ }
316
+ interface CallOptions {
317
+ /**
318
+ * Extra request headers: `Idempotency-Key` on a write, `X-Request-Id` when
319
+ * the caller wants to correlate one. **Never a credential** — the only
320
+ * `Authorization` header this client sends is the one it builds from
321
+ * `getAccessToken`, and it is applied after these so a caller cannot
322
+ * replace it.
323
+ */
324
+ headers?: Record<string, string>;
325
+ /**
326
+ * Whether repeating this request is safe after a `429`. Defaults to `true`.
327
+ * A non-idempotent `POST` is never retried without an `Idempotency-Key`, so
328
+ * a caller making a keyless `POST` passes `false`.
329
+ */
330
+ idempotent?: boolean;
331
+ }
332
+ /** A response, body included as the bytes that arrived. */
333
+ interface RawResponse {
334
+ status: number;
335
+ /**
336
+ * The body exactly as it arrived, unparsed. The CLI's `--json` prints the
337
+ * response body as it arrived, not a re-serialisation of a parsed object,
338
+ * which is what lets an older CLI against a newer API pass
339
+ * through fields it has never heard of.
340
+ */
341
+ text: string;
342
+ headers: Headers;
343
+ }
344
+ interface OperationArgs {
345
+ [name: string]: unknown;
346
+ }
347
+ declare class ManagementClient {
348
+ #private;
349
+ readonly baseUrl: string;
350
+ constructor(options: ManagementClientOptions);
351
+ /**
352
+ * Calls one operation and parses the body. `args` is a flat argument
353
+ * object; this method is what splits it back into path, query and body using
354
+ * the operation's own metadata — never a lookup this package invents.
355
+ */
356
+ call(operation: Operation, args: OperationArgs, options?: CallOptions): Promise<unknown>;
357
+ /** The same call, with the body left as the bytes that arrived. */
358
+ request(operation: Operation, args: OperationArgs, options?: CallOptions): Promise<RawResponse>;
359
+ }
360
+ /** `Retry-After` in seconds, from either the delta-seconds or the HTTP-date form. */
361
+ declare function retryAfterSeconds(response: Response): number | null;
362
+
363
+ export { ApiError, AuthorizationDenied, type CallOptions, type CredentialStore, type CredentialStoreOptions, type DeviceAuthorization, type DeviceGrantOptions, FileCredentialStore, type IssuerDiscoveryOptions, KleoraToolError, ManagementApiUnreachable, ManagementClient, type ManagementClientOptions, type NotReadyState, OAuthError, type OAuthErrorCode, type Operation, type OperationArgs, PLATFORM_PATH, type ProblemDetails, type RawResponse, type RequestTrace, Session, SessionNotReady, type SessionOptions, type SessionState, type Tokens, createCredentialStore, defaultConfigDir, discoverIssuer, issuerResolver, pollDeviceToken, refreshAccessToken, retryAfterSeconds, revokeRefreshToken, startDeviceAuthorization };