@vinaystwt/xmpp-http-interceptor 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/dist/config/src/index.d.ts +49 -0
- package/dist/config/src/index.js +117 -0
- package/dist/contract-runtime/src/index.d.ts +44 -0
- package/dist/contract-runtime/src/index.js +364 -0
- package/dist/http-interceptor/src/agents.d.ts +5 -0
- package/dist/http-interceptor/src/agents.js +88 -0
- package/dist/http-interceptor/src/agents.test.d.ts +1 -0
- package/dist/http-interceptor/src/agents.test.js +35 -0
- package/dist/http-interceptor/src/idempotency.d.ts +68 -0
- package/dist/http-interceptor/src/idempotency.js +149 -0
- package/dist/http-interceptor/src/idempotency.test.d.ts +1 -0
- package/dist/http-interceptor/src/idempotency.test.js +75 -0
- package/dist/http-interceptor/src/index.d.ts +10 -0
- package/dist/http-interceptor/src/index.js +870 -0
- package/dist/http-interceptor/src/index.test.d.ts +1 -0
- package/dist/http-interceptor/src/index.test.js +131 -0
- package/dist/http-interceptor/src/state.d.ts +17 -0
- package/dist/http-interceptor/src/state.js +188 -0
- package/dist/logger/src/index.d.ts +2 -0
- package/dist/logger/src/index.js +18 -0
- package/dist/payment-adapters/src/index.d.ts +27 -0
- package/dist/payment-adapters/src/index.js +512 -0
- package/dist/policy-engine/src/index.d.ts +8 -0
- package/dist/policy-engine/src/index.js +90 -0
- package/dist/router/src/index.d.ts +23 -0
- package/dist/router/src/index.js +432 -0
- package/dist/types/src/index.d.ts +343 -0
- package/dist/types/src/index.js +1 -0
- package/dist/wallet/src/index.d.ts +14 -0
- package/dist/wallet/src/index.js +250 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 xMPP contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export declare const config: {
|
|
2
|
+
readonly nodeEnv: string;
|
|
3
|
+
readonly network: string;
|
|
4
|
+
readonly paymentExecutionMode: "mock" | "testnet";
|
|
5
|
+
readonly rpcUrl: string;
|
|
6
|
+
readonly networkPassphrase: string;
|
|
7
|
+
readonly gatewayPort: number;
|
|
8
|
+
readonly dashboardPort: number;
|
|
9
|
+
readonly dashboardGatewayUrl: string | undefined;
|
|
10
|
+
readonly dailyBudgetUsd: number;
|
|
11
|
+
readonly facilitatorUrl: string;
|
|
12
|
+
readonly wallet: {
|
|
13
|
+
readonly agentSecretKey: string | undefined;
|
|
14
|
+
readonly smartAccountContractId: string | undefined;
|
|
15
|
+
readonly smartAccountWasmHash: string;
|
|
16
|
+
readonly webauthnVerifierAddress: string;
|
|
17
|
+
readonly ed25519VerifierAddress: string;
|
|
18
|
+
readonly spendingLimitPolicyAddress: string;
|
|
19
|
+
readonly thresholdPolicyAddress: string;
|
|
20
|
+
};
|
|
21
|
+
readonly x402: {
|
|
22
|
+
readonly facilitatorUrl: string;
|
|
23
|
+
readonly facilitatorApiKey: string | undefined;
|
|
24
|
+
readonly maxTransactionFeeStroops: number;
|
|
25
|
+
readonly facilitatorPrivateKey: string | undefined;
|
|
26
|
+
readonly recipientAddress: string | undefined;
|
|
27
|
+
};
|
|
28
|
+
readonly mpp: {
|
|
29
|
+
readonly secretKey: string | undefined;
|
|
30
|
+
readonly recipientAddress: string | undefined;
|
|
31
|
+
readonly channelContractId: string | undefined;
|
|
32
|
+
readonly feeSponsorshipEnabled: boolean;
|
|
33
|
+
readonly feeSponsorship: {
|
|
34
|
+
readonly chargeEnabled: boolean;
|
|
35
|
+
readonly sessionEnabled: boolean;
|
|
36
|
+
};
|
|
37
|
+
readonly feeSponsorSecretKey: string | undefined;
|
|
38
|
+
readonly feeBumpSecretKey: string | undefined;
|
|
39
|
+
};
|
|
40
|
+
readonly services: {
|
|
41
|
+
readonly research: string;
|
|
42
|
+
readonly market: string;
|
|
43
|
+
readonly stream: string;
|
|
44
|
+
};
|
|
45
|
+
readonly contracts: {
|
|
46
|
+
readonly policyContractId: string | undefined;
|
|
47
|
+
readonly sessionRegistryContractId: string | undefined;
|
|
48
|
+
};
|
|
49
|
+
};
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { config as loadEnv } from 'dotenv';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
const moduleDir = dirname(fileURLToPath(import.meta.url));
|
|
6
|
+
const repoRoot = resolve(moduleDir, '../../../');
|
|
7
|
+
loadEnv({ path: resolve(repoRoot, '.env') });
|
|
8
|
+
loadEnv({ path: resolve(repoRoot, '.env.local'), override: true });
|
|
9
|
+
loadEnv();
|
|
10
|
+
const envSchema = z.object({
|
|
11
|
+
NODE_ENV: z.string().default('development'),
|
|
12
|
+
XMPP_NETWORK: z.string().default('stellar:testnet'),
|
|
13
|
+
XMPP_PAYMENT_EXECUTION_MODE: z.enum(['mock', 'testnet']).default('mock'),
|
|
14
|
+
XMPP_RPC_URL: z.string().default('https://soroban-testnet.stellar.org'),
|
|
15
|
+
XMPP_NETWORK_PASSPHRASE: z.string().default('Test SDF Network ; September 2015'),
|
|
16
|
+
XMPP_GATEWAY_PORT: z.coerce.number().default(4300),
|
|
17
|
+
XMPP_DASHBOARD_PORT: z.coerce.number().default(4310),
|
|
18
|
+
XMPP_DASHBOARD_GATEWAY_URL: z.string().optional(),
|
|
19
|
+
XMPP_DAILY_BUDGET_USD: z.coerce.number().default(0.5),
|
|
20
|
+
XMPP_AGENT_SECRET_KEY: z.string().optional(),
|
|
21
|
+
XMPP_SMART_ACCOUNT_CONTRACT_ID: z.string().optional(),
|
|
22
|
+
XMPP_SMART_ACCOUNT_WASM_HASH: z
|
|
23
|
+
.string()
|
|
24
|
+
.default('3e51f5b222dec74650f0b33367acb42a41ce497f72639230463070e666abba2c'),
|
|
25
|
+
XMPP_WEBAUTHN_VERIFIER_ADDRESS: z
|
|
26
|
+
.string()
|
|
27
|
+
.default('CATPTBRWVMH5ZCIKO5HN2F4FMPXVZEXC56RKGHRXCM7EEZGGXK7PICEH'),
|
|
28
|
+
XMPP_ED25519_VERIFIER_ADDRESS: z
|
|
29
|
+
.string()
|
|
30
|
+
.default('CAIKK32K3BZJYTWVTXHZFPIEEDBR6YCVTGPABH4UQUQ4XFA3OLYXG27G'),
|
|
31
|
+
XMPP_SPENDING_LIMIT_POLICY_ADDRESS: z
|
|
32
|
+
.string()
|
|
33
|
+
.default('CBYLPYZGLQ6JVY2IQ5P23QLQPR3KAMMKMZLNWG6RUUKJDNYGPLVHK7U4'),
|
|
34
|
+
XMPP_THRESHOLD_POLICY_ADDRESS: z
|
|
35
|
+
.string()
|
|
36
|
+
.default('CDDQLFG7CV74QHWPSP6NZIPNBR2PPCMTUVYCJF4P3ONDYHODRFGR7LWC'),
|
|
37
|
+
X402_FACILITATOR_URL: z.string().default('http://localhost:4022'),
|
|
38
|
+
X402_FACILITATOR_API_KEY: z.string().optional(),
|
|
39
|
+
X402_MAX_TRANSACTION_FEE_STROOPS: z.coerce.number().default(2000000),
|
|
40
|
+
X402_RECIPIENT_ADDRESS: z.string().optional(),
|
|
41
|
+
FACILITATOR_STELLAR_PRIVATE_KEY: z.string().optional(),
|
|
42
|
+
MPP_SECRET_KEY: z.string().optional(),
|
|
43
|
+
MPP_RECIPIENT_ADDRESS: z.string().optional(),
|
|
44
|
+
MPP_CHANNEL_CONTRACT_ID: z.string().optional(),
|
|
45
|
+
XMPP_ENABLE_MPP_FEE_SPONSORSHIP: z
|
|
46
|
+
.enum(['true', 'false'])
|
|
47
|
+
.default('false')
|
|
48
|
+
.transform((value) => value === 'true'),
|
|
49
|
+
XMPP_ENABLE_MPP_CHARGE_FEE_SPONSORSHIP: z
|
|
50
|
+
.enum(['true', 'false'])
|
|
51
|
+
.optional()
|
|
52
|
+
.transform((value) => value === 'true'),
|
|
53
|
+
XMPP_ENABLE_MPP_SESSION_FEE_SPONSORSHIP: z
|
|
54
|
+
.enum(['true', 'false'])
|
|
55
|
+
.optional()
|
|
56
|
+
.transform((value) => value === 'true'),
|
|
57
|
+
XMPP_MPP_FEE_SPONSOR_SECRET_KEY: z.string().optional(),
|
|
58
|
+
XMPP_MPP_FEE_BUMP_SECRET_KEY: z.string().optional(),
|
|
59
|
+
XMPP_RESEARCH_API_URL: z.string().default('http://localhost:4101'),
|
|
60
|
+
XMPP_MARKET_API_URL: z.string().default('http://localhost:4102'),
|
|
61
|
+
XMPP_STREAM_API_URL: z.string().default('http://localhost:4103'),
|
|
62
|
+
XMPP_POLICY_CONTRACT_ID: z.string().optional(),
|
|
63
|
+
XMPP_SESSION_REGISTRY_CONTRACT_ID: z.string().optional(),
|
|
64
|
+
});
|
|
65
|
+
const env = envSchema.parse(process.env);
|
|
66
|
+
const mppFeeSponsorshipEnabled = env.XMPP_ENABLE_MPP_FEE_SPONSORSHIP;
|
|
67
|
+
const mppChargeFeeSponsorshipEnabled = env.XMPP_ENABLE_MPP_CHARGE_FEE_SPONSORSHIP ?? mppFeeSponsorshipEnabled;
|
|
68
|
+
const mppSessionFeeSponsorshipEnabled = env.XMPP_ENABLE_MPP_SESSION_FEE_SPONSORSHIP ?? mppFeeSponsorshipEnabled;
|
|
69
|
+
export const config = {
|
|
70
|
+
nodeEnv: env.NODE_ENV,
|
|
71
|
+
network: env.XMPP_NETWORK,
|
|
72
|
+
paymentExecutionMode: env.XMPP_PAYMENT_EXECUTION_MODE,
|
|
73
|
+
rpcUrl: env.XMPP_RPC_URL,
|
|
74
|
+
networkPassphrase: env.XMPP_NETWORK_PASSPHRASE,
|
|
75
|
+
gatewayPort: env.XMPP_GATEWAY_PORT,
|
|
76
|
+
dashboardPort: env.XMPP_DASHBOARD_PORT,
|
|
77
|
+
dashboardGatewayUrl: env.XMPP_DASHBOARD_GATEWAY_URL,
|
|
78
|
+
dailyBudgetUsd: env.XMPP_DAILY_BUDGET_USD,
|
|
79
|
+
facilitatorUrl: env.X402_FACILITATOR_URL,
|
|
80
|
+
wallet: {
|
|
81
|
+
agentSecretKey: env.XMPP_AGENT_SECRET_KEY,
|
|
82
|
+
smartAccountContractId: env.XMPP_SMART_ACCOUNT_CONTRACT_ID,
|
|
83
|
+
smartAccountWasmHash: env.XMPP_SMART_ACCOUNT_WASM_HASH,
|
|
84
|
+
webauthnVerifierAddress: env.XMPP_WEBAUTHN_VERIFIER_ADDRESS,
|
|
85
|
+
ed25519VerifierAddress: env.XMPP_ED25519_VERIFIER_ADDRESS,
|
|
86
|
+
spendingLimitPolicyAddress: env.XMPP_SPENDING_LIMIT_POLICY_ADDRESS,
|
|
87
|
+
thresholdPolicyAddress: env.XMPP_THRESHOLD_POLICY_ADDRESS,
|
|
88
|
+
},
|
|
89
|
+
x402: {
|
|
90
|
+
facilitatorUrl: env.X402_FACILITATOR_URL,
|
|
91
|
+
facilitatorApiKey: env.X402_FACILITATOR_API_KEY,
|
|
92
|
+
maxTransactionFeeStroops: env.X402_MAX_TRANSACTION_FEE_STROOPS,
|
|
93
|
+
facilitatorPrivateKey: env.FACILITATOR_STELLAR_PRIVATE_KEY,
|
|
94
|
+
recipientAddress: env.X402_RECIPIENT_ADDRESS,
|
|
95
|
+
},
|
|
96
|
+
mpp: {
|
|
97
|
+
secretKey: env.MPP_SECRET_KEY,
|
|
98
|
+
recipientAddress: env.MPP_RECIPIENT_ADDRESS,
|
|
99
|
+
channelContractId: env.MPP_CHANNEL_CONTRACT_ID,
|
|
100
|
+
feeSponsorshipEnabled: mppFeeSponsorshipEnabled,
|
|
101
|
+
feeSponsorship: {
|
|
102
|
+
chargeEnabled: mppChargeFeeSponsorshipEnabled,
|
|
103
|
+
sessionEnabled: mppSessionFeeSponsorshipEnabled,
|
|
104
|
+
},
|
|
105
|
+
feeSponsorSecretKey: env.XMPP_MPP_FEE_SPONSOR_SECRET_KEY,
|
|
106
|
+
feeBumpSecretKey: env.XMPP_MPP_FEE_BUMP_SECRET_KEY,
|
|
107
|
+
},
|
|
108
|
+
services: {
|
|
109
|
+
research: env.XMPP_RESEARCH_API_URL,
|
|
110
|
+
market: env.XMPP_MARKET_API_URL,
|
|
111
|
+
stream: env.XMPP_STREAM_API_URL,
|
|
112
|
+
},
|
|
113
|
+
contracts: {
|
|
114
|
+
policyContractId: env.XMPP_POLICY_CONTRACT_ID,
|
|
115
|
+
sessionRegistryContractId: env.XMPP_SESSION_REGISTRY_CONTRACT_ID,
|
|
116
|
+
},
|
|
117
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { RouteKind, XmppAgentPolicySnapshot, XmppContractAgentTreasuryState, XmppContractTreasurySnapshot, XmppSessionRecord } from '@xmpp/types';
|
|
2
|
+
export type PolicyRuntimeSnapshot = {
|
|
3
|
+
source: 'local' | 'contract' | 'fallback';
|
|
4
|
+
pauseFlag: boolean;
|
|
5
|
+
globalPolicy: {
|
|
6
|
+
maxSpendUsdCents: number;
|
|
7
|
+
allowUnknownServices: boolean;
|
|
8
|
+
allowPostAutopay: boolean;
|
|
9
|
+
} | null;
|
|
10
|
+
servicePolicy: {
|
|
11
|
+
serviceId: string;
|
|
12
|
+
enabled: boolean;
|
|
13
|
+
maxSpendUsdCents: number;
|
|
14
|
+
preferredRoute: string;
|
|
15
|
+
allowSessionReuse: boolean;
|
|
16
|
+
} | null;
|
|
17
|
+
};
|
|
18
|
+
export type AgentPolicyRuntimeSnapshot = {
|
|
19
|
+
source: 'local' | 'contract' | 'fallback';
|
|
20
|
+
agentPolicy: XmppAgentPolicySnapshot | null;
|
|
21
|
+
};
|
|
22
|
+
export type SessionRouteEventInput = {
|
|
23
|
+
sessionId: string;
|
|
24
|
+
serviceId: string;
|
|
25
|
+
route: RouteKind;
|
|
26
|
+
status: 'open' | 'reused' | 'closed';
|
|
27
|
+
callCount: number;
|
|
28
|
+
receiptId: string;
|
|
29
|
+
totalAmountUsdCents?: number;
|
|
30
|
+
};
|
|
31
|
+
export declare function getAgentPolicySnapshot(agentId: string): Promise<AgentPolicyRuntimeSnapshot>;
|
|
32
|
+
export declare function listAgentPolicySnapshots(): Promise<XmppAgentPolicySnapshot[]>;
|
|
33
|
+
export declare function getTreasurySnapshot(): Promise<XmppContractTreasurySnapshot | null>;
|
|
34
|
+
export declare function getAgentTreasuryState(agentId: string): Promise<XmppContractAgentTreasuryState | null>;
|
|
35
|
+
export declare function listAgentTreasuryStates(): Promise<XmppContractAgentTreasuryState[]>;
|
|
36
|
+
export declare function getPolicyRuntimeSnapshot(serviceId?: string): Promise<PolicyRuntimeSnapshot>;
|
|
37
|
+
export declare function recordTreasurySpend(input: {
|
|
38
|
+
agentId: string;
|
|
39
|
+
serviceId: string;
|
|
40
|
+
route: RouteKind;
|
|
41
|
+
amountUsdCents: number;
|
|
42
|
+
}): Promise<XmppContractAgentTreasuryState | null>;
|
|
43
|
+
export declare function recordSessionRouteEvent(input: SessionRouteEventInput): Promise<XmppSessionRecord | null>;
|
|
44
|
+
export declare function listAgentSessions(): Promise<XmppSessionRecord[]>;
|
|
@@ -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
|
+
}
|