@vinaystwt/xmpp-mcp 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 +21 -0
- package/README.md +10 -0
- package/dist/apps/mcp-server/src/index.d.ts +2 -0
- package/dist/apps/mcp-server/src/index.js +10 -0
- package/dist/apps/mcp-server/src/server.d.ts +9 -0
- package/dist/apps/mcp-server/src/server.js +232 -0
- package/dist/packages/config/src/index.d.ts +49 -0
- package/dist/packages/config/src/index.js +117 -0
- package/dist/packages/contract-runtime/src/index.d.ts +44 -0
- package/dist/packages/contract-runtime/src/index.js +364 -0
- package/dist/packages/http-interceptor/src/agents.d.ts +5 -0
- package/dist/packages/http-interceptor/src/agents.js +88 -0
- package/dist/packages/http-interceptor/src/idempotency.d.ts +68 -0
- package/dist/packages/http-interceptor/src/idempotency.js +149 -0
- package/dist/packages/http-interceptor/src/index.d.ts +10 -0
- package/dist/packages/http-interceptor/src/index.js +870 -0
- package/dist/packages/http-interceptor/src/state.d.ts +17 -0
- package/dist/packages/http-interceptor/src/state.js +188 -0
- package/dist/packages/logger/src/index.d.ts +2 -0
- package/dist/packages/logger/src/index.js +18 -0
- package/dist/packages/payment-adapters/src/index.d.ts +27 -0
- package/dist/packages/payment-adapters/src/index.js +512 -0
- package/dist/packages/policy-engine/src/index.d.ts +8 -0
- package/dist/packages/policy-engine/src/index.js +90 -0
- package/dist/packages/router/src/index.d.ts +23 -0
- package/dist/packages/router/src/index.js +432 -0
- package/dist/packages/types/src/index.d.ts +343 -0
- package/dist/packages/types/src/index.js +1 -0
- package/dist/packages/wallet/src/index.d.ts +14 -0
- package/dist/packages/wallet/src/index.js +250 -0
- package/package.json +69 -0
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import { Keypair } from '@stellar/stellar-sdk';
|
|
2
|
+
import { Client, basicNodeSigner } from '@stellar/stellar-sdk/contract';
|
|
3
|
+
import { config } from '@xmpp/config';
|
|
4
|
+
import { logger } from '@xmpp/logger';
|
|
5
|
+
let policyClientPromise;
|
|
6
|
+
let sessionRegistryClientPromise;
|
|
7
|
+
let policyClientDisabled = false;
|
|
8
|
+
let sessionRegistryClientDisabled = false;
|
|
9
|
+
function contractRuntimeEnabled() {
|
|
10
|
+
return process.env.VITEST !== 'true' && process.env.XMPP_DISABLE_CONTRACT_RUNTIME !== 'true';
|
|
11
|
+
}
|
|
12
|
+
function toNumber(value) {
|
|
13
|
+
return value == null ? 0 : Number(value);
|
|
14
|
+
}
|
|
15
|
+
function normalizeStringList(value) {
|
|
16
|
+
if (Array.isArray(value)) {
|
|
17
|
+
return value.map((entry) => String(entry));
|
|
18
|
+
}
|
|
19
|
+
if (value && typeof value === 'object' && Symbol.iterator in value) {
|
|
20
|
+
return [...value].map((entry) => String(entry));
|
|
21
|
+
}
|
|
22
|
+
return [];
|
|
23
|
+
}
|
|
24
|
+
function getAgentKeypair() {
|
|
25
|
+
if (!config.wallet.agentSecretKey) {
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
try {
|
|
29
|
+
return Keypair.fromSecret(config.wallet.agentSecretKey);
|
|
30
|
+
}
|
|
31
|
+
catch (error) {
|
|
32
|
+
logger.warn({ error }, '[xMPP] failed to parse agent secret key for contract runtime');
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
function getClientOptions(contractId) {
|
|
37
|
+
const keypair = getAgentKeypair();
|
|
38
|
+
if (!keypair) {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
return {
|
|
42
|
+
contractId,
|
|
43
|
+
rpcUrl: config.rpcUrl,
|
|
44
|
+
networkPassphrase: config.networkPassphrase,
|
|
45
|
+
allowHttp: config.rpcUrl.startsWith('http://'),
|
|
46
|
+
publicKey: keypair.publicKey(),
|
|
47
|
+
...basicNodeSigner(keypair, config.networkPassphrase),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
async function createClient(contractId, label) {
|
|
51
|
+
const options = getClientOptions(contractId);
|
|
52
|
+
if (!options) {
|
|
53
|
+
logger.debug({ label }, '[xMPP] contract runtime disabled because no agent signer is available');
|
|
54
|
+
return null;
|
|
55
|
+
}
|
|
56
|
+
try {
|
|
57
|
+
return (await Client.from(options));
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
logger.warn({ error, contractId, label }, '[xMPP] failed to create Soroban contract client');
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
function hasMethod(client, method, label) {
|
|
65
|
+
if (typeof client[method] === 'function') {
|
|
66
|
+
return true;
|
|
67
|
+
}
|
|
68
|
+
logger.warn({ label, method }, '[xMPP] contract method is unavailable on deployed contract');
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
async function getPolicyClient() {
|
|
72
|
+
if (!contractRuntimeEnabled() || !config.contracts.policyContractId || policyClientDisabled) {
|
|
73
|
+
return null;
|
|
74
|
+
}
|
|
75
|
+
policyClientPromise ??= createClient(config.contracts.policyContractId, 'policy');
|
|
76
|
+
const client = await policyClientPromise;
|
|
77
|
+
if (!client) {
|
|
78
|
+
policyClientDisabled = true;
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
if (!hasMethod(client, 'get_global_policy', 'policy') || !hasMethod(client, 'pause_flag', 'policy')) {
|
|
82
|
+
policyClientDisabled = true;
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
return client;
|
|
86
|
+
}
|
|
87
|
+
async function getSessionRegistryClient() {
|
|
88
|
+
if (!contractRuntimeEnabled() ||
|
|
89
|
+
!config.contracts.sessionRegistryContractId ||
|
|
90
|
+
sessionRegistryClientDisabled) {
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
sessionRegistryClientPromise ??= createClient(config.contracts.sessionRegistryContractId, 'session-registry');
|
|
94
|
+
const client = await sessionRegistryClientPromise;
|
|
95
|
+
if (!client) {
|
|
96
|
+
sessionRegistryClientDisabled = true;
|
|
97
|
+
return null;
|
|
98
|
+
}
|
|
99
|
+
if (!hasMethod(client, 'upsert_session', 'session-registry')) {
|
|
100
|
+
sessionRegistryClientDisabled = true;
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
return client;
|
|
104
|
+
}
|
|
105
|
+
function normalizeGlobalPolicy(policy) {
|
|
106
|
+
return {
|
|
107
|
+
maxSpendUsdCents: toNumber(policy.max_spend_usd_cents),
|
|
108
|
+
allowUnknownServices: policy.allow_unknown_services,
|
|
109
|
+
allowPostAutopay: policy.allow_post_autopay,
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
function normalizeServicePolicy(policy) {
|
|
113
|
+
if (!policy) {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
serviceId: policy.service_id,
|
|
118
|
+
enabled: policy.enabled,
|
|
119
|
+
maxSpendUsdCents: toNumber(policy.max_spend_usd_cents),
|
|
120
|
+
preferredRoute: policy.preferred_route,
|
|
121
|
+
allowSessionReuse: policy.allow_session_reuse,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
function normalizeAgentPolicy(policy) {
|
|
125
|
+
if (!policy) {
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
agentId: policy.agent_id,
|
|
130
|
+
enabled: policy.enabled,
|
|
131
|
+
dailyBudgetUsd: toNumber(policy.daily_budget_usd_cents) / 100,
|
|
132
|
+
allowedServices: normalizeStringList(policy.allowed_services),
|
|
133
|
+
preferredRoutes: normalizeStringList(policy.preferred_routes),
|
|
134
|
+
autopayMethods: normalizeStringList(policy.autopay_methods),
|
|
135
|
+
source: 'contract',
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
function normalizeTreasurySnapshot(snapshot) {
|
|
139
|
+
if (!snapshot) {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
const sharedTreasuryUsd = toNumber(snapshot.shared_treasury_usd_cents) / 100;
|
|
143
|
+
const totalSpentUsd = toNumber(snapshot.total_spent_usd_cents) / 100;
|
|
144
|
+
return {
|
|
145
|
+
sharedTreasuryUsd,
|
|
146
|
+
totalSpentUsd,
|
|
147
|
+
remainingUsd: Math.max(0, sharedTreasuryUsd - totalSpentUsd),
|
|
148
|
+
paymentCount: Number(snapshot.payment_count ?? 0),
|
|
149
|
+
source: 'contract',
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
function normalizeAgentTreasuryState(state) {
|
|
153
|
+
if (!state) {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
agentId: state.agent_id,
|
|
158
|
+
spentUsd: toNumber(state.spent_usd_cents) / 100,
|
|
159
|
+
paymentCount: Number(state.payment_count ?? 0),
|
|
160
|
+
lastServiceId: state.last_service_id,
|
|
161
|
+
lastRoute: state.last_route,
|
|
162
|
+
source: 'contract',
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function normalizeSessionRecord(record) {
|
|
166
|
+
return {
|
|
167
|
+
sessionId: String(record.session_id ?? ''),
|
|
168
|
+
serviceId: String(record.service_id ?? ''),
|
|
169
|
+
agent: String(record.agent ?? ''),
|
|
170
|
+
channelContractId: String(record.channel_contract_id ?? ''),
|
|
171
|
+
route: String(record.route ?? ''),
|
|
172
|
+
status: String(record.status ?? ''),
|
|
173
|
+
totalAmountUsdCents: toNumber(record.total_amount_usd_cents),
|
|
174
|
+
callCount: Number(record.call_count ?? 0),
|
|
175
|
+
lastReceiptId: String(record.last_receipt_id ?? ''),
|
|
176
|
+
updatedAtLedger: Number(record.updated_at_ledger ?? 0),
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
export async function getAgentPolicySnapshot(agentId) {
|
|
180
|
+
const client = await getPolicyClient();
|
|
181
|
+
if (!client || !hasMethod(client, 'get_agent_policy', 'policy')) {
|
|
182
|
+
return {
|
|
183
|
+
source: 'local',
|
|
184
|
+
agentPolicy: null,
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
try {
|
|
188
|
+
const tx = await client.get_agent_policy({ agent_id: agentId });
|
|
189
|
+
return {
|
|
190
|
+
source: 'contract',
|
|
191
|
+
agentPolicy: normalizeAgentPolicy(tx.result ?? null),
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
catch (error) {
|
|
195
|
+
logger.warn({ error, agentId }, '[xMPP] failed to read agent policy from contract, falling back');
|
|
196
|
+
return {
|
|
197
|
+
source: 'fallback',
|
|
198
|
+
agentPolicy: null,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
export async function listAgentPolicySnapshots() {
|
|
203
|
+
const client = await getPolicyClient();
|
|
204
|
+
if (!client || !hasMethod(client, 'list_agent_policies', 'policy')) {
|
|
205
|
+
return [];
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
const tx = await client.list_agent_policies();
|
|
209
|
+
const result = tx.result;
|
|
210
|
+
return Array.isArray(result)
|
|
211
|
+
? result.filter((entry) => Boolean(entry)).flatMap((entry) => {
|
|
212
|
+
const normalized = normalizeAgentPolicy(entry);
|
|
213
|
+
return normalized ? [normalized] : [];
|
|
214
|
+
})
|
|
215
|
+
: [];
|
|
216
|
+
}
|
|
217
|
+
catch (error) {
|
|
218
|
+
logger.warn({ error }, '[xMPP] failed to list agent policies from contract');
|
|
219
|
+
return [];
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
export async function getTreasurySnapshot() {
|
|
223
|
+
const client = await getPolicyClient();
|
|
224
|
+
if (!client || !hasMethod(client, 'get_treasury_snapshot', 'policy')) {
|
|
225
|
+
return null;
|
|
226
|
+
}
|
|
227
|
+
try {
|
|
228
|
+
const tx = await client.get_treasury_snapshot();
|
|
229
|
+
return normalizeTreasurySnapshot(tx.result ?? null);
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
logger.warn({ error }, '[xMPP] failed to read treasury snapshot from contract');
|
|
233
|
+
return null;
|
|
234
|
+
}
|
|
235
|
+
}
|
|
236
|
+
export async function getAgentTreasuryState(agentId) {
|
|
237
|
+
const client = await getPolicyClient();
|
|
238
|
+
if (!client || !hasMethod(client, 'get_agent_treasury_state', 'policy')) {
|
|
239
|
+
return null;
|
|
240
|
+
}
|
|
241
|
+
try {
|
|
242
|
+
const tx = await client.get_agent_treasury_state({ agent_id: agentId });
|
|
243
|
+
return normalizeAgentTreasuryState(tx.result ?? null);
|
|
244
|
+
}
|
|
245
|
+
catch (error) {
|
|
246
|
+
logger.warn({ error, agentId }, '[xMPP] failed to read agent treasury state from contract');
|
|
247
|
+
return null;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
export async function listAgentTreasuryStates() {
|
|
251
|
+
const client = await getPolicyClient();
|
|
252
|
+
if (!client || !hasMethod(client, 'list_agent_treasury_states', 'policy')) {
|
|
253
|
+
return [];
|
|
254
|
+
}
|
|
255
|
+
try {
|
|
256
|
+
const tx = await client.list_agent_treasury_states();
|
|
257
|
+
const result = tx.result;
|
|
258
|
+
return Array.isArray(result)
|
|
259
|
+
? result.flatMap((entry) => {
|
|
260
|
+
const normalized = normalizeAgentTreasuryState(entry);
|
|
261
|
+
return normalized ? [normalized] : [];
|
|
262
|
+
})
|
|
263
|
+
: [];
|
|
264
|
+
}
|
|
265
|
+
catch (error) {
|
|
266
|
+
logger.warn({ error }, '[xMPP] failed to list agent treasury states from contract');
|
|
267
|
+
return [];
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
export async function getPolicyRuntimeSnapshot(serviceId) {
|
|
271
|
+
const client = await getPolicyClient();
|
|
272
|
+
if (!client) {
|
|
273
|
+
return {
|
|
274
|
+
source: 'local',
|
|
275
|
+
pauseFlag: false,
|
|
276
|
+
globalPolicy: null,
|
|
277
|
+
servicePolicy: null,
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
try {
|
|
281
|
+
const globalPolicyTx = await client.get_global_policy();
|
|
282
|
+
const pauseFlagTx = await client.pause_flag();
|
|
283
|
+
const servicePolicyTx = serviceId && hasMethod(client, 'get_service_policy', 'policy')
|
|
284
|
+
? await client.get_service_policy({ service_id: serviceId })
|
|
285
|
+
: null;
|
|
286
|
+
return {
|
|
287
|
+
source: 'contract',
|
|
288
|
+
pauseFlag: Boolean(pauseFlagTx.result),
|
|
289
|
+
globalPolicy: normalizeGlobalPolicy(globalPolicyTx.result),
|
|
290
|
+
servicePolicy: normalizeServicePolicy(servicePolicyTx?.result ?? null),
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
catch (error) {
|
|
294
|
+
logger.warn({ error, serviceId }, '[xMPP] failed to read policy from contract, falling back');
|
|
295
|
+
return {
|
|
296
|
+
source: 'fallback',
|
|
297
|
+
pauseFlag: false,
|
|
298
|
+
globalPolicy: null,
|
|
299
|
+
servicePolicy: null,
|
|
300
|
+
};
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
export async function recordTreasurySpend(input) {
|
|
304
|
+
const client = await getPolicyClient();
|
|
305
|
+
if (!client || !hasMethod(client, 'record_treasury_spend', 'policy')) {
|
|
306
|
+
return null;
|
|
307
|
+
}
|
|
308
|
+
try {
|
|
309
|
+
const tx = await client.record_treasury_spend({
|
|
310
|
+
agent_id: input.agentId,
|
|
311
|
+
service_id: input.serviceId,
|
|
312
|
+
route: input.route,
|
|
313
|
+
amount_usd_cents: BigInt(input.amountUsdCents),
|
|
314
|
+
});
|
|
315
|
+
const sent = await tx.signAndSend();
|
|
316
|
+
return normalizeAgentTreasuryState(sent.result);
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
logger.warn({ error, input }, '[xMPP] failed to record treasury spend in contract');
|
|
320
|
+
return null;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
export async function recordSessionRouteEvent(input) {
|
|
324
|
+
const client = await getSessionRegistryClient();
|
|
325
|
+
const keypair = getAgentKeypair();
|
|
326
|
+
if (!client || !keypair) {
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
try {
|
|
330
|
+
const tx = await client.upsert_session({
|
|
331
|
+
agent: keypair.publicKey(),
|
|
332
|
+
session_id: input.sessionId,
|
|
333
|
+
service_id: input.serviceId,
|
|
334
|
+
channel_contract_id: config.mpp.channelContractId ?? '',
|
|
335
|
+
route: input.route,
|
|
336
|
+
total_amount_usd_cents: BigInt(input.totalAmountUsdCents ?? 0),
|
|
337
|
+
call_count: input.callCount,
|
|
338
|
+
last_receipt_id: input.receiptId,
|
|
339
|
+
status: input.status,
|
|
340
|
+
});
|
|
341
|
+
const sent = await tx.signAndSend();
|
|
342
|
+
return normalizeSessionRecord(sent.result);
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
logger.warn({ error, input }, '[xMPP] failed to write session route event to contract');
|
|
346
|
+
return null;
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
export async function listAgentSessions() {
|
|
350
|
+
const client = await getSessionRegistryClient();
|
|
351
|
+
const keypair = getAgentKeypair();
|
|
352
|
+
if (!client || !keypair || !hasMethod(client, 'list_agent_sessions', 'session-registry')) {
|
|
353
|
+
return [];
|
|
354
|
+
}
|
|
355
|
+
try {
|
|
356
|
+
const tx = await client.list_agent_sessions({ agent: keypair.publicKey() });
|
|
357
|
+
const result = tx.result;
|
|
358
|
+
return Array.isArray(result) ? result.map(normalizeSessionRecord) : [];
|
|
359
|
+
}
|
|
360
|
+
catch (error) {
|
|
361
|
+
logger.warn({ error }, '[xMPP] failed to list agent sessions from contract');
|
|
362
|
+
return [];
|
|
363
|
+
}
|
|
364
|
+
}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { XmppAgentPolicySnapshot, XmppAgentProfile } from '@xmpp/types';
|
|
2
|
+
export declare function listXmppAgentProfiles(): XmppAgentProfile[];
|
|
3
|
+
export declare function getXmppAgentProfile(agentId?: string): XmppAgentProfile;
|
|
4
|
+
export declare function applyAgentPolicy(profile: XmppAgentProfile, policy: XmppAgentPolicySnapshot | null | undefined): XmppAgentProfile;
|
|
5
|
+
export declare function mergeAgentPolicies(profiles: XmppAgentProfile[], policies: XmppAgentPolicySnapshot[]): XmppAgentProfile[];
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { config } from '@xmpp/config';
|
|
2
|
+
const ALL_ROUTES = ['x402', 'mpp-charge', 'mpp-session-open', 'mpp-session-reuse'];
|
|
3
|
+
const ROUTE_SET = new Set(ALL_ROUTES);
|
|
4
|
+
function roundUsd(value) {
|
|
5
|
+
return Math.round(value * 1000) / 1000;
|
|
6
|
+
}
|
|
7
|
+
function normalizeRoutes(routes) {
|
|
8
|
+
return routes.filter((route) => ROUTE_SET.has(route));
|
|
9
|
+
}
|
|
10
|
+
function normalizeAutopayMethods(methods) {
|
|
11
|
+
return [...new Set(methods.map((method) => method.toUpperCase()))];
|
|
12
|
+
}
|
|
13
|
+
function buildAgentProfiles() {
|
|
14
|
+
const researchBudget = roundUsd(config.dailyBudgetUsd * 0.3);
|
|
15
|
+
const marketBudget = roundUsd(config.dailyBudgetUsd * 0.7);
|
|
16
|
+
return [
|
|
17
|
+
{
|
|
18
|
+
agentId: 'shared-treasury',
|
|
19
|
+
displayName: 'Shared Treasury',
|
|
20
|
+
role: 'shared',
|
|
21
|
+
description: 'Default unrestricted orchestrator agent backed by the common wallet.',
|
|
22
|
+
dailyBudgetUsd: roundUsd(config.dailyBudgetUsd),
|
|
23
|
+
allowedServices: ['research-api', 'market-api', 'stream-api'],
|
|
24
|
+
preferredRoutes: ALL_ROUTES,
|
|
25
|
+
autopayMethods: ['GET', 'HEAD'],
|
|
26
|
+
enabled: true,
|
|
27
|
+
policySource: 'local',
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
agentId: 'research-agent',
|
|
31
|
+
displayName: 'Research Agent',
|
|
32
|
+
role: 'research',
|
|
33
|
+
description: 'Low-risk research worker limited to exact x402 calls on the research API.',
|
|
34
|
+
dailyBudgetUsd: researchBudget,
|
|
35
|
+
allowedServices: ['research-api'],
|
|
36
|
+
preferredRoutes: ['x402'],
|
|
37
|
+
autopayMethods: ['GET'],
|
|
38
|
+
enabled: true,
|
|
39
|
+
policySource: 'local',
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
agentId: 'market-agent',
|
|
43
|
+
displayName: 'Market Agent',
|
|
44
|
+
role: 'market',
|
|
45
|
+
description: 'Higher-ceiling market worker optimized for premium quotes and reusable session flows.',
|
|
46
|
+
dailyBudgetUsd: marketBudget,
|
|
47
|
+
allowedServices: ['market-api', 'stream-api'],
|
|
48
|
+
preferredRoutes: ['mpp-charge', 'mpp-session-open', 'mpp-session-reuse'],
|
|
49
|
+
autopayMethods: ['GET'],
|
|
50
|
+
enabled: true,
|
|
51
|
+
policySource: 'local',
|
|
52
|
+
},
|
|
53
|
+
];
|
|
54
|
+
}
|
|
55
|
+
export function listXmppAgentProfiles() {
|
|
56
|
+
return buildAgentProfiles();
|
|
57
|
+
}
|
|
58
|
+
export function getXmppAgentProfile(agentId) {
|
|
59
|
+
const profiles = buildAgentProfiles();
|
|
60
|
+
if (!agentId) {
|
|
61
|
+
return profiles[0];
|
|
62
|
+
}
|
|
63
|
+
return profiles.find((profile) => profile.agentId === agentId) ?? profiles[0];
|
|
64
|
+
}
|
|
65
|
+
export function applyAgentPolicy(profile, policy) {
|
|
66
|
+
if (!policy) {
|
|
67
|
+
return {
|
|
68
|
+
...profile,
|
|
69
|
+
enabled: profile.enabled ?? true,
|
|
70
|
+
policySource: profile.policySource ?? 'local',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
const preferredRoutes = normalizeRoutes(policy.preferredRoutes);
|
|
74
|
+
const autopayMethods = normalizeAutopayMethods(policy.autopayMethods);
|
|
75
|
+
return {
|
|
76
|
+
...profile,
|
|
77
|
+
dailyBudgetUsd: policy.dailyBudgetUsd > 0 ? roundUsd(policy.dailyBudgetUsd) : profile.dailyBudgetUsd,
|
|
78
|
+
allowedServices: policy.allowedServices.length > 0 ? [...policy.allowedServices] : profile.allowedServices,
|
|
79
|
+
preferredRoutes: preferredRoutes.length > 0 ? preferredRoutes : profile.preferredRoutes,
|
|
80
|
+
autopayMethods: autopayMethods.length > 0 ? autopayMethods : profile.autopayMethods,
|
|
81
|
+
enabled: policy.enabled,
|
|
82
|
+
policySource: 'merged',
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
export function mergeAgentPolicies(profiles, policies) {
|
|
86
|
+
const policiesByAgentId = new Map(policies.map((policy) => [policy.agentId, policy]));
|
|
87
|
+
return profiles.map((profile) => applyAgentPolicy(profile, policiesByAgentId.get(profile.agentId)));
|
|
88
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import type { XmppFetchMetadata, XmppFetchOptions } from '@xmpp/types';
|
|
2
|
+
type IdempotencySnapshot = {
|
|
3
|
+
fingerprint: string;
|
|
4
|
+
storedAt: number;
|
|
5
|
+
inflight: boolean;
|
|
6
|
+
response?: {
|
|
7
|
+
status: number;
|
|
8
|
+
statusText: string;
|
|
9
|
+
headers: Record<string, string>;
|
|
10
|
+
body: string;
|
|
11
|
+
metadata: XmppFetchMetadata;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
export declare function inspectIdempotency(url: string, method: string, init?: RequestInit, options?: XmppFetchOptions): {
|
|
15
|
+
allowed: true;
|
|
16
|
+
code?: undefined;
|
|
17
|
+
reason?: undefined;
|
|
18
|
+
idempotencyKey?: undefined;
|
|
19
|
+
fingerprint?: undefined;
|
|
20
|
+
replay?: undefined;
|
|
21
|
+
response?: undefined;
|
|
22
|
+
} | {
|
|
23
|
+
allowed: false;
|
|
24
|
+
code: string;
|
|
25
|
+
reason: string;
|
|
26
|
+
idempotencyKey?: undefined;
|
|
27
|
+
fingerprint?: undefined;
|
|
28
|
+
replay?: undefined;
|
|
29
|
+
response?: undefined;
|
|
30
|
+
} | {
|
|
31
|
+
allowed: true;
|
|
32
|
+
idempotencyKey: string;
|
|
33
|
+
fingerprint: string;
|
|
34
|
+
code?: undefined;
|
|
35
|
+
reason?: undefined;
|
|
36
|
+
replay?: undefined;
|
|
37
|
+
response?: undefined;
|
|
38
|
+
} | {
|
|
39
|
+
allowed: true;
|
|
40
|
+
idempotencyKey: string;
|
|
41
|
+
fingerprint: string;
|
|
42
|
+
replay: true;
|
|
43
|
+
response: {
|
|
44
|
+
status: number;
|
|
45
|
+
statusText: string;
|
|
46
|
+
headers: Record<string, string>;
|
|
47
|
+
body: string;
|
|
48
|
+
metadata: XmppFetchMetadata;
|
|
49
|
+
};
|
|
50
|
+
code?: undefined;
|
|
51
|
+
reason?: undefined;
|
|
52
|
+
};
|
|
53
|
+
export declare function storeIdempotentResponse(idempotencyKey: string, fingerprint: string, response: Response, metadata: XmppFetchMetadata): Promise<void>;
|
|
54
|
+
export declare function clearIdempotentReservation(idempotencyKey: string, fingerprint: string): void;
|
|
55
|
+
export declare function buildIdempotentReplay(snapshot: IdempotencySnapshot['response']): {
|
|
56
|
+
response: Response;
|
|
57
|
+
metadata: {
|
|
58
|
+
idempotentReplay: boolean;
|
|
59
|
+
route: import("@xmpp/types").RouteKind;
|
|
60
|
+
challenge?: import("@xmpp/types").PaymentChallenge;
|
|
61
|
+
retried: boolean;
|
|
62
|
+
execution?: import("@xmpp/types").PaymentExecutionMetadata;
|
|
63
|
+
policy?: import("@xmpp/types").PolicyDecision;
|
|
64
|
+
budget?: import("@xmpp/types").XmppBudgetSnapshot;
|
|
65
|
+
};
|
|
66
|
+
} | null;
|
|
67
|
+
export declare function resetIdempotencyCache(): void;
|
|
68
|
+
export {};
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
const IDEMPOTENCY_TTL_MS = 60 * 60 * 1000;
|
|
3
|
+
const idempotencyCache = new Map();
|
|
4
|
+
function normalizeBody(body) {
|
|
5
|
+
if (body == null) {
|
|
6
|
+
return '';
|
|
7
|
+
}
|
|
8
|
+
if (typeof body === 'string') {
|
|
9
|
+
return body;
|
|
10
|
+
}
|
|
11
|
+
if (body instanceof URLSearchParams) {
|
|
12
|
+
return body.toString();
|
|
13
|
+
}
|
|
14
|
+
if (body instanceof FormData) {
|
|
15
|
+
const entries = [];
|
|
16
|
+
body.forEach((value, key) => {
|
|
17
|
+
entries.push(`${key}=${typeof value === 'string' ? value : value.name}`);
|
|
18
|
+
});
|
|
19
|
+
return entries.join('&');
|
|
20
|
+
}
|
|
21
|
+
return '[stream]';
|
|
22
|
+
}
|
|
23
|
+
function cleanupExpired() {
|
|
24
|
+
const cutoff = Date.now() - IDEMPOTENCY_TTL_MS;
|
|
25
|
+
for (const [key, snapshot] of idempotencyCache.entries()) {
|
|
26
|
+
if (snapshot.storedAt < cutoff) {
|
|
27
|
+
idempotencyCache.delete(key);
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function buildFingerprint(url, method, init) {
|
|
32
|
+
const headers = new Headers(init?.headers);
|
|
33
|
+
const headerPairs = [];
|
|
34
|
+
headers.forEach((value, key) => {
|
|
35
|
+
headerPairs.push(`${key.toLowerCase()}=${value}`);
|
|
36
|
+
});
|
|
37
|
+
headerPairs.sort();
|
|
38
|
+
return createHash('sha256')
|
|
39
|
+
.update(JSON.stringify({
|
|
40
|
+
url,
|
|
41
|
+
method: method.toUpperCase(),
|
|
42
|
+
headers: headerPairs,
|
|
43
|
+
body: normalizeBody(init?.body),
|
|
44
|
+
}))
|
|
45
|
+
.digest('hex');
|
|
46
|
+
}
|
|
47
|
+
function resolveIdempotencyKey(init, options) {
|
|
48
|
+
const headers = new Headers(init?.headers);
|
|
49
|
+
return (options?.idempotencyKey ??
|
|
50
|
+
headers.get('idempotency-key') ??
|
|
51
|
+
headers.get('x-idempotency-key') ??
|
|
52
|
+
undefined);
|
|
53
|
+
}
|
|
54
|
+
export function inspectIdempotency(url, method, init, options) {
|
|
55
|
+
cleanupExpired();
|
|
56
|
+
const upperMethod = method.toUpperCase();
|
|
57
|
+
if (upperMethod === 'GET' || upperMethod === 'HEAD') {
|
|
58
|
+
return { allowed: true };
|
|
59
|
+
}
|
|
60
|
+
const idempotencyKey = resolveIdempotencyKey(init, options);
|
|
61
|
+
if (!idempotencyKey) {
|
|
62
|
+
return {
|
|
63
|
+
allowed: false,
|
|
64
|
+
code: 'missing-key',
|
|
65
|
+
reason: 'Automatic payment for non-GET requests requires an idempotency key.',
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
const fingerprint = buildFingerprint(url, upperMethod, init);
|
|
69
|
+
const existing = idempotencyCache.get(idempotencyKey);
|
|
70
|
+
if (!existing) {
|
|
71
|
+
idempotencyCache.set(idempotencyKey, {
|
|
72
|
+
fingerprint,
|
|
73
|
+
storedAt: Date.now(),
|
|
74
|
+
inflight: true,
|
|
75
|
+
});
|
|
76
|
+
return {
|
|
77
|
+
allowed: true,
|
|
78
|
+
idempotencyKey,
|
|
79
|
+
fingerprint,
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
if (existing.fingerprint !== fingerprint) {
|
|
83
|
+
return {
|
|
84
|
+
allowed: false,
|
|
85
|
+
code: 'mismatch',
|
|
86
|
+
reason: 'This idempotency key was already used for a different request payload.',
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (existing.inflight || !existing.response) {
|
|
90
|
+
return {
|
|
91
|
+
allowed: false,
|
|
92
|
+
code: 'inflight',
|
|
93
|
+
reason: 'An idempotent request with this key is already in progress.',
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
allowed: true,
|
|
98
|
+
idempotencyKey,
|
|
99
|
+
fingerprint,
|
|
100
|
+
replay: true,
|
|
101
|
+
response: existing.response,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
export async function storeIdempotentResponse(idempotencyKey, fingerprint, response, metadata) {
|
|
105
|
+
const body = await response.clone().text();
|
|
106
|
+
const headers = {};
|
|
107
|
+
response.headers.forEach((value, key) => {
|
|
108
|
+
headers[key] = value;
|
|
109
|
+
});
|
|
110
|
+
idempotencyCache.set(idempotencyKey, {
|
|
111
|
+
fingerprint,
|
|
112
|
+
storedAt: Date.now(),
|
|
113
|
+
inflight: false,
|
|
114
|
+
response: {
|
|
115
|
+
status: response.status,
|
|
116
|
+
statusText: response.statusText,
|
|
117
|
+
headers,
|
|
118
|
+
body,
|
|
119
|
+
metadata,
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
export function clearIdempotentReservation(idempotencyKey, fingerprint) {
|
|
124
|
+
const existing = idempotencyCache.get(idempotencyKey);
|
|
125
|
+
if (existing && existing.fingerprint === fingerprint && existing.inflight) {
|
|
126
|
+
idempotencyCache.delete(idempotencyKey);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
export function buildIdempotentReplay(snapshot) {
|
|
130
|
+
if (!snapshot) {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
const headers = new Headers(snapshot.headers);
|
|
134
|
+
headers.set('x-xmpp-idempotency-replay', 'true');
|
|
135
|
+
return {
|
|
136
|
+
response: new Response(snapshot.body, {
|
|
137
|
+
status: snapshot.status,
|
|
138
|
+
statusText: snapshot.statusText,
|
|
139
|
+
headers,
|
|
140
|
+
}),
|
|
141
|
+
metadata: {
|
|
142
|
+
...snapshot.metadata,
|
|
143
|
+
idempotentReplay: true,
|
|
144
|
+
},
|
|
145
|
+
};
|
|
146
|
+
}
|
|
147
|
+
export function resetIdempotencyCache() {
|
|
148
|
+
idempotencyCache.clear();
|
|
149
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { XmppAgentProfile, XmppFetchMetadata, XmppFetchOptions } from '@xmpp/types';
|
|
2
|
+
import { getXmppOperatorState, listLocalSessions } from './state.js';
|
|
3
|
+
import { listXmppAgentProfiles } from './agents.js';
|
|
4
|
+
export declare function getXmppMetadata(resp: Response): XmppFetchMetadata | undefined;
|
|
5
|
+
export { getXmppOperatorState, listLocalSessions, listXmppAgentProfiles };
|
|
6
|
+
export declare function resetXmppRuntimeState(): void;
|
|
7
|
+
export { resetXmppRuntimeState as resetXmppOperatorState };
|
|
8
|
+
export declare function getEffectiveXmppAgentProfile(agentId?: string): Promise<XmppAgentProfile>;
|
|
9
|
+
export declare function listEffectiveXmppAgentProfiles(): Promise<XmppAgentProfile[]>;
|
|
10
|
+
export declare function xmppFetch(input: RequestInfo | URL, init?: RequestInit, options?: XmppFetchOptions): Promise<Response>;
|