@ghostspeak/sdk
Version:
TypeScript SDK for GhostSpeak AI Agent Commerce Protocol - Production Ready Beta
1,619 lines (1,611 loc) • 197 kB
JavaScript
import { __esm, __export } from './chunk-UP2VWCW5.js';
import { createSolanaClient } from 'gill';
import { address } from '@solana/addresses';
import '@solana/sysvars';
// src/types/reputation-tags.ts
var TagCategory, SkillTag, BehaviorTag, ComplianceTag, TAG_CONSTANTS, DEFAULT_TAG_DECAY, TagConfidenceLevel;
var init_reputation_tags = __esm({
"src/types/reputation-tags.ts"() {
TagCategory = /* @__PURE__ */ ((TagCategory2) => {
TagCategory2["Skill"] = "skill";
TagCategory2["Behavior"] = "behavior";
TagCategory2["Compliance"] = "compliance";
return TagCategory2;
})(TagCategory || {});
SkillTag = /* @__PURE__ */ ((SkillTag2) => {
SkillTag2["CodeGeneration"] = "code-generation";
SkillTag2["DataAnalysis"] = "data-analysis";
SkillTag2["ContentCreation"] = "content-creation";
SkillTag2["ImageGeneration"] = "image-generation";
SkillTag2["AudioProcessing"] = "audio-processing";
SkillTag2["VideoProcessing"] = "video-processing";
SkillTag2["NaturalLanguageProcessing"] = "nlp-specialist";
SkillTag2["ComputerVision"] = "computer-vision";
SkillTag2["ReinforcementLearning"] = "reinforcement-learning";
SkillTag2["DeFiExpert"] = "defi-expert";
SkillTag2["NFTSpecialist"] = "nft-specialist";
SkillTag2["SmartContractAudit"] = "smart-contract-audit";
SkillTag2["BlockchainDevelopment"] = "blockchain-dev";
SkillTag2["DAOGovernance"] = "dao-governance";
SkillTag2["GameDevelopment"] = "game-dev";
SkillTag2["WebDevelopment"] = "web-dev";
SkillTag2["MobileDevelopment"] = "mobile-dev";
SkillTag2["APIIntegration"] = "api-integration";
SkillTag2["DatabaseManagement"] = "database-management";
SkillTag2["DevOpsAutomation"] = "devops-automation";
SkillTag2["FinancialAnalysis"] = "financial-analysis";
SkillTag2["MarketResearch"] = "market-research";
SkillTag2["LegalCompliance"] = "legal-compliance";
SkillTag2["CustomerSupport"] = "customer-support";
SkillTag2["TranslationServices"] = "translation-services";
SkillTag2["SecurityAudit"] = "security-audit";
SkillTag2["PenetrationTesting"] = "penetration-testing";
SkillTag2["ThreatDetection"] = "threat-detection";
SkillTag2["IncidentResponse"] = "incident-response";
SkillTag2["DataEngineering"] = "data-engineering";
SkillTag2["DataVisualization"] = "data-visualization";
SkillTag2["PredictiveModeling"] = "predictive-modeling";
SkillTag2["StatisticalAnalysis"] = "statistical-analysis";
return SkillTag2;
})(SkillTag || {});
BehaviorTag = /* @__PURE__ */ ((BehaviorTag2) => {
BehaviorTag2["FastResponder"] = "fast-responder";
BehaviorTag2["QuickResponder"] = "quick-responder";
BehaviorTag2["SameDay"] = "same-day";
BehaviorTag2["ConsistentQuality"] = "consistent-quality";
BehaviorTag2["HighQuality"] = "high-quality";
BehaviorTag2["TopRated"] = "top-rated";
BehaviorTag2["PerfectRecord"] = "perfect-record";
BehaviorTag2["HighVolume"] = "high-volume";
BehaviorTag2["VeryHighVolume"] = "very-high-volume";
BehaviorTag2["MegaVolume"] = "mega-volume";
BehaviorTag2["LongTermActive"] = "long-term-active";
BehaviorTag2["MultiYear"] = "multi-year";
BehaviorTag2["CategorySpecialist"] = "category-specialist";
BehaviorTag2["MultiDomain"] = "multi-domain";
BehaviorTag2["Generalist"] = "generalist";
BehaviorTag2["DisputeFree"] = "dispute-free";
BehaviorTag2["LowDispute"] = "low-dispute";
BehaviorTag2["HighResolution"] = "high-resolution";
BehaviorTag2["PlatinumTier"] = "platinum-tier";
BehaviorTag2["GoldTier"] = "gold-tier";
BehaviorTag2["SilverTier"] = "silver-tier";
BehaviorTag2["BronzeTier"] = "bronze-tier";
BehaviorTag2["Responsive"] = "responsive";
BehaviorTag2["Communicative"] = "communicative";
BehaviorTag2["Proactive"] = "proactive";
BehaviorTag2["DetailOriented"] = "detail-oriented";
BehaviorTag2["VerifiedIdentity"] = "verified-identity";
BehaviorTag2["LongStanding"] = "long-standing";
BehaviorTag2["CommunityTrusted"] = "community-trusted";
BehaviorTag2["ClientFavorite"] = "client-favorite";
return BehaviorTag2;
})(BehaviorTag || {});
ComplianceTag = /* @__PURE__ */ ((ComplianceTag2) => {
ComplianceTag2["KYCVerified"] = "kyc-verified";
ComplianceTag2["KYBVerified"] = "kyb-verified";
ComplianceTag2["AccreditedInvestor"] = "accredited-investor";
ComplianceTag2["SOC2Compliant"] = "soc2-compliant";
ComplianceTag2["ISO27001"] = "iso-27001";
ComplianceTag2["GDPR"] = "gdpr-compliant";
ComplianceTag2["HIPAA"] = "hipaa-compliant";
ComplianceTag2["PCI_DSS"] = "pci-dss";
ComplianceTag2["AuditedCode"] = "audited-code";
ComplianceTag2["BugBounty"] = "bug-bounty";
ComplianceTag2["OpenSource"] = "open-source";
ComplianceTag2["InsuredService"] = "insured-service";
ComplianceTag2["BondedAgent"] = "bonded-agent";
ComplianceTag2["LicensedProfessional"] = "licensed-professional";
ComplianceTag2["RegulatedEntity"] = "regulated-entity";
ComplianceTag2["PublicAuditTrail"] = "public-audit-trail";
ComplianceTag2["TransparentPricing"] = "transparent-pricing";
ComplianceTag2["VerifiedMetrics"] = "verified-metrics";
return ComplianceTag2;
})(ComplianceTag || {});
TAG_CONSTANTS = {
/** Maximum skill tags per agent */
MAX_SKILL_TAGS: 20,
/** Maximum behavior tags per agent */
MAX_BEHAVIOR_TAGS: 20,
/** Maximum compliance tags per agent */
MAX_COMPLIANCE_TAGS: 10,
/** Maximum total tag scores */
MAX_TAG_SCORES: 50,
/** Maximum tag name length */
MAX_TAG_NAME_LENGTH: 32,
/** Stale tag threshold (90 days in seconds) */
STALE_TAG_THRESHOLD: 90 * 24 * 60 * 60,
/** Minimum confidence for tag assignment */
MIN_TAG_CONFIDENCE: 5e3,
// 50%
/** Maximum confidence */
MAX_TAG_CONFIDENCE: 1e4,
// 100%
/** Basis points max */
BASIS_POINTS_MAX: 1e4
};
DEFAULT_TAG_DECAY = {
decayRatePerDay: 10,
// 0.1% per day
minConfidence: 2e3,
// Remove when below 20%
maxAgeSeconds: 90 * 24 * 60 * 60
// 90 days
};
TagConfidenceLevel = /* @__PURE__ */ ((TagConfidenceLevel2) => {
TagConfidenceLevel2[TagConfidenceLevel2["VeryLow"] = 2e3] = "VeryLow";
TagConfidenceLevel2[TagConfidenceLevel2["Low"] = 4e3] = "Low";
TagConfidenceLevel2[TagConfidenceLevel2["Medium"] = 6e3] = "Medium";
TagConfidenceLevel2[TagConfidenceLevel2["High"] = 8e3] = "High";
TagConfidenceLevel2[TagConfidenceLevel2["VeryHigh"] = 9500] = "VeryHigh";
TagConfidenceLevel2[TagConfidenceLevel2["Absolute"] = 1e4] = "Absolute";
return TagConfidenceLevel2;
})(TagConfidenceLevel || {});
}
});
// src/utils/reputation-tag-engine.ts
var reputation_tag_engine_exports = {};
__export(reputation_tag_engine_exports, {
ReputationTagEngine: () => ReputationTagEngine
});
var ReputationTagEngine;
var init_reputation_tag_engine = __esm({
"src/utils/reputation-tag-engine.ts"() {
init_reputation_tags();
ReputationTagEngine = class {
tagCriteria = [];
decayConfig;
constructor(decayConfig = DEFAULT_TAG_DECAY) {
this.decayConfig = decayConfig;
this.initializeTagCriteria();
}
/**
* Initialize all tag assignment criteria
*/
initializeTagCriteria() {
this.tagCriteria = [
// ========================================
// BEHAVIOR TAGS
// ========================================
// Fast Responder: avg response time < 60s
{
tag: "fast-responder" /* FastResponder */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
if (metrics.responseTimeCount === 0n) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
const avgResponseTime = metrics.avgResponseTime;
const evidenceCount = Number(metrics.responseTimeCount);
if (avgResponseTime < 6e4) {
const confidence = Math.min(
1e4,
1e4 - Math.floor(avgResponseTime / 6e4 * 2e3)
);
return {
shouldAssign: true,
confidence,
evidenceCount,
reason: `Average response time ${avgResponseTime}ms`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount };
}
},
// Quick Responder: avg < 5 minutes
{
tag: "quick-responder" /* QuickResponder */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
if (metrics.responseTimeCount === 0n) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
const avgResponseTime = metrics.avgResponseTime;
const evidenceCount = Number(metrics.responseTimeCount);
if (avgResponseTime < 3e5) {
const confidence = Math.min(
1e4,
1e4 - Math.floor(avgResponseTime / 3e5 * 3e3)
);
return {
shouldAssign: true,
confidence,
evidenceCount,
reason: `Average response time ${avgResponseTime}ms`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount };
}
},
// Dispute Free: 0 disputes in last 90 days
{
tag: "dispute-free" /* DisputeFree */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
const totalPayments = Number(metrics.successfulPayments + metrics.failedPayments);
if (totalPayments < 10) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
if (metrics.totalDisputes === 0) {
const confidence = Math.min(1e4, 7e3 + totalPayments * 10);
return {
shouldAssign: true,
confidence,
evidenceCount: totalPayments,
reason: `0 disputes over ${totalPayments} transactions`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount: totalPayments };
}
},
// Low Dispute: <1% dispute rate
{
tag: "low-dispute" /* LowDispute */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
const totalPayments = Number(metrics.successfulPayments + metrics.failedPayments);
if (totalPayments < 100) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
const disputeRate = metrics.totalDisputes / totalPayments * 100;
if (disputeRate < 1) {
const confidence = Math.min(
1e4,
1e4 - Math.floor(disputeRate * 1e3)
);
return {
shouldAssign: true,
confidence,
evidenceCount: totalPayments,
reason: `${disputeRate.toFixed(2)}% dispute rate`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount: totalPayments };
}
},
// High Volume: >1000 transactions
{
tag: "high-volume" /* HighVolume */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
const totalPayments = Number(metrics.successfulPayments);
if (totalPayments >= 1e3) {
const confidence = Math.min(1e4, 6e3 + Math.floor(totalPayments / 100));
return {
shouldAssign: true,
confidence,
evidenceCount: totalPayments,
reason: `${totalPayments} successful transactions`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount: totalPayments };
}
},
// Very High Volume: >10000 transactions
{
tag: "very-high-volume" /* VeryHighVolume */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
const totalPayments = Number(metrics.successfulPayments);
if (totalPayments >= 1e4) {
const confidence = Math.min(1e4, 8e3 + Math.floor(totalPayments / 1e3));
return {
shouldAssign: true,
confidence,
evidenceCount: totalPayments,
reason: `${totalPayments} successful transactions`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount: totalPayments };
}
},
// Top Rated: avg rating > 4.8
{
tag: "top-rated" /* TopRated */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
if (metrics.totalRatingsCount < 10) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
const avgRating = metrics.avgRating / 20;
const evidenceCount = metrics.totalRatingsCount;
if (avgRating > 4.8) {
const confidence = Math.min(
1e4,
Math.floor((avgRating - 4.8) * 5e4) + 8e3
);
return {
shouldAssign: true,
confidence,
evidenceCount,
reason: `Average rating ${avgRating.toFixed(2)}/5.0`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount };
}
},
// High Quality: avg rating > 4.5
{
tag: "high-quality" /* HighQuality */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
if (metrics.totalRatingsCount < 5) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
const avgRating = metrics.avgRating / 20;
const evidenceCount = metrics.totalRatingsCount;
if (avgRating > 4.5) {
const confidence = Math.min(
1e4,
Math.floor((avgRating - 4.5) * 2e4) + 7e3
);
return {
shouldAssign: true,
confidence,
evidenceCount,
reason: `Average rating ${avgRating.toFixed(2)}/5.0`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount };
}
},
// Consistent Quality: low variance in ratings
{
tag: "consistent-quality" /* ConsistentQuality */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
if (metrics.totalRatingsCount < 20) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
const avgRating = metrics.avgRating / 20;
const evidenceCount = metrics.totalRatingsCount;
if (avgRating > 4.3) {
const confidence = Math.min(
1e4,
Math.floor((avgRating - 4) * 1e4) + 5e3
);
return {
shouldAssign: true,
confidence,
evidenceCount,
reason: `Consistent high ratings (${avgRating.toFixed(2)}/5.0)`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount };
}
},
// Perfect Record: 100% success rate
{
tag: "perfect-record" /* PerfectRecord */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
const totalPayments = Number(metrics.successfulPayments + metrics.failedPayments);
if (totalPayments < 50) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
const successRate = metrics.successRate / 100;
if (successRate === 100 && metrics.failedPayments === 0n) {
const confidence = Math.min(1e4, 8e3 + Math.floor(totalPayments / 10));
return {
shouldAssign: true,
confidence,
evidenceCount: totalPayments,
reason: `100% success rate over ${totalPayments} transactions`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount: totalPayments };
}
},
// High Resolution: >90% disputes resolved favorably
{
tag: "high-resolution" /* HighResolution */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
if (metrics.totalDisputes < 5) {
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
const resolutionRate = metrics.disputesResolved / metrics.totalDisputes * 100;
const evidenceCount = metrics.totalDisputes;
if (resolutionRate > 90) {
const confidence = Math.min(
1e4,
Math.floor((resolutionRate - 90) * 1e3) + 8e3
);
return {
shouldAssign: true,
confidence,
evidenceCount,
reason: `${resolutionRate.toFixed(1)}% disputes resolved favorably`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount };
}
},
// Long Term Active: active >1 year
{
tag: "long-term-active" /* LongTermActive */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
const currentTime = Math.floor(Date.now() / 1e3);
const ageSeconds = currentTime - metrics.createdAt;
const ageYears = ageSeconds / (365 * 24 * 60 * 60);
if (ageYears >= 1) {
const confidence = Math.min(1e4, Math.floor(ageYears * 2e3) + 6e3);
return {
shouldAssign: true,
confidence,
evidenceCount: Math.floor(ageYears),
reason: `Active for ${ageYears.toFixed(1)} years`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
},
// Multi-Year: active >3 years
{
tag: "multi-year" /* MultiYear */,
category: "behavior" /* Behavior */,
minConfidence: TAG_CONSTANTS.MIN_TAG_CONFIDENCE,
evaluate: (metrics) => {
const currentTime = Math.floor(Date.now() / 1e3);
const ageSeconds = currentTime - metrics.createdAt;
const ageYears = ageSeconds / (365 * 24 * 60 * 60);
if (ageYears >= 3) {
const confidence = Math.min(1e4, Math.floor(ageYears * 1e3) + 7e3);
return {
shouldAssign: true,
confidence,
evidenceCount: Math.floor(ageYears),
reason: `Active for ${ageYears.toFixed(1)} years`
};
}
return { shouldAssign: false, confidence: 0, evidenceCount: 0 };
}
}
];
}
/**
* Calculate tags for an agent based on their metrics
*/
async calculateTags(metrics) {
const tagScores = [];
const currentTime = Math.floor(Date.now() / 1e3);
for (const criteria of this.tagCriteria) {
const evaluation = criteria.evaluate(metrics);
if (evaluation.shouldAssign && evaluation.confidence >= criteria.minConfidence) {
tagScores.push({
tagName: criteria.tag,
confidence: evaluation.confidence,
evidenceCount: evaluation.evidenceCount,
lastUpdated: currentTime
});
}
}
return tagScores;
}
/**
* Apply decay to existing tags based on age
*/
applyTagDecay(tagScores, currentTimestamp) {
const now = currentTimestamp || Math.floor(Date.now() / 1e3);
const decayedTags = [];
for (const tag of tagScores) {
const ageSeconds = now - tag.lastUpdated;
const ageDays = ageSeconds / (24 * 60 * 60);
const totalDecay = Math.floor(ageDays * this.decayConfig.decayRatePerDay);
const newConfidence = Math.max(0, tag.confidence - totalDecay);
if (newConfidence >= this.decayConfig.minConfidence && ageSeconds <= this.decayConfig.maxAgeSeconds) {
decayedTags.push({
...tag,
confidence: newConfidence
});
}
}
return decayedTags;
}
/**
* Merge new tags with existing tags, updating confidence scores
*/
mergeTags(existingTags, newTags) {
const tagMap = /* @__PURE__ */ new Map();
for (const tag of existingTags) {
tagMap.set(tag.tagName, tag);
}
for (const tag of newTags) {
const existing = tagMap.get(tag.tagName);
if (existing) {
if (tag.confidence > existing.confidence || tag.evidenceCount > existing.evidenceCount) {
tagMap.set(tag.tagName, tag);
}
} else {
tagMap.set(tag.tagName, tag);
}
}
return Array.from(tagMap.values());
}
/**
* Filter tags based on criteria
*/
filterTags(tags, filters) {
let filtered = [...tags];
const currentTime = Math.floor(Date.now() / 1e3);
if (filters.category) {
filtered = filtered.filter((tag) => this.getTagCategory(tag.tagName) === filters.category);
}
if (filters.minConfidence !== void 0) {
filtered = filtered.filter((tag) => tag.confidence >= filters.minConfidence);
}
if (filters.maxAge !== void 0) {
filtered = filtered.filter((tag) => {
const age = currentTime - tag.lastUpdated;
return age <= filters.maxAge;
});
}
if (filters.activeOnly) {
filtered = filtered.filter((tag) => {
const age = currentTime - tag.lastUpdated;
return age <= TAG_CONSTANTS.STALE_TAG_THRESHOLD && tag.confidence >= this.decayConfig.minConfidence;
});
}
return filtered;
}
/**
* Get category for a tag
*/
getTagCategory(tagName) {
if (Object.values(SkillTag).includes(tagName)) {
return "skill" /* Skill */;
} else if (Object.values(BehaviorTag).includes(tagName)) {
return "behavior" /* Behavior */;
} else if (Object.values(ComplianceTag).includes(tagName)) {
return "compliance" /* Compliance */;
}
return "behavior" /* Behavior */;
}
/**
* Validate tag name length
*/
validateTagName(tagName) {
return tagName.length > 0 && tagName.length <= TAG_CONSTANTS.MAX_TAG_NAME_LENGTH;
}
/**
* Validate confidence score
*/
validateConfidence(confidence) {
return confidence >= 0 && confidence <= TAG_CONSTANTS.MAX_TAG_CONFIDENCE;
}
/**
* Get confidence level description
*/
getConfidenceLevel(confidence) {
if (confidence >= 1e4 /* Absolute */) return "Absolute";
if (confidence >= 9500 /* VeryHigh */) return "Very High";
if (confidence >= 8e3 /* High */) return "High";
if (confidence >= 6e3 /* Medium */) return "Medium";
if (confidence >= 4e3 /* Low */) return "Low";
return "Very Low";
}
/**
* Sort tags by confidence (descending)
*/
sortByConfidence(tags) {
return [...tags].sort((a, b) => b.confidence - a.confidence);
}
/**
* Sort tags by evidence count (descending)
*/
sortByEvidence(tags) {
return [...tags].sort((a, b) => b.evidenceCount - a.evidenceCount);
}
/**
* Sort tags by last updated (most recent first)
*/
sortByRecent(tags) {
return [...tags].sort((a, b) => b.lastUpdated - a.lastUpdated);
}
/**
* Get top N tags by confidence
*/
getTopTags(tags, count) {
return this.sortByConfidence(tags).slice(0, count);
}
/**
* Categorize tags by type
*/
categorizeTags(tags) {
const skillTags = [];
const behaviorTags = [];
const complianceTags = [];
const allTags = [];
for (const tag of tags) {
allTags.push(tag.tagName);
const category = this.getTagCategory(tag.tagName);
switch (category) {
case "skill" /* Skill */:
skillTags.push(tag.tagName);
break;
case "behavior" /* Behavior */:
behaviorTags.push(tag.tagName);
break;
case "compliance" /* Compliance */:
complianceTags.push(tag.tagName);
break;
}
}
return {
allTags,
skillTags,
behaviorTags,
complianceTags,
tagScores: tags,
lastUpdated: tags.length > 0 ? Math.max(...tags.map((t) => t.lastUpdated)) : 0
};
}
};
}
});
// src/types/privacy-types.ts
var PrivacyMode = /* @__PURE__ */ ((PrivacyMode2) => {
PrivacyMode2["Public"] = "Public";
PrivacyMode2["TierOnly"] = "TierOnly";
PrivacyMode2["RangeOnly"] = "RangeOnly";
PrivacyMode2["Custom"] = "Custom";
PrivacyMode2["Confidential"] = "Confidential";
return PrivacyMode2;
})(PrivacyMode || {});
var VisibilityLevel = /* @__PURE__ */ ((VisibilityLevel2) => {
VisibilityLevel2["Public"] = "Public";
VisibilityLevel2["Private"] = "Private";
VisibilityLevel2["ZKProof"] = "ZKProof";
return VisibilityLevel2;
})(VisibilityLevel || {});
var ScoreRange = /* @__PURE__ */ ((ScoreRange2) => {
ScoreRange2["VeryLow"] = "VeryLow";
ScoreRange2["Low"] = "Low";
ScoreRange2["Medium"] = "Medium";
ScoreRange2["High"] = "High";
ScoreRange2["VeryHigh"] = "VeryHigh";
return ScoreRange2;
})(ScoreRange || {});
var PrivacyPresets = {
CONSERVATIVE: {
name: "Conservative",
mode: "TierOnly" /* TierOnly */,
metricVisibility: {
showScore: "Private" /* Private */,
showJobsCompleted: "Private" /* Private */,
showSuccessRate: "Private" /* Private */,
showResponseTime: "Private" /* Private */,
showDisputes: "Private" /* Private */,
showEarnings: "Private" /* Private */,
showRatings: "Private" /* Private */,
showBadges: "Public" /* Public */
},
autoGrantClients: false
},
BALANCED: {
name: "Balanced",
mode: "Custom" /* Custom */,
metricVisibility: {
showScore: "Private" /* Private */,
showJobsCompleted: "Public" /* Public */,
showSuccessRate: "Public" /* Public */,
showResponseTime: "Public" /* Public */,
showDisputes: "Private" /* Private */,
showEarnings: "Private" /* Private */,
showRatings: "Public" /* Public */,
showBadges: "Public" /* Public */
},
autoGrantClients: true
},
OPEN: {
name: "Open",
mode: "Public" /* Public */,
metricVisibility: {
showScore: "Public" /* Public */,
showJobsCompleted: "Public" /* Public */,
showSuccessRate: "Public" /* Public */,
showResponseTime: "Public" /* Public */,
showDisputes: "Public" /* Public */,
showEarnings: "Public" /* Public */,
showRatings: "Public" /* Public */,
showBadges: "Public" /* Public */
},
autoGrantClients: true
}
};
var PRIVACY_CONSTANTS = {
/** Score range thresholds */
SCORE_RANGES: {
VERY_LOW: { min: 0, max: 2e3 },
LOW: { min: 2e3, max: 5e3 },
MEDIUM: { min: 5e3, max: 7500 },
HIGH: { min: 7500, max: 9e3 },
VERY_HIGH: { min: 9e3, max: 1e4 }
},
/** Tier thresholds */
TIER_THRESHOLDS: {
BRONZE: 2e3,
SILVER: 5e3,
GOLD: 7500,
PLATINUM: 9e3
},
/** Maximum authorized viewers */
MAX_AUTHORIZED_VIEWERS: 100
};
// src/types/index.ts
init_reputation_tags();
// src/types/api-types.ts
var GhostNotFoundError = class extends Error {
constructor(address2) {
super(`Ghost not found: ${address2}`);
this.name = "GhostNotFoundError";
}
};
var ExternalIdNotFoundError = class extends Error {
constructor(platform, externalId) {
super(`No Ghost found for ${platform}:${externalId}`);
this.platform = platform;
this.externalId = externalId;
this.name = "ExternalIdNotFoundError";
}
};
// src/types/index.ts
var GhostSpeakError = class extends Error {
constructor(message, code) {
super(message);
this.code = code;
this.name = "GhostSpeakError";
}
};
function isIPFSUploadResponse(data) {
if (typeof data !== "object" || data === null) return false;
const obj = data;
return typeof obj.IpfsHash === "string";
}
var DEFAULT_ENDPOINTS = {
devnet: "https://api.devnet.solana.com",
mainnet: "https://api.mainnet-beta.solana.com",
localnet: "http://127.0.0.1:8899",
testnet: "https://api.testnet.solana.com"
};
var _defaultClient = null;
var _cachedEndpoint = null;
function createSolanaClient2(config) {
return createSolanaClient({ urlOrMoniker: config.urlOrMoniker });
}
function getDefaultSolanaClient(endpoint) {
const targetEndpoint = endpoint || DEFAULT_ENDPOINTS.devnet;
if (_cachedEndpoint !== targetEndpoint) {
_defaultClient = null;
_cachedEndpoint = targetEndpoint;
}
if (!_defaultClient) {
_defaultClient = createSolanaClient({ urlOrMoniker: targetEndpoint });
}
return _defaultClient;
}
function resetDefaultClient() {
_defaultClient = null;
_cachedEndpoint = null;
}
function createNetworkClient(network) {
return createSolanaClient({ urlOrMoniker: network });
}
function isNetworkMoniker(endpoint) {
return ["devnet", "mainnet", "localnet", "testnet"].includes(endpoint);
}
function getDefaultEndpoint(network) {
return DEFAULT_ENDPOINTS[network];
}
function detectNetworkFromEndpoint(endpoint) {
const lowerEndpoint = endpoint.toLowerCase();
if (lowerEndpoint.includes("devnet") || lowerEndpoint.includes("api.devnet.solana.com")) {
return "devnet";
}
if (lowerEndpoint.includes("mainnet") || lowerEndpoint.includes("api.mainnet-beta.solana.com")) {
return "mainnet";
}
if (lowerEndpoint.includes("testnet") || lowerEndpoint.includes("api.testnet.solana.com")) {
return "testnet";
}
if (lowerEndpoint.includes("localhost") || lowerEndpoint.includes("127.0.0.1")) {
return "localnet";
}
return "unknown";
}
// src/generated/instruction-mappings.ts
var instructionAccountMappings = {
"activate_agent": {
"name": "activate_agent",
"expectedAccounts": [
{
"name": "agent_account",
"pda": true
},
{
"name": "signer",
"pda": false
},
{
"name": "clock",
"pda": false
}
],
"accounts": [
{
"name": "agent_account",
"writable": true,
"signer": false,
"optional": false,
"docs": [
"Agent account with canonical PDA validation"
],
"pda": {
"seeds": [
{
"kind": "const",
"value": [
97,
103,
101,
110,
116
]
},
{
"kind": "account",
"path": "signer"
},
{
"kind": "arg",
"path": "agent_id"
}
]
}
},
{
"name": "signer",
"writable": true,
"signer": true,
"optional": false,
"docs": [
"Enhanced authority verification"
]
},
{
"name": "clock",
"writable": false,
"signer": false,
"optional": false,
"docs": [
"Clock sysvar for rate limiting"
],
"address": "SysvarC1ock11111111111111111111111111111111"
}
],
"docs": "",
"discriminator": [
252,
139,
87,
21,
195,
152,
29,
217
],
"args": [
{
"name": "agent_id",
"type": "string"
}
]
},
"approve_delivery": {
"name": "approve_delivery",
"expectedAccounts": [
{
"name": "escrow",
"pda": true
},
{
"name": "escrow_vault",
"pda": false
},
{
"name": "agent_token_account",
"pda": false
},
{
"name": "client",
"pda": false
},
{
"name": "token_program",
"pda": false
}
],
"accounts": [
{
"name": "escrow",
"writable": true,
"signer": false,
"optional": false,
"docs": [],
"pda": {
"seeds": [
{
"kind": "const",
"value": [
103,
104,
111,
115,
116,
95,
112,
114,
111,
116,
101,
99,
116
]
},
{
"kind": "account",
"path": "escrow.client",
"account": "GhostProtectEscrow"
},
{
"kind": "account",
"path": "escrow.escrow_id",
"account": "GhostProtectEscrow"
}
]
}
},
{
"name": "escrow_vault",
"writable": true,
"signer": false,
"optional": false,
"docs": []
},
{
"name": "agent_token_account",
"writable": true,
"signer": false,
"optional": false,
"docs": []
},
{
"name": "client",
"writable": false,
"signer": true,
"optional": false,
"docs": []
},
{
"name": "token_program",
"writable": false,
"signer": false,
"optional": false,
"docs": [],
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
}
],
"docs": "Client approves delivery and releases payment",
"discriminator": [
28,
233,
51,
115,
33,
220,
41,
28
],
"args": []
},
"arbitrate_dispute": {
"name": "arbitrate_dispute",
"expectedAccounts": [
{
"name": "escrow",
"pda": true
},
{
"name": "escrow_vault",
"pda": false
},
{
"name": "agent_token_account",
"pda": false
},
{
"name": "client_token_account",
"pda": false
},
{
"name": "agent_staking",
"pda": true
},
{
"name": "arbitrator",
"pda": false
},
{
"name": "token_program",
"pda": false
}
],
"accounts": [
{
"name": "escrow",
"writable": true,
"signer": false,
"optional": false,
"docs": [],
"pda": {
"seeds": [
{
"kind": "const",
"value": [
103,
104,
111,
115,
116,
95,
112,
114,
111,
116,
101,
99,
116
]
},
{
"kind": "account",
"path": "escrow.client",
"account": "GhostProtectEscrow"
},
{
"kind": "account",
"path": "escrow.escrow_id",
"account": "GhostProtectEscrow"
}
]
}
},
{
"name": "escrow_vault",
"writable": true,
"signer": false,
"optional": false,
"docs": []
},
{
"name": "agent_token_account",
"writable": true,
"signer": false,
"optional": false,
"docs": []
},
{
"name": "client_token_account",
"writable": true,
"signer": false,
"optional": false,
"docs": []
},
{
"name": "agent_staking",
"writable": true,
"signer": false,
"optional": false,
"docs": [
"Agent's staking account (for potential slashing)"
],
"pda": {
"seeds": [
{
"kind": "const",
"value": [
115,
116,
97,
107,
105,
110,
103
]
},
{
"kind": "account",
"path": "escrow.agent",
"account": "GhostProtectEscrow"
}
]
}
},
{
"name": "arbitrator",
"writable": false,
"signer": true,
"optional": false,
"docs": []
},
{
"name": "token_program",
"writable": false,
"signer": false,
"optional": false,
"docs": [],
"address": "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"
}
],
"docs": "Arbitrator resolves dispute (admin only)",
"discriminator": [
225,
89,
166,
101,
215,
40,
191,
4
],
"args": [
{
"name": "decision",
"type": {
"defined": {
"name": "ArbitratorDecision"
}
}
}
]
},
"auto_create_ghost": {
"name": "auto_create_ghost",
"expectedAccounts": [
{
"name": "agent_account",
"pda": true
},
{
"name": "authority",
"pda": false
},
{
"name": "system_program",
"pda": false
}
],
"accounts": [
{
"name": "agent_account",
"writable": true,
"signer": false,
"optional": false,
"docs": [],
"pda": {
"seeds": [
{
"kind": "const",
"value": [
97,
103,
101,
110,
116
]
},
{
"kind": "arg",
"path": "payment_address"
}
]
}
},
{
"name": "authority",
"writable": true,
"signer": true,
"optional": false,
"docs": []
},
{
"name": "system_program",
"writable": false,
"signer": false,
"optional": false,
"docs": [],
"address": "11111111111111111111111111111111"
}
],
"docs": 'Auto-create a Ghost from discovered x402 transaction (indexer service only) Used by the off-chain indexer service when it discovers a new agent via x402 payment transactions. Creates an Unregistered Ghost. Parameters: - payment_address: The x402_payment_address (merchant address) of the discovered agent - first_tx_signature: Transaction signature where this agent was first discovered - discovery_source: Source identifier (e.g., "http:payai", "blockchain:direct") - initial_ghost_score: Optional initial Ghost Score from backfill metrics',
"discriminator": [
50,
170,
232,
73,
238,
200,
180,
16
],
"args": [
{
"name": "payment_address",
"type": "pubkey"
},
{
"name": "first_tx_signature",
"type": "string"
},
{
"name": "discovery_source",
"type": "string"
},
{
"name": "initial_ghost_score",
"type": {
"option": "u64"
}
}
]
},
"claim_ghost": {
"name": "claim_ghost",
"expectedAccounts": [
{
"name": "agent_account",
"pda": false
},
{
"name": "did_document",
"pda": true
},
{
"name": "sas_attestation",
"pda": false
},
{
"name": "claimer",
"pda": false
},
{
"name": "system_program",
"pda": false
}
],
"accounts": [
{
"name": "agent_account",
"writable": true,
"signer": false,
"optional": false,
"docs": []
},
{
"name": "did_document",
"writable": true,
"signer": false,
"optional": false,
"docs": [
"DID document to create for this Ghost",
'Seeds: [b"did_document", agent_account.x402_payment_address.as_ref()]'
],
"pda": {
"seeds": [
{
"kind": "const",
"value": [
100,
105,
100,
95,
100,
111,
99,
117,
109,
101,
110,
116
]
},
{
"kind": "account",
"path": "agent_account.x402_payment_address",
"account": "Agent"
}
]
}
},
{
"name": "sas_attestation",
"writable": false,
"signer": false,
"optional": false,
"docs": [
"SAS Attestation proving ownership of x402_payment_address",
'PDA: [b"attestation", sas_credential, sas_schema, x402_payment_address]'
]
},
{
"name": "claimer",
"writable": true,
"signer": true,
"optional": false,
"docs": [
"The claimer must have created a SAS attestation proving they own x402_payment_address"
]
},
{
"name": "system_program",
"writable": false,
"signer": false,
"optional": false,
"docs": [],
"address": "11111111111111111111111111111111"
}
],
"docs": 'Claim ownership of a Ghost using Solana Attestation Service (SAS) Security: Uses SAS for trustless ownership verification. The claimer must have created a SAS attestation proving they own the x402_payment_address. Auto-creates: DID document with did:sol:<network>:<address> format Transitions: Unregistered/Registered \u2192 Claimed SAS Attestation Requirements: - Credential: GhostSpeak ownership credential (issuer) - Schema: Ghost ownership schema defining attestation data structure - Nonce: x402_payment_address (ensures PDA uniqueness) - Data: Contains x402_payment_address as proof of ownership Parameters: - sas_credential: Pubkey of the SAS Credential (issuer) for ownership attestations - sas_schema: Pubkey of the SAS Schema defining the ownership attestation format - ipfs_metadata_uri: Optional IPFS URI for agent metadata (ipfs://...) - network: Network identifier ("devnet", "mainnet-beta", "testnet")',
"discriminator": [
149,
107,
35,
233,
252,
101,
148,
225
],
"args": [
{
"name": "sas_credential",
"type": "pubkey"
},
{
"name": "sas_schema",
"type": "pubkey"
},
{
"name": "ipfs_metadata_uri",
"type": {
"option": "string"
}
},
{
"name": "network",
"type": "string"
}
]
},
"create_agent_authorization": {
"name": "create_agent_authorization",
"expectedAccounts": [
{
"name": "agent",
"pda": false
},
{
"name": "authorization",
"pda": true
},
{
"name": "authority",
"pda": false
},
{
"name": "system_program",
"pda": false
}
],
"accounts": [
{
"name": "agent",
"writable": false,
"signer": false,
"optional": false,
"docs": [
"Agent granting authorization"
]
},
{
"name": "authorization",
"writable": true,
"signer": false,
"optional": false,
"docs": [
"Authorization account (PDA)"
],
"pda": {
"seeds": [
{
"kind": "const",
"value": [
97,
103,
101,
110,
116,
95,
97,
117,
116,
104
]
},
{
"kind": "account",
"path": "agent"
},
{
"kind": "arg",
"path": "authorized_source"
},
{
"kind": "arg",
"path": "nonce"
}
]
}
},
{
"name": "authority",
"writable": true,
"signer": true,
"optional": false,
"docs": [
"Authority (agent owner)"
]
},
{
"name": "system_program",
"writable": false,
"signer": false,
"optional": false,
"docs": [
"System program"
],
"address": "11111111111111111111111111111111"
}
],
"docs": "Create agent authorization for reputation updates Allows an agent to pre-authorize a facilitator (e.g., PayAI) to update their reputation a limited number of times before expiration. Parameters: - authorized_source: Pubkey of the facilitator being authorized - index_limit: Maximum number of updates allowed - expires_at: Unix timestamp when authorization expires - network: Network ID for cross-chain compatibility - signature: Ed25519 signature proving agent's consent - nonce: Optional nonce for multiple authorizations to same facilitator",
"discriminator": [
48,
219,
232,
202,
151,
97,
230,
20
],
"args": [
{
"name": "authorized_source",
"type": "pubkey"
},
{
"name": "index_limit",
"type": "u64"
},
{
"name": "expires_at",
"type": "i64"
},
{
"name": "network",
"type": "u8"
},
{
"name": "signature",
"type": {
"array": [
"u8",
64
]
}
},
{
"name": "nonce",
"type": {
"option": "string"
}
}
]
},
"create_credential_template": {
"name": "create_credential_template",
"expectedAccounts": [
{
"name": "credential_template",
"pda": true
},
{
"name": "credential_type",
"pda": false
},
{
"name": "issuer",
"pda": false
},
{
"name": "system_program",
"pda": false
}
],
"accounts": [
{
"name": "credential_template",
"writable": true,
"signer": false,
"optional": false,
"docs": [],
"pda": {
"seeds": [
{
"kind": "const",
"value": [
99,
114,
101,
100,
101,
110,
116,
105,
97,
108,
95,
116,
101,
109,
112,
108,
97,
116,
101
]
},
{
"kind": "account",
"path": "credential_type"
},
{
"kind": "arg",
"path": "name"
}
]
}
},
{
"name": "credential_type",
"writable": false,
"signer": false,
"optional": false,
"docs": []
},
{
"name": "issuer",
"writable": true,