@402flow/sdk 0.1.0-alpha.13 → 0.1.0-alpha.15
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/README.md +319 -53
- package/dist/agent-harness.d.ts +161 -0
- package/dist/agent-harness.js +371 -0
- package/dist/agent-harness.js.map +1 -0
- package/dist/challenge-detection.d.ts +10 -0
- package/dist/challenge-detection.js +11 -0
- package/dist/challenge-detection.js.map +1 -1
- package/dist/contracts.d.ts +3690 -30
- package/dist/contracts.js +150 -0
- package/dist/contracts.js.map +1 -1
- package/dist/index.d.ts +63 -1
- package/dist/index.js +747 -11
- package/dist/index.js.map +1 -1
- package/dist/version.d.ts +2 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -1
- package/package.json +8 -6
package/README.md
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
# @402flow/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Paid HTTP SDK for AI agents with an inspectable prepare/execute flow.
|
|
4
|
+
|
|
5
|
+
It uses the 402flow control plane as the governance and execution backend, but the main developer surface is a small client for preparing and executing paid HTTP requests.
|
|
4
6
|
|
|
5
7
|
## Install
|
|
6
8
|
|
|
@@ -8,86 +10,350 @@ Node.js SDK for making paid requests through the 402flow control plane.
|
|
|
8
10
|
npm install @402flow/sdk
|
|
9
11
|
```
|
|
10
12
|
|
|
11
|
-
|
|
13
|
+
The published package supports Node 20+.
|
|
14
|
+
|
|
15
|
+
## Overview
|
|
16
|
+
|
|
17
|
+
`@402flow/sdk` is built for AI agents and other callers that need to inspect, prepare, and execute paid HTTP requests without embedding payment-protocol or governance logic in the host.
|
|
18
|
+
|
|
19
|
+
The SDK has one core client, `AgentPayClient`, and three main calls:
|
|
20
|
+
|
|
21
|
+
| API | Use when | What it does |
|
|
22
|
+
| --- | --- | --- |
|
|
23
|
+
| `fetchPaid(...)` | You already know the request shape | Probes if needed, resolves payment through the control plane, and returns passthrough or success |
|
|
24
|
+
| `preparePaidRequest(...)` | You want to inspect before paying | Returns normalized payment terms, request hints, validation issues, and `nextAction` |
|
|
25
|
+
| `executePreparedRequest(...)` | You already prepared the request | Executes the exact prepared request without re-probing first |
|
|
26
|
+
|
|
27
|
+
Use `fetchPaid(...)` for the simplest direct path.
|
|
28
|
+
Use `preparePaidRequest(...)` plus `executePreparedRequest(...)` when the caller needs an explicit inspect, revise, then execute loop.
|
|
29
|
+
|
|
30
|
+
The package also includes `AgentHarness`, an optional preparedId-based wrapper for tool hosts. It is a convenience layer on top of `AgentPayClient`, not part of the core client API.
|
|
12
31
|
|
|
13
|
-
|
|
32
|
+
## Runtime Notes
|
|
33
|
+
|
|
34
|
+
Two constraints matter early in real integrations:
|
|
35
|
+
|
|
36
|
+
1. paid prepare and execute flows require replayable request bodies
|
|
37
|
+
2. the current replayable body types are `string` and `URLSearchParams`
|
|
38
|
+
|
|
39
|
+
That means JSON payloads should be sent as strings, and form-style payloads should be sent as `URLSearchParams`.
|
|
40
|
+
|
|
41
|
+
The SDK exports small helpers for that:
|
|
14
42
|
|
|
15
43
|
```ts
|
|
16
|
-
import {
|
|
44
|
+
import {
|
|
45
|
+
createFormUrlEncodedBody,
|
|
46
|
+
createJsonRequestBody,
|
|
47
|
+
} from '@402flow/sdk';
|
|
48
|
+
|
|
49
|
+
const jsonBody = createJsonRequestBody({
|
|
50
|
+
prompt: 'foggy coastline',
|
|
51
|
+
});
|
|
52
|
+
|
|
53
|
+
const formBody = createFormUrlEncodedBody({
|
|
54
|
+
prompt: 'foggy coastline',
|
|
55
|
+
style: 'noir',
|
|
56
|
+
tags: ['coast', 'mist'],
|
|
57
|
+
});
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
`FormData`, `Blob`, streams, and framework-specific body wrappers are not currently accepted in paid flows because the SDK has to replay the exact request body through preparation and execution. Convert those upstream into a stable string or `URLSearchParams` first.
|
|
61
|
+
|
|
62
|
+
## Create A Client
|
|
63
|
+
|
|
64
|
+
Create one `AgentPayClient` per agent identity. The client binds the 402flow control-plane location and the organization plus agent selectors up front, and each request only carries request-specific context.
|
|
65
|
+
|
|
66
|
+
### Bootstrap key
|
|
67
|
+
|
|
68
|
+
For most SDK integrations, bootstrap-key auth is the recommended mode. The SDK exchanges it for a short-lived runtime token, caches that token, and refreshes it automatically before expiry.
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
import { AgentPayClient, createJsonRequestBody } from '@402flow/sdk';
|
|
17
72
|
|
|
18
73
|
const client = new AgentPayClient({
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
74
|
+
controlPlaneBaseUrl: 'https://402flow.ai',
|
|
75
|
+
organization: 'acme-labs',
|
|
76
|
+
agent: 'reporting-worker',
|
|
77
|
+
auth: {
|
|
78
|
+
type: 'bootstrapKey',
|
|
79
|
+
bootstrapKey: process.env.X402FLOW_BOOTSTRAP_KEY ?? '',
|
|
80
|
+
},
|
|
26
81
|
});
|
|
27
82
|
```
|
|
28
83
|
|
|
84
|
+
### Runtime token
|
|
29
85
|
|
|
30
|
-
|
|
31
|
-
|
|
86
|
+
```ts
|
|
87
|
+
import { AgentPayClient } from '@402flow/sdk';
|
|
88
|
+
|
|
89
|
+
const client = new AgentPayClient({
|
|
90
|
+
controlPlaneBaseUrl: 'https://402flow.ai',
|
|
91
|
+
organization: 'acme-labs',
|
|
92
|
+
agent: 'reporting-worker',
|
|
93
|
+
auth: {
|
|
94
|
+
type: 'runtimeToken',
|
|
95
|
+
runtimeToken: process.env.X402FLOW_RUNTIME_TOKEN ?? '',
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
```
|
|
32
99
|
|
|
33
|
-
|
|
100
|
+
## Fast Path: `fetchPaid()`
|
|
34
101
|
|
|
35
|
-
Call `fetchPaid()`
|
|
102
|
+
Call `fetchPaid()` when you already know the merchant URL, method, headers, and body.
|
|
36
103
|
|
|
37
104
|
```ts
|
|
38
105
|
try {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
106
|
+
const result = await client.fetchPaid(
|
|
107
|
+
'https://merchant.example.com/reports/daily',
|
|
108
|
+
{
|
|
109
|
+
method: 'POST',
|
|
110
|
+
headers: {
|
|
111
|
+
'content-type': 'application/json',
|
|
112
|
+
},
|
|
113
|
+
body: createJsonRequestBody({
|
|
114
|
+
date: '2026-03-25',
|
|
115
|
+
}),
|
|
116
|
+
},
|
|
117
|
+
{
|
|
118
|
+
description: 'sync daily paid report',
|
|
119
|
+
idempotencyKey: 'daily-report-2026-03-25',
|
|
120
|
+
},
|
|
121
|
+
);
|
|
122
|
+
|
|
123
|
+
const paidContent = await result.response.json();
|
|
124
|
+
console.log('paid content:', paidContent);
|
|
57
125
|
} catch (error) {
|
|
58
|
-
|
|
59
|
-
|
|
126
|
+
console.error('paid request failed', error);
|
|
127
|
+
throw error;
|
|
60
128
|
}
|
|
61
129
|
```
|
|
62
130
|
|
|
63
|
-
|
|
131
|
+
If the merchant does not require payment for that exact request, the SDK returns a passthrough response. If the merchant returns a payable challenge, the SDK resolves payment through the control plane and returns a durable paid outcome.
|
|
64
132
|
|
|
65
|
-
|
|
133
|
+
## Preparation Flow
|
|
66
134
|
|
|
67
|
-
|
|
68
|
-
2. `preflight_failed`: the request was incompatible with paid execution before payment started
|
|
69
|
-
3. `execution_pending`: a safe retry attached to an in-flight paid attempt that is still executing
|
|
70
|
-
4. `execution_failed`: payment failed, no receipt was produced, and no paid content was delivered
|
|
71
|
-
5. `paid_fulfillment_failed`: payment was accepted and a receipt exists, but the merchant did not deliver the paid content
|
|
72
|
-
6. `execution_inconclusive`: the system could not conclusively determine the payment outcome
|
|
135
|
+
Use `preparePaidRequest()` when the caller needs a first-class pre-execution result before paying.
|
|
73
136
|
|
|
74
|
-
|
|
137
|
+
```ts
|
|
138
|
+
import { createJsonRequestBody } from '@402flow/sdk';
|
|
139
|
+
|
|
140
|
+
const prepared = await client.preparePaidRequest(
|
|
141
|
+
'https://merchant.example.com/images/generate',
|
|
142
|
+
{
|
|
143
|
+
method: 'POST',
|
|
144
|
+
headers: {
|
|
145
|
+
'content-type': 'application/json',
|
|
146
|
+
},
|
|
147
|
+
body: createJsonRequestBody({
|
|
148
|
+
prompt: 'foggy coastline',
|
|
149
|
+
}),
|
|
150
|
+
},
|
|
151
|
+
);
|
|
152
|
+
|
|
153
|
+
if (prepared.kind === 'passthrough') {
|
|
154
|
+
console.log('merchant did not require payment', prepared.probe?.responseStatus);
|
|
155
|
+
} else {
|
|
156
|
+
console.log('protocol:', prepared.protocol);
|
|
157
|
+
console.log('payment requirement:', prepared.paymentRequirement);
|
|
158
|
+
console.log('request hints:', prepared.hints);
|
|
159
|
+
}
|
|
75
160
|
|
|
76
|
-
|
|
161
|
+
console.log('next action:', prepared.nextAction);
|
|
162
|
+
console.log('validation issues:', prepared.validationIssues);
|
|
163
|
+
```
|
|
77
164
|
|
|
78
|
-
|
|
165
|
+
This flow is useful when:
|
|
79
166
|
|
|
80
|
-
1.
|
|
81
|
-
2.
|
|
82
|
-
3.
|
|
83
|
-
4. later chain analysis in the control plane will advance a provisional receipt to confirmed, refunded, void, or expired
|
|
84
|
-
5. if you safely retry the same logical paid request with the same `idempotencyKey`, the SDK returns the same durable paid outcome and receipt instead of creating a second paid attempt
|
|
167
|
+
1. an agent needs request-shape hints before attempting execution
|
|
168
|
+
2. the caller wants normalized payment terms before paying
|
|
169
|
+
3. the caller wants to merge optional `externalMetadata` it already has from another system
|
|
85
170
|
|
|
86
|
-
|
|
171
|
+
The common loop is:
|
|
172
|
+
|
|
173
|
+
1. prepare the request
|
|
174
|
+
2. inspect `kind`, `paymentRequirement`, `hints`, `validationIssues`, and `nextAction`
|
|
175
|
+
3. revise if needed
|
|
176
|
+
4. execute only once the request is understood
|
|
177
|
+
|
|
178
|
+
If your system already has endpoint metadata, you can pass it in as optional context:
|
|
179
|
+
|
|
180
|
+
```ts
|
|
181
|
+
import { createJsonRequestBody } from '@402flow/sdk';
|
|
182
|
+
|
|
183
|
+
const prepared = await client.preparePaidRequest(
|
|
184
|
+
'https://merchant.example.com/images/generate',
|
|
185
|
+
{
|
|
186
|
+
method: 'POST',
|
|
187
|
+
headers: {
|
|
188
|
+
'content-type': 'application/json',
|
|
189
|
+
},
|
|
190
|
+
body: createJsonRequestBody({
|
|
191
|
+
prompt: 'foggy coastline',
|
|
192
|
+
}),
|
|
193
|
+
},
|
|
194
|
+
{
|
|
195
|
+
externalMetadata: {
|
|
196
|
+
requestBodyType: 'json',
|
|
197
|
+
requestBodyFields: [
|
|
198
|
+
{
|
|
199
|
+
name: 'prompt',
|
|
200
|
+
type: 'string',
|
|
201
|
+
required: true,
|
|
202
|
+
},
|
|
203
|
+
],
|
|
204
|
+
},
|
|
205
|
+
},
|
|
206
|
+
);
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
`externalMetadata` is optional caller context. It improves preparation when the caller already has structured endpoint knowledge, but it is not required for normal SDK use.
|
|
210
|
+
|
|
211
|
+
### What `ready` Means
|
|
212
|
+
|
|
213
|
+
`ready` means this exact request can proceed through governed paid execution as-is; it does not mean the SDK has inferred the best task parameters for you.
|
|
214
|
+
|
|
215
|
+
That distinction matters:
|
|
216
|
+
|
|
217
|
+
1. `ready` is about protocol and payment executability
|
|
218
|
+
2. `validationIssues` and `hints` are about request-shape guidance
|
|
219
|
+
3. choosing semantically correct task parameters still belongs to the caller or agent
|
|
220
|
+
|
|
221
|
+
### Execute A Prepared Request
|
|
87
222
|
|
|
223
|
+
If preparation returns `kind === 'ready'`, execute that exact prepared request with `executePreparedRequest(prepared, ...)`.
|
|
224
|
+
|
|
225
|
+
```ts
|
|
226
|
+
import { createJsonRequestBody } from '@402flow/sdk';
|
|
227
|
+
|
|
228
|
+
const prepared = await client.preparePaidRequest(
|
|
229
|
+
'https://merchant.example.com/images/generate',
|
|
230
|
+
{
|
|
231
|
+
method: 'POST',
|
|
232
|
+
headers: {
|
|
233
|
+
'content-type': 'application/json',
|
|
234
|
+
},
|
|
235
|
+
body: createJsonRequestBody({
|
|
236
|
+
prompt: 'foggy coastline',
|
|
237
|
+
}),
|
|
238
|
+
},
|
|
239
|
+
);
|
|
240
|
+
|
|
241
|
+
if (prepared.kind === 'ready') {
|
|
242
|
+
const result = await client.executePreparedRequest(prepared, {
|
|
243
|
+
description: 'generate image',
|
|
244
|
+
idempotencyKey: 'image-generate-foggy-coastline',
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
console.log('paid response status:', result.response.status);
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
If preparation does not return `kind === 'ready'`, that is not necessarily an error. It means this exact request did not currently resolve to a payable executable path. The caller can accept that result, run a normal non-paid path, or revise and prepare again.
|
|
252
|
+
|
|
253
|
+
## Prepared Result Semantics
|
|
254
|
+
|
|
255
|
+
`preparePaidRequest()` separates request checking from paid execution.
|
|
256
|
+
|
|
257
|
+
The preparation result distinguishes four important things:
|
|
258
|
+
|
|
259
|
+
1. `paymentRequirement`: normalized payment terms derived from the merchant challenge when available
|
|
260
|
+
2. `hints`: request-shape hints such as body fields, query params, path params, descriptions, examples, and notes
|
|
261
|
+
3. `validationIssues`: structured remediation diagnostics derived from the current request and defensible preparation inputs
|
|
262
|
+
4. `nextAction`: a narrow action summary such as `execute`, `revise_request`, or `treat_as_passthrough`
|
|
263
|
+
|
|
264
|
+
Each prepared hint carries `attribution` so callers can distinguish live merchant-authoritative data from advisory caller-supplied metadata.
|
|
265
|
+
|
|
266
|
+
In this model, payment terms come from the merchant challenge, optional request-shape enrichment comes from `externalMetadata`, and live confirmation is represented by the prepared `probe` result.
|
|
267
|
+
|
|
268
|
+
## Result And Error Semantics
|
|
269
|
+
|
|
270
|
+
`fetchPaid()` and `executePreparedRequest()` either:
|
|
271
|
+
|
|
272
|
+
1. return a passthrough response when the request did not require payment
|
|
273
|
+
2. return `success` with a receipt when the paid request completed successfully
|
|
274
|
+
3. throw `FetchPaidError` for all non-success paid outcomes
|
|
275
|
+
|
|
276
|
+
`FetchPaidError` kinds are:
|
|
277
|
+
|
|
278
|
+
1. `denied`
|
|
279
|
+
2. `preflight_failed`
|
|
280
|
+
3. `execution_pending`
|
|
281
|
+
4. `execution_failed`
|
|
282
|
+
5. `paid_fulfillment_failed`
|
|
283
|
+
6. `execution_inconclusive`
|
|
284
|
+
7. `request_failed`
|
|
285
|
+
|
|
286
|
+
Receipt notes:
|
|
287
|
+
|
|
288
|
+
1. `receipt.status = 'confirmed'` means the control plane has chain-backed settlement attribution for the paid attempt
|
|
289
|
+
2. `receipt.status = 'provisional'` means the paid outcome was supportable by merchant-provided evidence, but final settlement attribution is still pending reconciliation
|
|
290
|
+
3. callers should treat provisional receipts as payment-attempt evidence, not as proof of final settlement
|
|
291
|
+
4. if you safely retry the same logical paid request with the same `idempotencyKey`, the SDK returns the same durable paid outcome instead of creating a second paid attempt
|
|
292
|
+
|
|
293
|
+
## Receipt Lookup
|
|
294
|
+
|
|
295
|
+
```ts
|
|
296
|
+
const receipt = await client.lookupReceipt('receipt-id');
|
|
297
|
+
|
|
298
|
+
console.log(receipt.receipt.status);
|
|
88
299
|
```
|
|
300
|
+
|
|
301
|
+
## Minimal Agent Integration Contract
|
|
302
|
+
|
|
303
|
+
Most agent frameworks only need a small orchestration policy:
|
|
304
|
+
|
|
305
|
+
```text
|
|
306
|
+
When using @402flow/sdk:
|
|
307
|
+
- Always prepare a paid request before executing it.
|
|
308
|
+
- Execute only when preparation returns nextAction as execute.
|
|
309
|
+
- If preparation returns treat_as_passthrough, do not pay and explain that paid execution is not required.
|
|
310
|
+
- If preparation returns revise_request, use validationIssues and hints to revise only when the task provides enough information; otherwise stop and explain what is still missing.
|
|
311
|
+
- Use externalMetadata only when the caller already has it from another system, and treat it as advisory when merchant-challenge hints disagree.
|
|
312
|
+
- Do not invent missing business parameters or execute the same prepared request twice unless the caller explicitly asks for a retry.
|
|
313
|
+
- After execution, read the stored execution result and report denied, pending, failed, or inconclusive outcomes clearly.
|
|
314
|
+
```
|
|
315
|
+
|
|
316
|
+
That is the portable core SDK story. It should work across OpenAI, Claude, LangGraph, MCP, or custom workflows without requiring host-specific packaging in the SDK contract itself.
|
|
317
|
+
|
|
318
|
+
## Tiny OpenAI Tools Host
|
|
319
|
+
|
|
320
|
+
If you want a minimal real host integration instead of the larger evaluation harness, use the tiny OpenAI Responses example in `examples/openai-tools-quickstart.mjs`.
|
|
321
|
+
|
|
322
|
+
It keeps the host story narrow:
|
|
323
|
+
|
|
324
|
+
1. create an `AgentPayClient`
|
|
325
|
+
2. wrap it with optional `AgentHarness` so tool calls can pass `preparedId`
|
|
326
|
+
3. expose `prepare_paid_request`, `execute_prepared_request`, and `get_execution_result`
|
|
327
|
+
|
|
328
|
+
Run it with one prompt:
|
|
329
|
+
|
|
330
|
+
```bash
|
|
331
|
+
export OPENAI_API_KEY="..."
|
|
332
|
+
export X402FLOW_CONTROL_PLANE_BASE_URL="https://402flow.ai"
|
|
333
|
+
export X402FLOW_ORGANIZATION="acme-labs"
|
|
334
|
+
export X402FLOW_AGENT="reporting-worker"
|
|
335
|
+
export X402FLOW_BOOTSTRAP_KEY="..."
|
|
336
|
+
|
|
337
|
+
npm run example:openai-tools-quickstart -- \
|
|
338
|
+
"Prepare and execute a paid POST request to https://merchant.example.com/images/generate with JSON body {\"prompt\":\"foggy coastline\"}"
|
|
339
|
+
```
|
|
340
|
+
|
|
341
|
+
Use this when you want the shortest real host integration path. Use the full evaluation harness only when you need scenarios, transcripts, or repeated eval runs.
|
|
342
|
+
|
|
343
|
+
## Optional `AgentHarness`
|
|
344
|
+
|
|
345
|
+
`AgentHarness` is an optional preparedId-based wrapper for tool hosts that do not want to manage in-flight prepared request objects themselves. It is a convenience layer on top of `AgentPayClient`, not a required abstraction.
|
|
346
|
+
|
|
347
|
+
For harness usage, presets, transcripts, and scenario packs, see:
|
|
348
|
+
|
|
349
|
+
1. [docs/evaluation-harness.md](docs/evaluation-harness.md)
|
|
350
|
+
2. [docs/harness-scenarios.md](docs/harness-scenarios.md)
|
|
351
|
+
|
|
352
|
+
## Publish
|
|
353
|
+
|
|
354
|
+
```bash
|
|
89
355
|
npm install
|
|
90
356
|
npm run check
|
|
91
357
|
npm run pack:check
|
|
92
358
|
npm publish --access public
|
|
93
|
-
```
|
|
359
|
+
```
|
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentHarness provides a small in-memory orchestration layer on top of
|
|
3
|
+
* AgentPayClient for hosts that prefer preparedId-based handoffs over holding
|
|
4
|
+
* full prepared request objects.
|
|
5
|
+
*
|
|
6
|
+
* The intended host-facing flow is:
|
|
7
|
+
*
|
|
8
|
+
* 1. prepare a candidate request and receive a preparedId plus the preparation summary
|
|
9
|
+
* 2. execute later by preparedId once nextAction is execute
|
|
10
|
+
* 3. read back the stored execution result by preparedId
|
|
11
|
+
*
|
|
12
|
+
* This is useful for tool-driven hosts such as OpenAI tools, MCP servers,
|
|
13
|
+
* Claude tools, LangGraph nodes, or custom orchestrators where passing a small
|
|
14
|
+
* opaque id between turns is easier than preserving the full prepared object.
|
|
15
|
+
*
|
|
16
|
+
* This file implements only a convenience layer. The core SDK contract remains
|
|
17
|
+
* AgentPayClient with preparePaidRequest() and executePreparedRequest().
|
|
18
|
+
*
|
|
19
|
+
* Important behavior:
|
|
20
|
+
* - State is kept only in memory inside this process.
|
|
21
|
+
* - Prepared requests expire after a TTL.
|
|
22
|
+
* - A newer active preparation for the same method + origin + pathname supersedes
|
|
23
|
+
* the older one.
|
|
24
|
+
* - Execution is rejected locally unless the stored preparation is still active,
|
|
25
|
+
* kind === 'ready', and nextAction === 'execute'.
|
|
26
|
+
*/
|
|
27
|
+
import type { PaidRequestChallenge, SdkExternalMetadata, SdkMerchantResponse, SdkPreparedNextAction, SdkPreparedPaidRequest, SdkPreparedPaymentRequirement, SdkPreparedRequestHints, SdkPreparedValidationIssue } from './contracts.js';
|
|
28
|
+
import type { AgentPayClient, ExecutePreparedRequest, FetchPaidFailureResponse, PaidResponse } from './index.js';
|
|
29
|
+
export type AgentHarnessPreparedState = 'active' | 'consumed' | 'expired' | 'superseded';
|
|
30
|
+
/** Local rejection reasons produced by the harness before the SDK is called. */
|
|
31
|
+
export type AgentHarnessRejectionCode = 'missing_prepared_id' | 'unknown_prepared_id' | 'expired_prepared_id' | 'prepared_request_superseded' | 'prepared_request_consumed' | 'prepared_request_not_ready' | 'prepared_request_not_executable';
|
|
32
|
+
/** Typed error used internally to convert local state failures into stable results. */
|
|
33
|
+
export declare class AgentHarnessError extends Error {
|
|
34
|
+
readonly code: AgentHarnessRejectionCode;
|
|
35
|
+
readonly preparedId: string | undefined;
|
|
36
|
+
constructor(code: AgentHarnessRejectionCode, message: string, preparedId?: string);
|
|
37
|
+
}
|
|
38
|
+
/** Host-facing input for the harness prepare step. */
|
|
39
|
+
export type AgentHarnessPrepareInput = {
|
|
40
|
+
url: string;
|
|
41
|
+
method?: string;
|
|
42
|
+
headers?: Record<string, string>;
|
|
43
|
+
body?: string;
|
|
44
|
+
externalMetadata?: SdkExternalMetadata;
|
|
45
|
+
};
|
|
46
|
+
/** Host-facing input for the harness execute step. */
|
|
47
|
+
export type AgentHarnessExecuteInput = {
|
|
48
|
+
preparedId: string;
|
|
49
|
+
executionContext?: ExecutePreparedRequest;
|
|
50
|
+
};
|
|
51
|
+
/** Exact immutable execution payload stored behind a preparedId. */
|
|
52
|
+
export type AgentHarnessExecutionBinding = {
|
|
53
|
+
method: string;
|
|
54
|
+
url: string;
|
|
55
|
+
headers: Record<string, string>;
|
|
56
|
+
body?: string;
|
|
57
|
+
bodyHash?: string;
|
|
58
|
+
challenge?: {
|
|
59
|
+
protocol: PaidRequestChallenge['protocol'];
|
|
60
|
+
headers: Record<string, string>;
|
|
61
|
+
body?: unknown;
|
|
62
|
+
};
|
|
63
|
+
merchantOrigin: string;
|
|
64
|
+
};
|
|
65
|
+
/** Summary returned to the host after preparation succeeds. */
|
|
66
|
+
export type AgentHarnessPreparedSummary = {
|
|
67
|
+
preparedId: string;
|
|
68
|
+
state: 'active';
|
|
69
|
+
kind: SdkPreparedPaidRequest['kind'];
|
|
70
|
+
protocol: SdkPreparedPaidRequest['protocol'];
|
|
71
|
+
paymentRequirement?: SdkPreparedPaymentRequirement;
|
|
72
|
+
hints: SdkPreparedRequestHints;
|
|
73
|
+
probe?: SdkPreparedPaidRequest['probe'];
|
|
74
|
+
validationIssues: SdkPreparedValidationIssue[];
|
|
75
|
+
nextAction: SdkPreparedNextAction;
|
|
76
|
+
expiresAt: string;
|
|
77
|
+
};
|
|
78
|
+
/** Stored summary for an SDK-backed paid execution outcome. */
|
|
79
|
+
export type AgentHarnessExecutedResult = {
|
|
80
|
+
preparedId: string;
|
|
81
|
+
harnessDisposition: 'executed';
|
|
82
|
+
sdkOutcomeKind: PaidResponse['kind'] | FetchPaidFailureResponse['kind'];
|
|
83
|
+
status: number;
|
|
84
|
+
merchantResponse: SdkMerchantResponse;
|
|
85
|
+
receiptId?: string;
|
|
86
|
+
paidRequestId?: string;
|
|
87
|
+
paymentAttemptId?: string;
|
|
88
|
+
reason?: string;
|
|
89
|
+
policyReviewEventId?: string;
|
|
90
|
+
};
|
|
91
|
+
/** Stored summary for a harness-local rejection outcome. */
|
|
92
|
+
export type AgentHarnessRejectedResult = {
|
|
93
|
+
preparedId: string;
|
|
94
|
+
harnessDisposition: 'rejected';
|
|
95
|
+
rejectionCode: AgentHarnessRejectionCode;
|
|
96
|
+
message: string;
|
|
97
|
+
};
|
|
98
|
+
export type AgentHarnessExecutionResult = AgentHarnessExecutedResult | AgentHarnessRejectedResult;
|
|
99
|
+
/** Lookup shape returned when a host asks for the durable result of a preparedId. */
|
|
100
|
+
export type AgentHarnessExecutionLookup = {
|
|
101
|
+
preparedId: string;
|
|
102
|
+
state: AgentHarnessPreparedState;
|
|
103
|
+
supersededByPreparedId?: string;
|
|
104
|
+
executionResult?: AgentHarnessExecutionResult;
|
|
105
|
+
};
|
|
106
|
+
/** Full internal record shape exposed for debugging and test inspection. */
|
|
107
|
+
export type AgentHarnessPreparedRecord = {
|
|
108
|
+
preparedId: string;
|
|
109
|
+
state: AgentHarnessPreparedState;
|
|
110
|
+
createdAt: string;
|
|
111
|
+
expiresAt: string;
|
|
112
|
+
supersededByPreparedId?: string;
|
|
113
|
+
prepared: SdkPreparedPaidRequest;
|
|
114
|
+
executionBinding: AgentHarnessExecutionBinding;
|
|
115
|
+
executionResult?: AgentHarnessExecutionResult;
|
|
116
|
+
};
|
|
117
|
+
/** Minimal client surface AgentHarness needs from the core SDK. */
|
|
118
|
+
export type AgentHarnessClient = Pick<AgentPayClient, 'preparePaidRequest' | 'executePreparedRequest'>;
|
|
119
|
+
/** Configuration for the in-memory wrapper, including TTL and id generation hooks. */
|
|
120
|
+
export type AgentHarnessOptions = {
|
|
121
|
+
client: AgentHarnessClient;
|
|
122
|
+
preparedTtlMs?: number;
|
|
123
|
+
now?: () => Date;
|
|
124
|
+
createPreparedId?: () => string;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Optional in-memory preparedId wrapper over AgentPayClient.
|
|
128
|
+
*/
|
|
129
|
+
export declare class AgentHarness {
|
|
130
|
+
private readonly client;
|
|
131
|
+
private readonly preparedTtlMs;
|
|
132
|
+
private readonly now;
|
|
133
|
+
private readonly createPreparedId;
|
|
134
|
+
private readonly preparedRecords;
|
|
135
|
+
constructor(options: AgentHarnessOptions);
|
|
136
|
+
/**
|
|
137
|
+
* Prepare a candidate request through the core SDK and store the immutable
|
|
138
|
+
* prepared result behind a generated preparedId for later execution.
|
|
139
|
+
*/
|
|
140
|
+
preparePaidRequest(input: AgentHarnessPrepareInput): Promise<AgentHarnessPreparedSummary>;
|
|
141
|
+
/**
|
|
142
|
+
* Execute a previously stored ready preparation. Local state failures are
|
|
143
|
+
* converted into deterministic rejected results rather than thrown to the host.
|
|
144
|
+
*/
|
|
145
|
+
executePreparedRequest(input: AgentHarnessExecuteInput): Promise<AgentHarnessExecutionResult>;
|
|
146
|
+
/**
|
|
147
|
+
* Return the durable stored outcome for a preparedId without re-running any
|
|
148
|
+
* merchant or control-plane call.
|
|
149
|
+
*/
|
|
150
|
+
getExecutionResult(preparedId: string): AgentHarnessExecutionLookup;
|
|
151
|
+
/**
|
|
152
|
+
* Return the full stored record for debugging, tests, or host inspection.
|
|
153
|
+
*/
|
|
154
|
+
getPreparedRecord(preparedId: string): AgentHarnessPreparedRecord;
|
|
155
|
+
private runExecution;
|
|
156
|
+
private handleExecutionRejection;
|
|
157
|
+
private getRecordForExecution;
|
|
158
|
+
private getKnownRecord;
|
|
159
|
+
private refreshRecordState;
|
|
160
|
+
private supersedeActiveRecords;
|
|
161
|
+
}
|