@lucid-agents/pi-xgate 0.0.0-stage → 0.1.6

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.
@@ -0,0 +1,275 @@
1
+ // Adapts TaskMarket's x402 payer to the xgate Pi transport. The payer package is private, so
2
+ // this file declares the structural subset of its v1 contract (`@taskmarket/x402-payer`
3
+ // `src/api.ts`, X402_PAYER_API_VERSION 1) that the adapter uses; TaskMarket injects its
4
+ // instance. The payer owns the wallet, signer, rails, policy and journals: this adapter keeps
5
+ // no payment state of its own.
6
+ //
7
+ // The payer's string unions may gain values without a version bump. Every type here accepts
8
+ // unknown strings, and the adapter treats an unknown state as unverified.
9
+ import { atomic, origin as checkOrigin, record, route as checkRoute, XgateError, } from "@lucid-agents/xgate-client/types";
10
+ import { XgatePurchaseError, } from "./transport.js";
11
+ const RESOLVED_CHARGES = ["none", "released", "settled", "manually_resolved"], RESOLVED_STATES = ["completed", "failed"];
12
+ const CATALOG_BYTES = 2 * 1024 * 1024, REQUEST_BYTES = 8 * 1024 * 1024, CATALOG_DEADLINE_MS = 15000;
13
+ /** Never sends the request again for an ID the payer has seen: `purchase` maps every non-verified outcome to a terminal error. */
14
+ export function createTaskMarketTransport(options) {
15
+ const { payer } = options, base = checkOrigin(options.origin), fetcher = options.fetch ?? fetch;
16
+ if (payer.apiVersion !== 1)
17
+ throw new XgateError("unsupported_payer_api");
18
+ const channel = async (payment) => {
19
+ if (!options.balances || payment.rail.kind !== "session")
20
+ return;
21
+ try {
22
+ const matches = (await options.balances()).filter((b) => b.railId === payment.rail.id &&
23
+ b.network === payment.network &&
24
+ b.asset === payment.asset);
25
+ // Several sessions on one rail are not one channel; unlike balances are never summed.
26
+ if (matches.length !== 1)
27
+ return;
28
+ const b = matches[0];
29
+ return {
30
+ depositingAtomic: b.depositing,
31
+ lockedAtomic: b.locked,
32
+ chargedAtomic: b.charged,
33
+ pendingAtomic: b.pending,
34
+ refundableAtomic: b.refundable,
35
+ };
36
+ }
37
+ catch {
38
+ return; // Display only.
39
+ }
40
+ };
41
+ return {
42
+ async models(signal) {
43
+ const deadline = AbortSignal.timeout(CATALOG_DEADLINE_MS);
44
+ let response;
45
+ try {
46
+ response = await fetcher(base + "/v1/models", {
47
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
48
+ redirect: "error",
49
+ cache: "no-store",
50
+ credentials: "omit",
51
+ referrerPolicy: "no-referrer",
52
+ headers: { accept: "application/json" },
53
+ });
54
+ }
55
+ catch {
56
+ throw new XgateError("catalog_unavailable");
57
+ }
58
+ if (!response.ok) {
59
+ await response.body?.cancel().catch(() => { });
60
+ throw new XgateError("catalog_unavailable");
61
+ }
62
+ const v = parse(await bounded(response, CATALOG_BYTES));
63
+ if (!record(v) || !Array.isArray(v.data) || v.data.length > 128)
64
+ throw new XgateError("invalid_catalog");
65
+ return v.data
66
+ .filter((m) => record(m) &&
67
+ (options.models === undefined || options.models.includes(m.id)))
68
+ .map((m) => ({ ...m, xgate_origin: base }));
69
+ },
70
+ async purchase(invocation, signal, onResponse) {
71
+ checkRoute(invocation.route);
72
+ const body = new TextEncoder().encode(invocation.body);
73
+ if (body.byteLength === 0 || body.byteLength > REQUEST_BYTES)
74
+ throw new XgateError("invalid_invocation");
75
+ const id = invocation.id;
76
+ let result;
77
+ try {
78
+ result = await payer.request({
79
+ apiVersion: 1,
80
+ invocationId: id,
81
+ url: base + invocation.route,
82
+ method: "POST",
83
+ // Application headers only: the payer owns every payment header.
84
+ headers: {
85
+ "content-type": "application/json",
86
+ accept: "application/json",
87
+ },
88
+ body,
89
+ limits: { maxRequestBodyBytes: REQUEST_BYTES },
90
+ ...(options.allocationId !== undefined
91
+ ? { allocationId: options.allocationId }
92
+ : {}),
93
+ ...(options.policyRuleId !== undefined
94
+ ? { policyRuleId: options.policyRuleId }
95
+ : {}),
96
+ ...(options.nonInteractive !== undefined
97
+ ? { nonInteractive: options.nonInteractive }
98
+ : {}),
99
+ }, {
100
+ ...(signal ? { signal } : {}),
101
+ ...(options.confirmPayment
102
+ ? { confirmPayment: options.confirmPayment }
103
+ : {}),
104
+ });
105
+ }
106
+ catch (error) {
107
+ throw failure(error, id);
108
+ }
109
+ const payment = result.payment;
110
+ if (result.invocationId !== id || result.apiVersion !== 1)
111
+ throw new XgatePurchaseError("payer_result_mismatch", id, true, payment && display(payment));
112
+ // A paid xgate route never answers without a payment challenge.
113
+ if (!payment)
114
+ throw new XgatePurchaseError(result.response.status === 200
115
+ ? "payment_missing"
116
+ : "request_rejected", id, false);
117
+ const shown = display(payment);
118
+ if (payment.charge !== "settled" ||
119
+ typeof payment.settledAmount !== "string")
120
+ throw new XgatePurchaseError("payment_unverified", id, true, shown);
121
+ shown.chargedAtomic = payment.settledAmount;
122
+ try {
123
+ if (atomic(payment.settledAmount) > atomic(payment.authorizedAmount))
124
+ throw new XgateError("charge_over_authorization");
125
+ }
126
+ catch {
127
+ throw new XgatePurchaseError("invalid_settlement", id, true, shown);
128
+ }
129
+ const r = result.response, h = r.headers;
130
+ // Charged, so not pending, but the content is unusable.
131
+ if (r.status !== 200 ||
132
+ !/^application\/json\b/i.test(r.contentType) ||
133
+ h["x-inference-privacy"] !== "anonymous" ||
134
+ h["x-result-retention"] !== "none" ||
135
+ !h["cache-control"]?.includes("no-store"))
136
+ throw new XgatePurchaseError("response_rejected", id, false, shown);
137
+ let value;
138
+ try {
139
+ value = parse(r.body);
140
+ }
141
+ catch {
142
+ throw new XgatePurchaseError("invalid_response", id, false, shown);
143
+ }
144
+ if (!record(value) ||
145
+ typeof value.id !== "string" ||
146
+ value.result_replay_available !== undefined)
147
+ throw new XgatePurchaseError("invalid_response", id, false, shown);
148
+ const head = {
149
+ status: r.status,
150
+ headers: { "content-type": r.contentType, "cache-control": "no-store" },
151
+ };
152
+ try {
153
+ await onResponse?.(head);
154
+ }
155
+ catch {
156
+ throw new XgatePurchaseError("response_hook_failed", id, false, shown);
157
+ }
158
+ const balance = await channel(payment);
159
+ if (balance)
160
+ shown.channel = balance;
161
+ return {
162
+ body: value,
163
+ settlement: {
164
+ chargedAtomic: payment.settledAmount,
165
+ reference: payment.transaction ?? payment.commitment ?? payment.paymentId,
166
+ },
167
+ purchase: payment.commitment ?? payment.paymentId,
168
+ payment: shown,
169
+ };
170
+ },
171
+ async status() {
172
+ return {
173
+ transport: "taskmarket",
174
+ origin: base,
175
+ ...(options.balances
176
+ ? {
177
+ balances: (await options.balances()).map((b) => ({
178
+ rail: b.railId,
179
+ network: b.network,
180
+ asset: b.asset,
181
+ depositingAtomic: b.depositing,
182
+ lockedAtomic: b.locked,
183
+ chargedAtomic: b.charged,
184
+ pendingAtomic: b.pending,
185
+ refundableAtomic: b.refundable,
186
+ })),
187
+ }
188
+ : {}),
189
+ };
190
+ },
191
+ async reconcile(invocationId) {
192
+ const s = await payer.reconcile(invocationId);
193
+ return {
194
+ invocationId: s.invocationId,
195
+ state: s.state,
196
+ charge: s.charge,
197
+ uncertain: s.uncertain,
198
+ ...(s.errorCode ? { errorCode: s.errorCode } : {}),
199
+ ...(s.payment ? { payment: display(s.payment) } : {}),
200
+ };
201
+ },
202
+ };
203
+ }
204
+ function display(p) {
205
+ return {
206
+ network: p.network,
207
+ scheme: p.scheme,
208
+ asset: p.asset,
209
+ payTo: p.payTo,
210
+ rail: p.rail.kind,
211
+ authorizedAtomic: p.authorizedAmount,
212
+ ...(p.charge === "settled" && p.settledAmount !== undefined
213
+ ? { chargedAtomic: p.settledAmount }
214
+ : {}),
215
+ status: p.charge,
216
+ ...((p.transaction ?? p.commitment)
217
+ ? { reference: p.transaction ?? p.commitment }
218
+ : {}),
219
+ };
220
+ }
221
+ /**
222
+ * Maps a payer rejection. Only the stable code crosses into Pi; the payer's message may carry
223
+ * URLs or server text. A rejection that does not state `pending: false` counts as pending.
224
+ */
225
+ function failure(error, id) {
226
+ const e = error;
227
+ const code = typeof e?.code === "string" && /^[a-z0-9_]{1,64}$/.test(e.code)
228
+ ? e.code
229
+ : "payer_failed";
230
+ // A duplicate never sends again, but its recorded invocation may still be unresolved: only a
231
+ // positively resolved record counts as not pending.
232
+ const recorded = e?.invocation;
233
+ const pending = e?.pending !== false ||
234
+ (recorded !== undefined &&
235
+ !(recorded.uncertain === false &&
236
+ RESOLVED_CHARGES.includes(recorded.charge) &&
237
+ RESOLVED_STATES.includes(recorded.state)));
238
+ const summary = e?.invocation?.payment;
239
+ return new XgatePurchaseError(code, id, pending, record(summary) ? display(summary) : undefined);
240
+ }
241
+ async function bounded(response, limit) {
242
+ if (!response.body)
243
+ throw new XgateError("invalid_catalog");
244
+ const reader = response.body.getReader(), chunks = [];
245
+ let length = 0;
246
+ try {
247
+ for (;;) {
248
+ const part = await reader.read();
249
+ if (part.done)
250
+ break;
251
+ length += part.value.byteLength;
252
+ if (length > limit)
253
+ throw new XgateError("catalog_bound");
254
+ chunks.push(part.value);
255
+ }
256
+ }
257
+ catch (error) {
258
+ await reader.cancel().catch(() => { });
259
+ throw error instanceof XgateError
260
+ ? error
261
+ : new XgateError("catalog_unavailable");
262
+ }
263
+ finally {
264
+ reader.releaseLock();
265
+ }
266
+ return Buffer.concat(chunks, length);
267
+ }
268
+ function parse(bytes) {
269
+ try {
270
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
271
+ }
272
+ catch {
273
+ throw new XgateError("invalid_response");
274
+ }
275
+ }
@@ -0,0 +1,72 @@
1
+ import { XgateError, type Invocation, type PurchaseResult } from "@lucid-agents/xgate-client/types";
2
+ /** Response metadata safe to show Pi's `onResponse` hook: never payment or status credentials. */
3
+ export interface XgateResponseHead {
4
+ status: number;
5
+ headers: Record<string, string>;
6
+ }
7
+ /**
8
+ * Rail-neutral payment terms and status for display. Pi shows them; it never selects or
9
+ * configures a rail. Amounts are unsigned integer strings in the asset's smallest unit, and
10
+ * amounts of different assets are never combined.
11
+ */
12
+ export interface XgatePayment {
13
+ /** CAIP-2 network, e.g. `eip155:8453`. */
14
+ network: string;
15
+ /** Payment scheme as the payee advertised it, e.g. `batch-settlement`, `exact`, `session`. */
16
+ scheme: string;
17
+ asset: string;
18
+ payTo?: string;
19
+ /** Rail shape: `per-request` or `session` today; other values may appear. */
20
+ rail?: string;
21
+ /** Most this invocation could be charged. */
22
+ authorizedAtomic: string;
23
+ /** Verified charge, once known. */
24
+ chargedAtomic?: string;
25
+ /** `settled`, `pending`, `amount_unknown`, `released`, ...; anything but `settled` is unverified. */
26
+ status: string;
27
+ /** Settlement transaction or payee commitment, when one exists. */
28
+ reference?: string;
29
+ /** Session-rail balance after this payment, when the host reports one. */
30
+ channel?: XgateChannelBalance;
31
+ }
32
+ export interface XgateChannelBalance {
33
+ depositingAtomic: string;
34
+ lockedAtomic: string;
35
+ chargedAtomic: string;
36
+ pendingAtomic: string;
37
+ refundableAtomic: string;
38
+ }
39
+ export interface XgatePurchaseResult extends PurchaseResult {
40
+ payment?: XgatePayment;
41
+ }
42
+ /**
43
+ * A purchase that ended without a verified result. `pending` is true when money may have moved
44
+ * and the outcome is unknown: the invocation must be reconciled, never retried.
45
+ */
46
+ export declare class XgatePurchaseError extends XgateError {
47
+ readonly invocationId: string;
48
+ readonly pending: boolean;
49
+ readonly payment?: XgatePayment;
50
+ constructor(code: string, invocationId: string, pending: boolean, payment?: XgatePayment);
51
+ }
52
+ /**
53
+ * Moves one frozen Pi request to xgate and returns the verified result. The provider owns
54
+ * catalog qualification, codecs and the invocation ID; the transport owns payment.
55
+ *
56
+ * `purchase` sends at most one paid submission per `Invocation.id`, never retries a paid
57
+ * request, and never pays again for an ID it has seen: a repeated ID rejects. It resolves
58
+ * only with a verified result and rejects on every other outcome, preferably with an
59
+ * `XgatePurchaseError` stating whether the payment is pending. `BrokerClient` is the
60
+ * standalone implementation.
61
+ */
62
+ export interface XgateTransport {
63
+ /** Current router catalog rows. Called before every paid invocation. */
64
+ models(signal?: AbortSignal): Promise<unknown[]>;
65
+ purchase(invocation: Invocation, signal?: AbortSignal, onResponse?: (response: XgateResponseHead) => Promise<void>): Promise<XgatePurchaseResult>;
66
+ /** Optional `/xgate status` and `/xgate budget` view. */
67
+ status?(signal?: AbortSignal): Promise<unknown>;
68
+ /** Optional `/xgate receipts` view. */
69
+ receipts?(signal?: AbortSignal): Promise<unknown>;
70
+ /** Optional `/xgate reconcile <invocation ID>`. Never resends the request. */
71
+ reconcile?(invocationId: string, signal?: AbortSignal): Promise<unknown>;
72
+ }
@@ -0,0 +1,21 @@
1
+ import { XgateError, } from "@lucid-agents/xgate-client/types";
2
+ /**
3
+ * A purchase that ended without a verified result. `pending` is true when money may have moved
4
+ * and the outcome is unknown: the invocation must be reconciled, never retried.
5
+ */
6
+ export class XgatePurchaseError extends XgateError {
7
+ invocationId;
8
+ pending;
9
+ payment;
10
+ constructor(code, invocationId, pending, payment) {
11
+ super(code);
12
+ this.name = "XgatePurchaseError";
13
+ this.message = pending
14
+ ? `Xgate: ${code}. The payment outcome is unknown; do not retry. Reconcile it before another purchase.`
15
+ : `Xgate: ${code}. Inspect the payment status before another purchase.`;
16
+ this.invocationId = invocationId;
17
+ this.pending = pending;
18
+ if (payment)
19
+ this.payment = payment;
20
+ }
21
+ }
package/package.json CHANGED
@@ -1,6 +1,65 @@
1
1
  {
2
2
  "name": "@lucid-agents/pi-xgate",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.6",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": {
7
+ "types": "./dist/index.d.ts",
8
+ "default": "./dist/index.js"
9
+ },
10
+ "./extension": {
11
+ "types": "./dist/extension.d.ts",
12
+ "default": "./dist/extension.js"
13
+ },
14
+ "./package.json": "./package.json"
15
+ },
16
+ "keywords": [
17
+ "pi-package",
18
+ "xgate",
19
+ "x402",
20
+ "mpp",
21
+ "lucid-agents"
22
+ ],
23
+ "pi": {
24
+ "extensions": [
25
+ "./src/extension.ts"
26
+ ]
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "src",
31
+ "README.md",
32
+ "LICENSE"
33
+ ],
34
+ "dependencies": {
35
+ "@lucid-agents/xgate-client": "0.1.6"
36
+ },
37
+ "peerDependencies": {
38
+ "@earendil-works/pi-ai": "0.85.1 || 1.1.0",
39
+ "@earendil-works/pi-coding-agent": "0.85.1 || 1.1.0"
40
+ },
41
+ "engines": {
42
+ "node": ">=24.19 <25"
43
+ },
44
+ "description": "Wallet-paid OpenAI and Anthropic inference through xgate for the Pi coding agent",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/daydreamsai/402-router.git",
48
+ "directory": "packages/pi-xgate"
49
+ },
50
+ "homepage": "https://github.com/daydreamsai/402-router/tree/main/packages/pi-xgate",
51
+ "bugs": {
52
+ "url": "https://github.com/daydreamsai/402-router/issues"
53
+ },
54
+ "publishConfig": {
55
+ "access": "public",
56
+ "registry": "https://registry.npmjs.org"
57
+ },
58
+ "license": "MIT",
59
+ "gitHead": "f26a9cdf35db07e8aa6b6ad7c6408884aa283ebc",
60
+ "xgateRelease": {
61
+ "version": "v0.1.6",
62
+ "sourceSha": "f26a9cdf35db07e8aa6b6ad7c6408884aa283ebc",
63
+ "candidateId": "rc-f26a9cdf35db-38096296216-1"
64
+ }
65
+ }