@ledgerhq/agent-intent-sdk 0.0.0-stage → 0.2.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 (63) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +377 -2
  3. package/dist/auth.d.ts +35 -0
  4. package/dist/auth.d.ts.map +1 -0
  5. package/dist/auth.js +366 -0
  6. package/dist/auth.js.map +1 -0
  7. package/dist/bytes.d.ts +7 -0
  8. package/dist/bytes.d.ts.map +1 -0
  9. package/dist/bytes.js +26 -0
  10. package/dist/bytes.js.map +1 -0
  11. package/dist/client.d.ts +34 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +149 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/completion.d.ts +29 -0
  16. package/dist/completion.d.ts.map +1 -0
  17. package/dist/completion.js +78 -0
  18. package/dist/completion.js.map +1 -0
  19. package/dist/enrollment.d.ts +54 -0
  20. package/dist/enrollment.d.ts.map +1 -0
  21. package/dist/enrollment.js +143 -0
  22. package/dist/enrollment.js.map +1 -0
  23. package/dist/enrollmentChannel.d.ts +85 -0
  24. package/dist/enrollmentChannel.d.ts.map +1 -0
  25. package/dist/enrollmentChannel.js +671 -0
  26. package/dist/enrollmentChannel.js.map +1 -0
  27. package/dist/fingerprint.d.ts +2 -0
  28. package/dist/fingerprint.d.ts.map +1 -0
  29. package/dist/fingerprint.js +36 -0
  30. package/dist/fingerprint.js.map +1 -0
  31. package/dist/identity.d.ts +13 -0
  32. package/dist/identity.d.ts.map +1 -0
  33. package/dist/identity.js +28 -0
  34. package/dist/identity.js.map +1 -0
  35. package/dist/index.d.ts +14 -0
  36. package/dist/index.d.ts.map +1 -0
  37. package/dist/index.js +14 -0
  38. package/dist/index.js.map +1 -0
  39. package/dist/intentPage.d.ts +71 -0
  40. package/dist/intentPage.d.ts.map +1 -0
  41. package/dist/intentPage.js +103 -0
  42. package/dist/intentPage.js.map +1 -0
  43. package/dist/intents.d.ts +93 -0
  44. package/dist/intents.d.ts.map +1 -0
  45. package/dist/intents.js +294 -0
  46. package/dist/intents.js.map +1 -0
  47. package/dist/recovery.d.ts +67 -0
  48. package/dist/recovery.d.ts.map +1 -0
  49. package/dist/recovery.js +188 -0
  50. package/dist/recovery.js.map +1 -0
  51. package/dist/requestFields.d.ts +64 -0
  52. package/dist/requestFields.d.ts.map +1 -0
  53. package/dist/requestFields.js +230 -0
  54. package/dist/requestFields.js.map +1 -0
  55. package/dist/swapApproval.d.ts +31 -0
  56. package/dist/swapApproval.d.ts.map +1 -0
  57. package/dist/swapApproval.js +59 -0
  58. package/dist/swapApproval.js.map +1 -0
  59. package/dist/userAgent.d.ts +16 -0
  60. package/dist/userAgent.d.ts.map +1 -0
  61. package/dist/userAgent.js +53 -0
  62. package/dist/userAgent.js.map +1 -0
  63. package/package.json +66 -3
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-present Ledger
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 CHANGED
@@ -1,3 +1,378 @@
1
- # Temporary Holding Version
1
+ # `@ledgerhq/agent-intent-sdk`
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
+ > [!CAUTION]
4
+ > **Status: UNSTABLE**
5
+ > This package is under active development. Breaking changes may be released
6
+ > while the Agent Intent protocol and service contract stabilize.
7
+
8
+ Headless TypeScript SDK for agents that enroll with Ledger Agent Intent,
9
+ authenticate through LKRP/Keycloak, and submit signed intents for human approval.
10
+
11
+ The package has no React, Vite, browser-storage, Ledger device, or application
12
+ state dependency. Secret-key persistence is deliberately left to consumers.
13
+
14
+ ## Installation
15
+
16
+ ```sh
17
+ pnpm add @ledgerhq/agent-intent-sdk
18
+ ```
19
+
20
+ ## Requirements
21
+
22
+ - Node.js 24 or newer
23
+ - An enrolled Agent Intent identity and Trustchain ID
24
+ - Network access to the selected Agent Intent and Keycloak environments
25
+
26
+ ## Submit an intent
27
+
28
+ ```ts
29
+ import { createAgentIntentClient, createSoftwareAgentIdentity } from "@ledgerhq/agent-intent-sdk";
30
+
31
+ const identity = createSoftwareAgentIdentity(savedSecretKey);
32
+ const client = createAgentIntentClient({
33
+ bffBaseUrl: "https://global.api.stg.ledger-test.com/agent-intent",
34
+ identity,
35
+ trustchainId,
36
+ environment: "staging",
37
+ });
38
+
39
+ const deeplink = await client.createSendIntent({
40
+ type: "send",
41
+ network: "ethereum",
42
+ sender,
43
+ recipient,
44
+ amount: "1000000000000000000",
45
+ asset: { type: "native" },
46
+ feeStrategy: "medium",
47
+ description: "Pay supplier",
48
+ });
49
+ ```
50
+
51
+ Amounts accept decimal strings or `bigint` and are serialized as exact JSON
52
+ integers to avoid JavaScript precision loss.
53
+
54
+ A Solana send uses `network: "solana"` (or `"solana_devnet"`) and canonical
55
+ base58 addresses. It has no fee strategy, because the service sets the priority
56
+ fee, and it may carry an on-chain `memo`. A native SOL send gives its amount in
57
+ lamports:
58
+
59
+ ```ts
60
+ const deeplink = await client.createSendIntent({
61
+ type: "send",
62
+ network: "solana",
63
+ sender,
64
+ recipient,
65
+ amount: "10000000", // 0.01 SOL
66
+ asset: { type: "native" },
67
+ memo: "Invoice 42",
68
+ });
69
+ ```
70
+
71
+ An SPL token send names the token by its mint, with the amount in the token's
72
+ base units:
73
+
74
+ ```ts
75
+ asset: { type: "spl-token", assetReference: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v" }, // USDC
76
+ amount: "1000000", // 1 USDC
77
+ ```
78
+
79
+ Token-2022 tokens and an `assetOwner` are refused for now: no client can send
80
+ the former yet, and the service doesn't use the latter on Solana.
81
+
82
+ ### Swap intents
83
+
84
+ ```ts
85
+ const deeplink = await client.createSwapIntent({
86
+ type: "swap",
87
+ network: "ethereum",
88
+ sender,
89
+ fromAsset: "ethereum",
90
+ toAsset: "ethereum/erc20/usd__coin",
91
+ fromAmount: "0.5",
92
+ toAmount: "1250",
93
+ provider: "oneinch",
94
+ description: "Rebalance to USDC",
95
+ });
96
+ ```
97
+
98
+ `network` is one of `SWAP_INTENT_NETWORKS` (`ethereum`, `ethereum_sepolia`,
99
+ `arc_testnet`). `fromAmount` and `toAmount` are human-unit decimal strings
100
+ (`"0.5"` ETH, not wei), signed as given: `"1.5"` and `"1.50"` sign differently.
101
+
102
+ ### Swap token approvals
103
+
104
+ `canApproveSwapQuote` decides whether the Agent Intent app can send the ERC-20
105
+ approval a Swap API quote needs, so that wallet-cli and the app can apply the same
106
+ rules:
107
+
108
+ ```ts
109
+ const approval = parseErc20Approval(tokenAllowanceData.approvalTransaction);
110
+ const approvable = canApproveSwapQuote(
111
+ {
112
+ approvalRequired: isSwapApprovalRequired({
113
+ isApproved: tokenAllowanceData.isApproved,
114
+ isTokenApprovalRequired: tags.isTokenApprovalRequired,
115
+ }),
116
+ permitRequired,
117
+ allowanceSpender: approval?.spender,
118
+ allowanceToken: approval?.token,
119
+ allowanceAmount: parseBaseUnits(tokenAllowanceData.approvedAmount),
120
+ },
121
+ { network: "ethereum", swapsWithCalldata, soldTokenContract },
122
+ );
123
+ ```
124
+
125
+ The caller computes three inputs:
126
+
127
+ - `permitRequired`: the quote asks for a Permit2 signature.
128
+ - `swapsWithCalldata`: the quote's provider is one the app swaps with calldata.
129
+ - `soldTokenContract`: the sold token's contract address from the Crypto Assets
130
+ List; `undefined` for a native sale, whose quote is refused.
131
+
132
+ The app can send the approval only when all of these hold:
133
+
134
+ - the network is `ethereum`;
135
+ - the quote needs an approval and no Permit2 signature;
136
+ - its provider swaps with calldata;
137
+ - the approval is an `approve` of the sold token, and its spender and token are
138
+ addresses, the spender not the zero address;
139
+ - for USDT, the allowance left is zero (`needsAllowanceReset` says when to reset it
140
+ first).
141
+
142
+ `parseErc20Approval` reads only exact `approve(address,uint256)` calldata.
143
+ `parseBaseUnits` takes decimal digits or a safe integer only, so `"0x0"` is not a
144
+ zero allowance.
145
+
146
+ ## List the agent's intents
147
+
148
+ ```ts
149
+ import { isSendOperation, isSwapOperation } from "@ledgerhq/agent-intent-sdk";
150
+
151
+ let page = await client.listIntents({ status: ["signed", "broadcast"], pageSize: 10 });
152
+ while (true) {
153
+ for (const { id, status, intent } of page.intents) {
154
+ if (isSendOperation(intent)) console.log(id, status, intent.amount);
155
+ else if (isSwapOperation(intent)) console.log(id, status, intent.fromAmount, intent.toAmount);
156
+ }
157
+ if (!page.nextCursor) break;
158
+ page = await client.listIntents({ cursor: page.nextCursor });
159
+ }
160
+ ```
161
+
162
+ The BFF scopes the listing to the authenticated agent: it only returns intents
163
+ that agent issued, most recent first. `status` takes any of
164
+ `AGENT_INTENT_STATUSES` and `pageSize` one of `AGENT_INTENT_PAGE_SIZES` (1, 5,
165
+ 10, 50, 100; the BFF defaults to 10). `nextCursor` is opaque; when you pass it
166
+ back, the first page's filters and page size apply and the other options are
167
+ ignored. Amounts are exact strings: a send's `amount` is an integer in the
168
+ asset's smallest unit (wei, lamports, token base units), a swap's `fromAmount`
169
+ and `toAmount` are decimals in human units. One record that lacks a required
170
+ field, or has a known field of the wrong type (`null` included, even on an
171
+ optional field such as `failureReason` or `memo`), fails the whole page with an
172
+ `AgentIntentSdkError`. An intent type the SDK doesn't know yet is passed
173
+ through, so narrow with `isSendOperation` or `isSwapOperation`. HTTP failures
174
+ throw `AgentIntentHttpError` with the BFF's `status` and `type`.
175
+
176
+ ## Read one intent
177
+
178
+ ```ts
179
+ const intent = await client.getIntent(intentId);
180
+ console.log(intent.status, intent.updatedAt);
181
+ ```
182
+
183
+ An unknown id and another agent's intent both fail with `AgentIntentHttpError`
184
+ `status` 404. Amounts are exact decimal strings, as in the listing.
185
+
186
+ ## Cancel an intent
187
+
188
+ An agent can withdraw an intent it created, as long as the user hasn't acted on it:
189
+
190
+ ```ts
191
+ await client.cancelIntent(intentId);
192
+ ```
193
+
194
+ A `created` or `crafted` intent can be cancelled, and cancelling an already
195
+ cancelled one also succeeds. Any other state, including one the user rejected or
196
+ signed, fails with `AgentIntentHttpError` `status` 400 and no `type`; call
197
+ `getIntent` to see which. Only the user rejects, in Ledger's interface. An intent
198
+ can't be edited: to change one, cancel it and create a new one.
199
+
200
+ ## User-Agent
201
+
202
+ Outside browsers, requests send `User-Agent: ledger-agent-intent-sdk/<version> (agentic)`.
203
+ A custom `tokenProvider` sends its own authentication requests, so it must set that header itself.
204
+
205
+ ## Enrollment fingerprint
206
+
207
+ Display the same fingerprint that the Ledger device shows:
208
+
209
+ ```ts
210
+ import { formatAgentPublicKeyFingerprint } from "@ledgerhq/agent-intent-sdk";
211
+
212
+ console.log(formatAgentPublicKeyFingerprint(identity.publicKey));
213
+ ```
214
+
215
+ The helper accepts compressed or uncompressed secp256k1 public keys.
216
+
217
+ ## Validate an enrollment or recovery link
218
+
219
+ `validateAgentEnrollment` and `validateAgentRecovery` take the link's query
220
+ parameters. A malformed link comes back with `reason: "malformed"` and the
221
+ field problems in `issues`, so an application can say what went wrong:
222
+
223
+ ```ts
224
+ const validation = validateAgentEnrollment(search);
225
+ if (validation.status === "invalid" && validation.reason === "malformed") {
226
+ // { status: "invalid", reason: "malformed",
227
+ // message: 'This agent enrollment link is malformed: "signature" is cut off (expected 128 hex characters).',
228
+ // issues: [{ field: "signature", problem: "truncated", expectedLength: 128 }] }
229
+ }
230
+ ```
231
+
232
+ A field can be `missing`, `repeated` (the link was pasted twice), `empty`,
233
+ `truncated` or followed by `extra-characters` (hex fields), `too-long` (name and
234
+ description), have an `invalid-value`, carry an `unsupported-version`, or be
235
+ `unexpected`. `message` describes the first issue, and unexpected parameters
236
+ come after every other problem. `issues` only explains a rejection and never
237
+ changes which links are accepted, so two problems that do not reject a link on
238
+ their own, an unreadable `expiresAt` and a repeated channel field on a link
239
+ without a channel, are listed only when something else already rejects it. An
240
+ `unexpected` issue has a `parameter` instead of a `field`: it is the name as the
241
+ link carried it, so treat it as untrusted text and don't show it as is.
242
+ `AGENT_NAME_MAX_LENGTH` and `AGENT_DESCRIPTION_MAX_LENGTH` export the name and
243
+ description limits the validators apply.
244
+
245
+ ## Agent setup prompt
246
+
247
+ The prompt a user pastes into their agent to enroll it with the app they are on:
248
+
249
+ ```ts
250
+ const prompt = buildAgentSetupPrompt(window.location.origin);
251
+ ```
252
+
253
+ An https app is named by its host (`app.agents.ledger.com`), an http one by its full origin
254
+ (`http://localhost:5173`). The wallet-cli skill holds the enrollment steps.
255
+
256
+ ## Encrypted enrollment completion
257
+
258
+ Version-2 enrollment requests bind a one-use ephemeral relay host key into the
259
+ agent signature. A headless agent creates the host binding before creating the
260
+ URL; the socket opens lazily when it starts waiting. The host independently
261
+ authenticates the completion, persists it, and only then acknowledges:
262
+
263
+ ```ts
264
+ const host = createAgentEnrollmentChannelHost({
265
+ environment: "production",
266
+ relayBaseUrl: "https://trustchain.api.live.ledger.com",
267
+ });
268
+ const request = createAgentEnrollmentRequest(identity, {
269
+ name,
270
+ description,
271
+ source,
272
+ expiresAt,
273
+ channel: host.binding,
274
+ });
275
+ console.log(createAgentEnrollmentUrl(frontendUrl, request));
276
+
277
+ await host.waitForCompletion({
278
+ request,
279
+ authenticate: async (completion) => {
280
+ // Prove this agent key belongs to the claimed Trustchains. Throw on failure.
281
+ },
282
+ persist: async (completion) => {
283
+ // Persist completion.trustchainId and completion.accountAccess atomically.
284
+ },
285
+ });
286
+ ```
287
+
288
+ The browser validates the signed request, derives its trusted relay origin from
289
+ the signed environment, and uses `createAgentEnrollmentChannelCandidate()` to
290
+ deliver the serialized completion. The encrypted channel is the only delivery
291
+ path for version-2 and channel-bound recovery requests.
292
+
293
+ The candidate separates reaching the agent from delivering to it, so device
294
+ work only starts once the agent is known to be listening:
295
+
296
+ ```ts
297
+ const candidate = createAgentEnrollmentChannelCandidate({ request, relayBaseUrl });
298
+
299
+ await candidate.connect(); // relay socket + key-confirmation handshake
300
+ const completion = await approveOnLedgerDevice(); // may take minutes
301
+ await candidate.deliver(completion); // resolves after the host acknowledges
302
+ ```
303
+
304
+ `deliver()` connects implicitly when `connect()` was not called or the session
305
+ was lost (for example, the relay dropped the socket during device approval).
306
+ If a delivery fails, for example because `authenticate` rejected it or the
307
+ acknowledgement timed out, `deliver()` may be retried on the same candidate. Each
308
+ retry opens a fresh session with a new ephemeral key, and a newly connecting
309
+ candidate replaces one that has not delivered yet. A retry fails once the host has
310
+ finished, closed, or timed out.
311
+
312
+ ### Recovery
313
+
314
+ A recovery request re-enrolls an existing agent key into its previous App-18
315
+ Trustchain. Its `source` is an `AgentRecoverySource`, which is any supported
316
+ `AgentSource` (see `isAgentRecoverySource`): recovery never depends on the
317
+ source. Bind it to a channel host the same way:
318
+
319
+ ```ts
320
+ const request = createAgentRecoveryRequest(identity, {
321
+ name,
322
+ description,
323
+ source,
324
+ previousTrustchainId,
325
+ expiresAt,
326
+ channel: host.binding,
327
+ });
328
+ console.log(createAgentRecoveryUrl(frontendUrl, request));
329
+
330
+ const completion = await host.waitForCompletion({ request, authenticate, persist });
331
+ // completion: { version: 3, recovery: true, trustchainId, previousTrustchainId, ... }
332
+ ```
333
+
334
+ For a recovery request, the host accepts only a version-3 recovery completion
335
+ whose agent key, previous Trustchain, and request signature match the signed
336
+ request, and whose `trustchainId` equals `previousTrustchainId`. For a version-2
337
+ request it accepts only a version-2 completion. `serializeAgentRecoveryCompletion`,
338
+ `parseAgentRecoveryCompletion`, and `validateAgentRecovery` are exported for the
339
+ frontend. The channel binding is optional and signed; an unbound recovery
340
+ request keeps its earlier canonical bytes.
341
+
342
+ ### Security and timeouts
343
+
344
+ The channel key and every encrypted envelope are bound to the exact signed
345
+ request and envelope metadata. Handshake, completion, persistence, and
346
+ acknowledgement waits are bounded and capped by the signed request expiry.
347
+ The host allows 15 minutes for the frontend candidate to connect. After a
348
+ candidate connects, the cryptographic handshake, persistence, and
349
+ acknowledgement defaults are 30 seconds each. The wait between a completed
350
+ handshake and the delivered completion (device approval) is bounded only by
351
+ `completionTimeoutMs` (15 minutes) and the request expiry, on both the host and
352
+ the candidate. Applications may override these with the `timeouts` option.
353
+ While a session is open, both sides send the relay a text `ping` every 60
354
+ seconds, because the Trustchain relay drops a client after 5 minutes without a
355
+ frame sent to it. A failed `authenticate` call rejects only that delivery, so
356
+ the same or a later candidate can complete the same bounded host session. A
357
+ persistence failure closes the session without acknowledging. If enrollment was
358
+ committed before delivery failed, re-enroll the agent with a channel-bound
359
+ recovery request.
360
+
361
+ The channel sends only the agent public key, App-18 Trustchain ID, and safe
362
+ App-16 environment/root/path references. It must never carry a serialized
363
+ Trustchain, `walletSyncEncryptionKey`, private key, JWT, or access token.
364
+
365
+ ## Development
366
+
367
+ ```sh
368
+ mise install
369
+ pnpm install
370
+ pnpm verify
371
+ ```
372
+
373
+ See [CONTRIBUTING.md](./CONTRIBUTING.md) for branch, changeset, review, and
374
+ release conventions.
375
+
376
+ ## License
377
+
378
+ Apache-2.0. See [LICENSE](./LICENSE).
package/dist/auth.d.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { type AgentIdentity } from "./identity.ts";
2
+ export type AgentIntentEnvironment = "staging" | "production";
3
+ export type AgentKeycloakConfig = {
4
+ baseUrl: string;
5
+ realm: string;
6
+ clientId: string;
7
+ brokerId: string;
8
+ disablePkce?: boolean;
9
+ };
10
+ export declare const AGENT_KEYCLOAK_ENVIRONMENTS: {
11
+ readonly staging: {
12
+ readonly baseUrl: "https://global.api.stg.ledger-test.com/keycloak";
13
+ readonly realm: "agent-intent-customers";
14
+ readonly clientId: "agentic-client";
15
+ readonly brokerId: "lkrp";
16
+ };
17
+ readonly production: {
18
+ readonly baseUrl: "https://global.api.prd.ledger.com/keycloak";
19
+ readonly realm: "agent-intent-customers";
20
+ readonly clientId: "agentic-client";
21
+ readonly brokerId: "lkrp";
22
+ };
23
+ };
24
+ export type AccessTokenProvider = {
25
+ withAccessToken<T>(query: (accessToken: string) => Promise<T>, retryWhen?: (result: T) => boolean): Promise<T>;
26
+ };
27
+ export declare function createAgentTokenProvider(input: {
28
+ identity: AgentIdentity;
29
+ trustchainId: string;
30
+ keycloak: AgentKeycloakConfig;
31
+ fetch?: typeof globalThis.fetch;
32
+ }): AccessTokenProvider;
33
+ export declare function buildUnsignedChallengeTlv(tlvHex: string): Uint8Array;
34
+ export declare function buildAttestation(trustchainId: string): string;
35
+ //# sourceMappingURL=auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AACA,OAAO,EAA+B,KAAK,aAAa,EAAE,MAAM,eAAe,CAAC;AAGhF,MAAM,MAAM,sBAAsB,GAAG,SAAS,GAAG,YAAY,CAAC;AAE9D,MAAM,MAAM,mBAAmB,GAAG;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,QAAQ,EAAE,MAAM,CAAC;IACjB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF,eAAO,MAAM,2BAA2B;;iBAEpC,OAAO,EAAE,iDAAiD;iBAC1D,KAAK,EAAE,wBAAwB;iBAC/B,QAAQ,EAAE,gBAAgB;iBAC1B,QAAQ,EAAE,MAAM;;;iBAGhB,OAAO,EAAE,4CAA4C;iBACrD,KAAK,EAAE,wBAAwB;iBAC/B,QAAQ,EAAE,gBAAgB;iBAC1B,QAAQ,EAAE,MAAM;;CAEoD,CAAC;AAEzE,MAAM,MAAM,mBAAmB,GAAG;IAChC,eAAe,CAAC,CAAC,EACf,KAAK,EAAE,CAAC,WAAW,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,EAC1C,SAAS,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,KAAK,OAAO,GACjC,OAAO,CAAC,CAAC,CAAC,CAAC;CACf,CAAC;AAOF,wBAAgB,wBAAwB,CAAC,KAAK,EAAE;IAC9C,QAAQ,EAAE,aAAa,CAAC;IACxB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,KAAK,CAAC,EAAE,OAAO,UAAU,CAAC,KAAK,CAAC;CACjC,GAAG,mBAAmB,CA4BtB;AA8HD,wBAAgB,yBAAyB,CAAC,MAAM,EAAE,MAAM,GAAG,UAAU,CAmBpE;AAED,wBAAgB,gBAAgB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAI7D"}