@elisym/sdk 0.11.0 → 0.12.1

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/dist/index.d.cts CHANGED
@@ -205,10 +205,10 @@ type Signer = TransactionSigner;
205
205
  /**
206
206
  * Protocol fee + treasury inputs for building a payment request.
207
207
  *
208
- * In Phase 2 the SDK no longer reads PROTOCOL_FEE_BPS / PROTOCOL_TREASURY
209
- * from constants. Callers supply this config so they can either pass
210
- * the bundled fallbacks or, in Phase 3, values fetched from the on-chain
211
- * elisym-config program.
208
+ * Callers must supply this config explicitly - the SDK does not bundle a
209
+ * fallback. The canonical source is `getProtocolConfig(rpc, programId)`,
210
+ * which reads the on-chain elisym-config program; tests and offline tools
211
+ * may pass fixture values directly.
212
212
  */
213
213
  interface ProtocolConfigInput {
214
214
  /** Protocol fee in basis points (300 = 3%). Must be a non-negative integer. */
@@ -320,7 +320,9 @@ declare class NostrPool {
320
320
  publish(event: Event): Promise<void>;
321
321
  /** Publish to all relays and wait for all to settle. Throws if none accepted. */
322
322
  publishAll(event: Event): Promise<void>;
323
- subscribe(filter: Filter, onEvent: (event: Event) => void): SubCloser;
323
+ subscribe(filter: Filter, onEvent: (event: Event) => void, opts?: {
324
+ oneose?: () => void;
325
+ }): SubCloser;
324
326
  /**
325
327
  * Subscribe and wait until at least one relay confirms the subscription
326
328
  * is active (EOSE). Resolves on the first relay that responds.
@@ -402,6 +404,43 @@ declare class DiscoveryService {
402
404
  * provider.
403
405
  */
404
406
  fetchAgents(network?: Network, limit?: number): Promise<Agent[]>;
407
+ /**
408
+ * Enrich an agent map with paid-job stats, feedback counters, and kind:0
409
+ * metadata, then return them sorted by `compareAgentsByRank`. Mutates the
410
+ * passed-in `Agent` objects in place.
411
+ *
412
+ * Shared between `fetchAgents` (one-shot) and `streamAgents` (post-EOSE
413
+ * second pass). The `signal` short-circuits the post-query work; in-flight
414
+ * pool queries are not cancellable today (they fall through to the standard
415
+ * timeout) and the caller drops the resolved value.
416
+ */
417
+ private runEnrichment;
418
+ /**
419
+ * Stream elisym agents progressively as relays deliver events.
420
+ *
421
+ * Two live subscriptions:
422
+ * - kind:31990 (capability cards) - emits `onAgent(agent)` for every new or
423
+ * updated `(pubkey, d-tag)`. The emitted Agent is the merged view across
424
+ * all surviving cards for that author.
425
+ * - kind:6100 (default-offset job results) tagged `t=elisym` since 30d ago -
426
+ * emits `onPaidJob(pubkey, ts)` for each delivered result. Custom-kind
427
+ * results (offset != 100) are not on this stream; they enter the final
428
+ * ranking via the post-EOSE enrichment pass.
429
+ *
430
+ * After capabilities EOSE, an enrichment pass runs in parallel to the live
431
+ * subscriptions and produces a ranked snapshot via `onComplete`. The snapshot
432
+ * is a clone, so further live updates do not mutate it.
433
+ *
434
+ * `closer.close()` tears down both subscriptions and aborts an in-flight
435
+ * enrichment. If `opts.signal` is provided, aborting it does the same.
436
+ */
437
+ streamAgents(network: Network, opts: {
438
+ onAgent: (agent: Agent) => void;
439
+ onPaidJob?: (pubkey: string, ts: number) => void;
440
+ onEose?: () => void;
441
+ onComplete?: (agents: Agent[]) => void;
442
+ signal?: AbortSignal;
443
+ }): SubCloser;
405
444
  /**
406
445
  * Publish a capability card (kind:31990) as a provider.
407
446
  * Solana address is validated for Base58 format only - full decode
@@ -632,9 +671,8 @@ declare function assertLamports(value: number, field: string): void;
632
671
  * Calculate the protocol fee using basis-point math (no floats).
633
672
  * Returns ceil(amount * feeBps / 10000).
634
673
  *
635
- * The caller passes the current fee (in basis points). Phase 2 of the
636
- * Solana Kit migration removes the implicit dependency on PROTOCOL_FEE_BPS
637
- * so callers can supply on-chain or test values.
674
+ * The caller passes the current fee (in basis points), typically obtained
675
+ * from `getProtocolConfig` or supplied as a test fixture.
638
676
  */
639
677
  declare function calculateProtocolFee(amount: number, feeBps: number): number;
640
678
  /** Validate payment request timestamps. Returns error message or null if valid. */
@@ -1043,21 +1081,6 @@ declare function jobResultKind(offset: number): number;
1043
1081
  declare const KIND_PING = 20200;
1044
1082
  declare const KIND_PONG = 20201;
1045
1083
  declare const LAMPORTS_PER_SOL = 1000000000;
1046
- /**
1047
- * @deprecated Fallback only - use `getProtocolConfig(rpc, programId)` for live values.
1048
- *
1049
- * Protocol fee in basis points (300 = 3%). Bundled as a default for offline use
1050
- * and for first-call before the on-chain config has been fetched. The on-chain
1051
- * `elisym-config` program is the source of truth.
1052
- */
1053
- declare const PROTOCOL_FEE_BPS = 300;
1054
- /**
1055
- * @deprecated Fallback only - use `getProtocolConfig(rpc, programId)` for live values.
1056
- *
1057
- * Solana address of the protocol treasury. Bundled fallback; the on-chain
1058
- * `elisym-config` program is the source of truth and may rotate this address.
1059
- */
1060
- declare const PROTOCOL_TREASURY: Address;
1061
1084
  /**
1062
1085
  * Solana program ID for the elisym protocol config (devnet deployment).
1063
1086
  *
@@ -1112,4 +1135,4 @@ declare const LIMITS: {
1112
1135
  readonly MAX_CAPABILITY_LENGTH: 64;
1113
1136
  };
1114
1137
 
1115
- export { type Agent, type AggregateNetworkStatsOptions, Asset, BoundedSet, type BuildTransactionOptions, type CapabilityCard, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, type ElisymClientConfig, type ElisymClientFullConfig, ElisymIdentity, type EstimatePriorityFeeOptions, type EstimateSolFeeOptions, type GetProtocolConfigOptions, INPUT_REDACT_PATHS, type Job, type JobStatus, type JobSubscriptionOptions, type JobUpdateCallbacks, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, type Network, type NetworkStats, type NetworkStatsResult, NostrPool, PROTOCOL_FEE_BPS, PROTOCOL_PROGRAM_ID_DEVNET, PROTOCOL_TREASURY, type ParseOptions, type ParseResult, type ParsedPaymentRequest, type PaymentAssetRef, type PaymentInfo, type PaymentRequestData, PaymentRequestSchema, type PaymentStrategy, type PaymentValidationCode, type PaymentValidationError, type PingResult, PingService, type ProtocolCluster, type ProtocolConfig, type ProtocolConfigInput, type QuickVerifyReason, type QuickVerifyResult, RELAYS, type RankKey, type RateLimitDecision, SECRET_REDACT_PATHS, type Signer, type SlidingWindowLimiter, type SlidingWindowLimiterOptions, type SolFeeEstimate, SolanaPaymentStrategy, type SubCloser, type SubmitJobOptions, type VerifyOptions, type VerifyResult, aggregateNetworkStats, assertExpiry, assertLamports, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatFeeBreakdown, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parsePaymentRequest, pickPercentileFee, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
1138
+ export { type Agent, type AggregateNetworkStatsOptions, Asset, BoundedSet, type BuildTransactionOptions, type CapabilityCard, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, type ElisymClientConfig, type ElisymClientFullConfig, ElisymIdentity, type EstimatePriorityFeeOptions, type EstimateSolFeeOptions, type GetProtocolConfigOptions, INPUT_REDACT_PATHS, type Job, type JobStatus, type JobSubscriptionOptions, type JobUpdateCallbacks, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, type Network, type NetworkStats, type NetworkStatsResult, NostrPool, PROTOCOL_PROGRAM_ID_DEVNET, type ParseOptions, type ParseResult, type ParsedPaymentRequest, type PaymentAssetRef, type PaymentInfo, type PaymentRequestData, PaymentRequestSchema, type PaymentStrategy, type PaymentValidationCode, type PaymentValidationError, type PingResult, PingService, type ProtocolCluster, type ProtocolConfig, type ProtocolConfigInput, type QuickVerifyReason, type QuickVerifyResult, RELAYS, type RankKey, type RateLimitDecision, SECRET_REDACT_PATHS, type Signer, type SlidingWindowLimiter, type SlidingWindowLimiterOptions, type SolFeeEstimate, SolanaPaymentStrategy, type SubCloser, type SubmitJobOptions, type VerifyOptions, type VerifyResult, aggregateNetworkStats, assertExpiry, assertLamports, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatFeeBreakdown, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parsePaymentRequest, pickPercentileFee, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
package/dist/index.d.ts CHANGED
@@ -205,10 +205,10 @@ type Signer = TransactionSigner;
205
205
  /**
206
206
  * Protocol fee + treasury inputs for building a payment request.
207
207
  *
208
- * In Phase 2 the SDK no longer reads PROTOCOL_FEE_BPS / PROTOCOL_TREASURY
209
- * from constants. Callers supply this config so they can either pass
210
- * the bundled fallbacks or, in Phase 3, values fetched from the on-chain
211
- * elisym-config program.
208
+ * Callers must supply this config explicitly - the SDK does not bundle a
209
+ * fallback. The canonical source is `getProtocolConfig(rpc, programId)`,
210
+ * which reads the on-chain elisym-config program; tests and offline tools
211
+ * may pass fixture values directly.
212
212
  */
213
213
  interface ProtocolConfigInput {
214
214
  /** Protocol fee in basis points (300 = 3%). Must be a non-negative integer. */
@@ -320,7 +320,9 @@ declare class NostrPool {
320
320
  publish(event: Event): Promise<void>;
321
321
  /** Publish to all relays and wait for all to settle. Throws if none accepted. */
322
322
  publishAll(event: Event): Promise<void>;
323
- subscribe(filter: Filter, onEvent: (event: Event) => void): SubCloser;
323
+ subscribe(filter: Filter, onEvent: (event: Event) => void, opts?: {
324
+ oneose?: () => void;
325
+ }): SubCloser;
324
326
  /**
325
327
  * Subscribe and wait until at least one relay confirms the subscription
326
328
  * is active (EOSE). Resolves on the first relay that responds.
@@ -402,6 +404,43 @@ declare class DiscoveryService {
402
404
  * provider.
403
405
  */
404
406
  fetchAgents(network?: Network, limit?: number): Promise<Agent[]>;
407
+ /**
408
+ * Enrich an agent map with paid-job stats, feedback counters, and kind:0
409
+ * metadata, then return them sorted by `compareAgentsByRank`. Mutates the
410
+ * passed-in `Agent` objects in place.
411
+ *
412
+ * Shared between `fetchAgents` (one-shot) and `streamAgents` (post-EOSE
413
+ * second pass). The `signal` short-circuits the post-query work; in-flight
414
+ * pool queries are not cancellable today (they fall through to the standard
415
+ * timeout) and the caller drops the resolved value.
416
+ */
417
+ private runEnrichment;
418
+ /**
419
+ * Stream elisym agents progressively as relays deliver events.
420
+ *
421
+ * Two live subscriptions:
422
+ * - kind:31990 (capability cards) - emits `onAgent(agent)` for every new or
423
+ * updated `(pubkey, d-tag)`. The emitted Agent is the merged view across
424
+ * all surviving cards for that author.
425
+ * - kind:6100 (default-offset job results) tagged `t=elisym` since 30d ago -
426
+ * emits `onPaidJob(pubkey, ts)` for each delivered result. Custom-kind
427
+ * results (offset != 100) are not on this stream; they enter the final
428
+ * ranking via the post-EOSE enrichment pass.
429
+ *
430
+ * After capabilities EOSE, an enrichment pass runs in parallel to the live
431
+ * subscriptions and produces a ranked snapshot via `onComplete`. The snapshot
432
+ * is a clone, so further live updates do not mutate it.
433
+ *
434
+ * `closer.close()` tears down both subscriptions and aborts an in-flight
435
+ * enrichment. If `opts.signal` is provided, aborting it does the same.
436
+ */
437
+ streamAgents(network: Network, opts: {
438
+ onAgent: (agent: Agent) => void;
439
+ onPaidJob?: (pubkey: string, ts: number) => void;
440
+ onEose?: () => void;
441
+ onComplete?: (agents: Agent[]) => void;
442
+ signal?: AbortSignal;
443
+ }): SubCloser;
405
444
  /**
406
445
  * Publish a capability card (kind:31990) as a provider.
407
446
  * Solana address is validated for Base58 format only - full decode
@@ -632,9 +671,8 @@ declare function assertLamports(value: number, field: string): void;
632
671
  * Calculate the protocol fee using basis-point math (no floats).
633
672
  * Returns ceil(amount * feeBps / 10000).
634
673
  *
635
- * The caller passes the current fee (in basis points). Phase 2 of the
636
- * Solana Kit migration removes the implicit dependency on PROTOCOL_FEE_BPS
637
- * so callers can supply on-chain or test values.
674
+ * The caller passes the current fee (in basis points), typically obtained
675
+ * from `getProtocolConfig` or supplied as a test fixture.
638
676
  */
639
677
  declare function calculateProtocolFee(amount: number, feeBps: number): number;
640
678
  /** Validate payment request timestamps. Returns error message or null if valid. */
@@ -1043,21 +1081,6 @@ declare function jobResultKind(offset: number): number;
1043
1081
  declare const KIND_PING = 20200;
1044
1082
  declare const KIND_PONG = 20201;
1045
1083
  declare const LAMPORTS_PER_SOL = 1000000000;
1046
- /**
1047
- * @deprecated Fallback only - use `getProtocolConfig(rpc, programId)` for live values.
1048
- *
1049
- * Protocol fee in basis points (300 = 3%). Bundled as a default for offline use
1050
- * and for first-call before the on-chain config has been fetched. The on-chain
1051
- * `elisym-config` program is the source of truth.
1052
- */
1053
- declare const PROTOCOL_FEE_BPS = 300;
1054
- /**
1055
- * @deprecated Fallback only - use `getProtocolConfig(rpc, programId)` for live values.
1056
- *
1057
- * Solana address of the protocol treasury. Bundled fallback; the on-chain
1058
- * `elisym-config` program is the source of truth and may rotate this address.
1059
- */
1060
- declare const PROTOCOL_TREASURY: Address;
1061
1084
  /**
1062
1085
  * Solana program ID for the elisym protocol config (devnet deployment).
1063
1086
  *
@@ -1112,4 +1135,4 @@ declare const LIMITS: {
1112
1135
  readonly MAX_CAPABILITY_LENGTH: 64;
1113
1136
  };
1114
1137
 
1115
- export { type Agent, type AggregateNetworkStatsOptions, Asset, BoundedSet, type BuildTransactionOptions, type CapabilityCard, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, type ElisymClientConfig, type ElisymClientFullConfig, ElisymIdentity, type EstimatePriorityFeeOptions, type EstimateSolFeeOptions, type GetProtocolConfigOptions, INPUT_REDACT_PATHS, type Job, type JobStatus, type JobSubscriptionOptions, type JobUpdateCallbacks, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, type Network, type NetworkStats, type NetworkStatsResult, NostrPool, PROTOCOL_FEE_BPS, PROTOCOL_PROGRAM_ID_DEVNET, PROTOCOL_TREASURY, type ParseOptions, type ParseResult, type ParsedPaymentRequest, type PaymentAssetRef, type PaymentInfo, type PaymentRequestData, PaymentRequestSchema, type PaymentStrategy, type PaymentValidationCode, type PaymentValidationError, type PingResult, PingService, type ProtocolCluster, type ProtocolConfig, type ProtocolConfigInput, type QuickVerifyReason, type QuickVerifyResult, RELAYS, type RankKey, type RateLimitDecision, SECRET_REDACT_PATHS, type Signer, type SlidingWindowLimiter, type SlidingWindowLimiterOptions, type SolFeeEstimate, SolanaPaymentStrategy, type SubCloser, type SubmitJobOptions, type VerifyOptions, type VerifyResult, aggregateNetworkStats, assertExpiry, assertLamports, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatFeeBreakdown, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parsePaymentRequest, pickPercentileFee, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
1138
+ export { type Agent, type AggregateNetworkStatsOptions, Asset, BoundedSet, type BuildTransactionOptions, type CapabilityCard, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, type ElisymClientConfig, type ElisymClientFullConfig, ElisymIdentity, type EstimatePriorityFeeOptions, type EstimateSolFeeOptions, type GetProtocolConfigOptions, INPUT_REDACT_PATHS, type Job, type JobStatus, type JobSubscriptionOptions, type JobUpdateCallbacks, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, type Network, type NetworkStats, type NetworkStatsResult, NostrPool, PROTOCOL_PROGRAM_ID_DEVNET, type ParseOptions, type ParseResult, type ParsedPaymentRequest, type PaymentAssetRef, type PaymentInfo, type PaymentRequestData, PaymentRequestSchema, type PaymentStrategy, type PaymentValidationCode, type PaymentValidationError, type PingResult, PingService, type ProtocolCluster, type ProtocolConfig, type ProtocolConfigInput, type QuickVerifyReason, type QuickVerifyResult, RELAYS, type RankKey, type RateLimitDecision, SECRET_REDACT_PATHS, type Signer, type SlidingWindowLimiter, type SlidingWindowLimiterOptions, type SolFeeEstimate, SolanaPaymentStrategy, type SubCloser, type SubmitJobOptions, type VerifyOptions, type VerifyResult, aggregateNetworkStats, assertExpiry, assertLamports, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatFeeBreakdown, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parsePaymentRequest, pickPercentileFee, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
package/dist/index.js CHANGED
@@ -37,8 +37,6 @@ function jobResultKind(offset) {
37
37
  var KIND_PING = 20200;
38
38
  var KIND_PONG = 20201;
39
39
  var LAMPORTS_PER_SOL = 1e9;
40
- var PROTOCOL_FEE_BPS = 300;
41
- var PROTOCOL_TREASURY = "GY7vnWMkKpftU4nQ16C2ATkj1JwrQpHhknkaBUn67VTy";
42
40
  var PROTOCOL_PROGRAM_ID_DEVNET = "BrX1CRkSgvcjxBvc2bgc3QqgWjinusofDmeP7ZVxvwrE";
43
41
  var ELISYM_PROTOCOL_TAG = "ELiZksgwDt41LaeuPDLkUfWgFXhGgVayTMP7L5nTSEL8";
44
42
  function getProtocolProgramId(cluster) {
@@ -1007,6 +1005,7 @@ async function createPaymentRequestWithOnchainConfig(rpc, programId, recipient,
1007
1005
  var RANKING_ACTIVITY_WINDOW_SECS = 30 * 24 * 60 * 60;
1008
1006
  var RANKING_BUCKET_SIZE_SECS = 60;
1009
1007
  var COLD_START_BUCKET = -Infinity;
1008
+ var NEVER_ABORTED_SIGNAL = new AbortController().signal;
1010
1009
  function toDTag(name) {
1011
1010
  const tag = name.toLowerCase().replace(/[^a-z0-9\s-]/g, (ch) => "_" + ch.charCodeAt(0).toString(16).padStart(2, "0")).replace(/\s+/g, "-").replace(/^-+|-+$/g, "");
1012
1011
  if (!tag) {
@@ -1036,13 +1035,63 @@ function compareAgentsByRank(a, b) {
1036
1035
  }
1037
1036
  return kb.lastSeen - ka.lastSeen;
1038
1037
  }
1038
+ function parseCapabilityEvent(event, network) {
1039
+ if (!verifyEvent(event)) {
1040
+ return null;
1041
+ }
1042
+ if (!event.content) {
1043
+ return null;
1044
+ }
1045
+ let raw;
1046
+ try {
1047
+ raw = JSON.parse(event.content);
1048
+ } catch {
1049
+ return null;
1050
+ }
1051
+ if (!raw || typeof raw !== "object") {
1052
+ return null;
1053
+ }
1054
+ const candidate = raw;
1055
+ if (typeof candidate.name !== "string" || !candidate.name) {
1056
+ return null;
1057
+ }
1058
+ if (typeof candidate.description !== "string") {
1059
+ return null;
1060
+ }
1061
+ if (!Array.isArray(candidate.capabilities) || !candidate.capabilities.every((cap) => typeof cap === "string")) {
1062
+ return null;
1063
+ }
1064
+ if (candidate.deleted) {
1065
+ return null;
1066
+ }
1067
+ const card = candidate;
1068
+ if (card.payment && (typeof card.payment.chain !== "string" || typeof card.payment.network !== "string" || typeof card.payment.address !== "string")) {
1069
+ return null;
1070
+ }
1071
+ if (card.payment?.job_price !== null && card.payment?.job_price !== void 0 && (!Number.isInteger(card.payment.job_price) || card.payment.job_price < 0)) {
1072
+ return null;
1073
+ }
1074
+ const agentNetwork = card.payment?.network ?? "devnet";
1075
+ if (agentNetwork !== network) {
1076
+ return null;
1077
+ }
1078
+ const kTags = event.tags.filter((tag) => tag[0] === "k").map((tag) => parseInt(tag[1] ?? "", 10)).filter((kind) => !isNaN(kind));
1079
+ return {
1080
+ pubkey: event.pubkey,
1081
+ npub: nip19.npubEncode(event.pubkey),
1082
+ cards: [card],
1083
+ eventId: event.id,
1084
+ supportedKinds: kTags,
1085
+ lastSeen: event.created_at
1086
+ };
1087
+ }
1039
1088
  function buildAgentsFromEvents(events, network) {
1040
1089
  const latestByDTag = /* @__PURE__ */ new Map();
1041
1090
  for (const event of events) {
1042
1091
  if (!verifyEvent(event)) {
1043
1092
  continue;
1044
1093
  }
1045
- const dTag = event.tags.find((t) => t[0] === "d")?.[1] ?? "";
1094
+ const dTag = event.tags.find((tag) => tag[0] === "d")?.[1] ?? "";
1046
1095
  const key = `${event.pubkey}:${dTag}`;
1047
1096
  const prev = latestByDTag.get(key);
1048
1097
  if (!prev || event.created_at > prev.created_at) {
@@ -1051,82 +1100,51 @@ function buildAgentsFromEvents(events, network) {
1051
1100
  }
1052
1101
  const accumMap = /* @__PURE__ */ new Map();
1053
1102
  for (const event of latestByDTag.values()) {
1054
- try {
1055
- if (!event.content) {
1056
- continue;
1057
- }
1058
- const raw = JSON.parse(event.content);
1059
- if (!raw || typeof raw !== "object") {
1060
- continue;
1061
- }
1062
- if (typeof raw.name !== "string" || !raw.name) {
1063
- continue;
1064
- }
1065
- if (typeof raw.description !== "string") {
1066
- continue;
1067
- }
1068
- if (!Array.isArray(raw.capabilities) || !raw.capabilities.every((c) => typeof c === "string")) {
1069
- continue;
1070
- }
1071
- if (raw.deleted) {
1072
- continue;
1073
- }
1074
- const card = raw;
1075
- if (card.payment && (typeof card.payment.chain !== "string" || typeof card.payment.network !== "string" || typeof card.payment.address !== "string")) {
1076
- continue;
1077
- }
1078
- if (card.payment?.job_price !== null && card.payment?.job_price !== void 0 && (!Number.isInteger(card.payment.job_price) || card.payment.job_price < 0)) {
1079
- continue;
1080
- }
1081
- const agentNetwork = card.payment?.network ?? "devnet";
1082
- if (agentNetwork !== network) {
1083
- continue;
1084
- }
1085
- const kTags = event.tags.filter((t) => t[0] === "k").map((t) => parseInt(t[1] ?? "", 10)).filter((k) => !isNaN(k));
1086
- const entry = { card, kTags, createdAt: event.created_at };
1087
- const existing = accumMap.get(event.pubkey);
1088
- if (existing) {
1089
- const dupIndex = existing.entries.findIndex((e) => e.card.name === card.name);
1090
- if (dupIndex >= 0) {
1091
- if (entry.createdAt >= existing.entries[dupIndex].createdAt) {
1092
- existing.entries[dupIndex] = entry;
1103
+ const parsed = parseCapabilityEvent(event, network);
1104
+ if (!parsed) {
1105
+ continue;
1106
+ }
1107
+ const card = parsed.cards[0];
1108
+ const cardKinds = parsed.supportedKinds;
1109
+ const createdAt = parsed.lastSeen;
1110
+ const existing = accumMap.get(parsed.pubkey);
1111
+ if (existing) {
1112
+ const prevForName = existing.perCard.get(card.name);
1113
+ if (prevForName) {
1114
+ if (createdAt >= prevForName.createdAt) {
1115
+ const idx = existing.agent.cards.findIndex(
1116
+ (existingCard) => existingCard.name === card.name
1117
+ );
1118
+ if (idx >= 0) {
1119
+ existing.agent.cards[idx] = card;
1093
1120
  }
1094
- } else {
1095
- existing.entries.push(entry);
1096
- }
1097
- if (event.created_at > existing.lastSeen) {
1098
- existing.lastSeen = event.created_at;
1099
- existing.eventId = event.id;
1121
+ existing.perCard.set(card.name, { createdAt, kTags: cardKinds });
1100
1122
  }
1101
1123
  } else {
1102
- accumMap.set(event.pubkey, {
1103
- pubkey: event.pubkey,
1104
- npub: nip19.npubEncode(event.pubkey),
1105
- entries: [entry],
1106
- eventId: event.id,
1107
- lastSeen: event.created_at
1108
- });
1124
+ existing.agent.cards.push(card);
1125
+ existing.perCard.set(card.name, { createdAt, kTags: cardKinds });
1109
1126
  }
1110
- } catch {
1127
+ if (createdAt > existing.agent.lastSeen) {
1128
+ existing.agent.lastSeen = createdAt;
1129
+ existing.agent.eventId = parsed.eventId;
1130
+ }
1131
+ } else {
1132
+ accumMap.set(parsed.pubkey, {
1133
+ agent: parsed,
1134
+ perCard: /* @__PURE__ */ new Map([[card.name, { createdAt, kTags: cardKinds }]])
1135
+ });
1111
1136
  }
1112
1137
  }
1113
1138
  const agentMap = /* @__PURE__ */ new Map();
1114
1139
  for (const [pubkey, acc] of accumMap) {
1115
1140
  const kindsSet = /* @__PURE__ */ new Set();
1116
- for (const e of acc.entries) {
1117
- for (const k of e.kTags) {
1118
- kindsSet.add(k);
1119
- }
1120
- }
1121
- const supportedKinds = [...kindsSet];
1122
- agentMap.set(pubkey, {
1123
- pubkey: acc.pubkey,
1124
- npub: acc.npub,
1125
- cards: acc.entries.map((e) => e.card),
1126
- eventId: acc.eventId,
1127
- supportedKinds,
1128
- lastSeen: acc.lastSeen
1129
- });
1141
+ for (const { kTags } of acc.perCard.values()) {
1142
+ for (const kind of kTags) {
1143
+ kindsSet.add(kind);
1144
+ }
1145
+ }
1146
+ acc.agent.supportedKinds = [...kindsSet];
1147
+ agentMap.set(pubkey, acc.agent);
1130
1148
  }
1131
1149
  return agentMap;
1132
1150
  }
@@ -1241,6 +1259,19 @@ var DiscoveryService = class {
1241
1259
  const events = await this.pool.querySync(filter);
1242
1260
  const agentMap = buildAgentsFromEvents(events, network);
1243
1261
  const agents = Array.from(agentMap.values());
1262
+ return this.runEnrichment(agents, agentMap, NEVER_ABORTED_SIGNAL);
1263
+ }
1264
+ /**
1265
+ * Enrich an agent map with paid-job stats, feedback counters, and kind:0
1266
+ * metadata, then return them sorted by `compareAgentsByRank`. Mutates the
1267
+ * passed-in `Agent` objects in place.
1268
+ *
1269
+ * Shared between `fetchAgents` (one-shot) and `streamAgents` (post-EOSE
1270
+ * second pass). The `signal` short-circuits the post-query work; in-flight
1271
+ * pool queries are not cancellable today (they fall through to the standard
1272
+ * timeout) and the caller drops the resolved value.
1273
+ */
1274
+ async runEnrichment(agents, agentMap, signal) {
1244
1275
  const agentPubkeys = Array.from(agentMap.keys());
1245
1276
  if (agentPubkeys.length === 0) {
1246
1277
  return agents;
@@ -1248,9 +1279,9 @@ var DiscoveryService = class {
1248
1279
  const activitySince = Math.floor(Date.now() / 1e3) - RANKING_ACTIVITY_WINDOW_SECS;
1249
1280
  const resultKinds = /* @__PURE__ */ new Set();
1250
1281
  for (const agent of agentMap.values()) {
1251
- for (const k of agent.supportedKinds) {
1252
- if (k >= KIND_JOB_REQUEST_BASE && k < KIND_JOB_RESULT_BASE) {
1253
- resultKinds.add(KIND_JOB_RESULT_BASE + (k - KIND_JOB_REQUEST_BASE));
1282
+ for (const supportedKind of agent.supportedKinds) {
1283
+ if (supportedKind >= KIND_JOB_REQUEST_BASE && supportedKind < KIND_JOB_RESULT_BASE) {
1284
+ resultKinds.add(KIND_JOB_RESULT_BASE + (supportedKind - KIND_JOB_REQUEST_BASE));
1254
1285
  }
1255
1286
  }
1256
1287
  }
@@ -1270,6 +1301,9 @@ var DiscoveryService = class {
1270
1301
  ),
1271
1302
  this.enrichWithMetadata(agents)
1272
1303
  ]);
1304
+ if (signal.aborted) {
1305
+ return agents;
1306
+ }
1273
1307
  const deliveredJobsByProvider = /* @__PURE__ */ new Map();
1274
1308
  for (const ev of resultEvents) {
1275
1309
  if (!verifyEvent(ev)) {
@@ -1282,7 +1316,7 @@ var DiscoveryService = class {
1282
1316
  if (ev.created_at > agent.lastSeen) {
1283
1317
  agent.lastSeen = ev.created_at;
1284
1318
  }
1285
- const jobEventId = ev.tags.find((t) => t[0] === "e")?.[1];
1319
+ const jobEventId = ev.tags.find((tag) => tag[0] === "e")?.[1];
1286
1320
  if (jobEventId) {
1287
1321
  let delivered = deliveredJobsByProvider.get(ev.pubkey);
1288
1322
  if (!delivered) {
@@ -1296,7 +1330,7 @@ var DiscoveryService = class {
1296
1330
  if (!verifyEvent(ev)) {
1297
1331
  continue;
1298
1332
  }
1299
- const targetPubkey = ev.tags.find((t) => t[0] === "p")?.[1];
1333
+ const targetPubkey = ev.tags.find((tag) => tag[0] === "p")?.[1];
1300
1334
  if (!targetPubkey) {
1301
1335
  continue;
1302
1336
  }
@@ -1307,17 +1341,17 @@ var DiscoveryService = class {
1307
1341
  if (ev.created_at > agent.lastSeen) {
1308
1342
  agent.lastSeen = ev.created_at;
1309
1343
  }
1310
- const rating = ev.tags.find((t) => t[0] === "rating")?.[1];
1344
+ const rating = ev.tags.find((tag) => tag[0] === "rating")?.[1];
1311
1345
  if (rating === "1" || rating === "0") {
1312
1346
  agent.totalRatingCount = (agent.totalRatingCount ?? 0) + 1;
1313
1347
  if (rating === "1") {
1314
1348
  agent.positiveCount = (agent.positiveCount ?? 0) + 1;
1315
1349
  }
1316
1350
  }
1317
- const status = ev.tags.find((t) => t[0] === "status")?.[1];
1318
- const txTag = ev.tags.find((t) => t[0] === "tx");
1351
+ const status = ev.tags.find((tag) => tag[0] === "status")?.[1];
1352
+ const txTag = ev.tags.find((tag) => tag[0] === "tx");
1319
1353
  const txSignature = txTag?.[1];
1320
- const jobEventId = ev.tags.find((t) => t[0] === "e")?.[1];
1354
+ const jobEventId = ev.tags.find((tag) => tag[0] === "e")?.[1];
1321
1355
  const hasDeliveredResult = jobEventId !== void 0 && deliveredJobsByProvider.get(targetPubkey)?.has(jobEventId) === true;
1322
1356
  if (status === "payment-completed" && typeof txSignature === "string" && txSignature && hasDeliveredResult) {
1323
1357
  if (!agent.lastPaidJobAt || ev.created_at > agent.lastPaidJobAt) {
@@ -1329,6 +1363,135 @@ var DiscoveryService = class {
1329
1363
  agents.sort(compareAgentsByRank);
1330
1364
  return agents;
1331
1365
  }
1366
+ /**
1367
+ * Stream elisym agents progressively as relays deliver events.
1368
+ *
1369
+ * Two live subscriptions:
1370
+ * - kind:31990 (capability cards) - emits `onAgent(agent)` for every new or
1371
+ * updated `(pubkey, d-tag)`. The emitted Agent is the merged view across
1372
+ * all surviving cards for that author.
1373
+ * - kind:6100 (default-offset job results) tagged `t=elisym` since 30d ago -
1374
+ * emits `onPaidJob(pubkey, ts)` for each delivered result. Custom-kind
1375
+ * results (offset != 100) are not on this stream; they enter the final
1376
+ * ranking via the post-EOSE enrichment pass.
1377
+ *
1378
+ * After capabilities EOSE, an enrichment pass runs in parallel to the live
1379
+ * subscriptions and produces a ranked snapshot via `onComplete`. The snapshot
1380
+ * is a clone, so further live updates do not mutate it.
1381
+ *
1382
+ * `closer.close()` tears down both subscriptions and aborts an in-flight
1383
+ * enrichment. If `opts.signal` is provided, aborting it does the same.
1384
+ */
1385
+ streamAgents(network, opts) {
1386
+ const eventsByPubkey = /* @__PURE__ */ new Map();
1387
+ const agentByPubkey = /* @__PURE__ */ new Map();
1388
+ const eoseSeen = { caps: false, results: false };
1389
+ let enrichmentStarted = false;
1390
+ const enrichmentAbort = new AbortController();
1391
+ const onExternalAbort = () => enrichmentAbort.abort();
1392
+ if (opts.signal) {
1393
+ if (opts.signal.aborted) {
1394
+ enrichmentAbort.abort();
1395
+ } else {
1396
+ opts.signal.addEventListener("abort", onExternalAbort, { once: true });
1397
+ }
1398
+ }
1399
+ const checkEose = () => {
1400
+ if (eoseSeen.caps && eoseSeen.results) {
1401
+ opts.onEose?.();
1402
+ }
1403
+ };
1404
+ const startEnrichment = () => {
1405
+ if (enrichmentStarted) {
1406
+ return;
1407
+ }
1408
+ enrichmentStarted = true;
1409
+ const snapshotAgents = Array.from(agentByPubkey.values()).map((agent) => ({ ...agent }));
1410
+ const snapshotMap = new Map(snapshotAgents.map((agent) => [agent.pubkey, agent]));
1411
+ void this.runEnrichment(snapshotAgents, snapshotMap, enrichmentAbort.signal).then(
1412
+ (sorted) => {
1413
+ if (enrichmentAbort.signal.aborted) {
1414
+ return;
1415
+ }
1416
+ opts.onComplete?.(sorted);
1417
+ },
1418
+ () => {
1419
+ }
1420
+ );
1421
+ };
1422
+ const capSub = this.pool.subscribe(
1423
+ { kinds: [KIND_APP_HANDLER], "#t": ["elisym"] },
1424
+ (event) => {
1425
+ const dTag = event.tags.find((tag) => tag[0] === "d")?.[1] ?? "";
1426
+ let perDTag = eventsByPubkey.get(event.pubkey);
1427
+ const prev = perDTag?.get(dTag);
1428
+ if (prev && event.created_at <= prev.created_at) {
1429
+ return;
1430
+ }
1431
+ if (!verifyEvent(event)) {
1432
+ return;
1433
+ }
1434
+ if (!event.content) {
1435
+ return;
1436
+ }
1437
+ let payload;
1438
+ try {
1439
+ payload = JSON.parse(event.content);
1440
+ } catch {
1441
+ return;
1442
+ }
1443
+ const isTombstone = payload !== null && typeof payload === "object" && Boolean(payload.deleted);
1444
+ if (!isTombstone && !parseCapabilityEvent(event, network)) {
1445
+ return;
1446
+ }
1447
+ if (!perDTag) {
1448
+ perDTag = /* @__PURE__ */ new Map();
1449
+ eventsByPubkey.set(event.pubkey, perDTag);
1450
+ }
1451
+ perDTag.set(dTag, event);
1452
+ const merged = buildAgentsFromEvents(Array.from(perDTag.values()), network).get(
1453
+ event.pubkey
1454
+ );
1455
+ if (!merged) {
1456
+ agentByPubkey.delete(event.pubkey);
1457
+ return;
1458
+ }
1459
+ agentByPubkey.set(event.pubkey, merged);
1460
+ opts.onAgent(merged);
1461
+ },
1462
+ {
1463
+ oneose: () => {
1464
+ eoseSeen.caps = true;
1465
+ startEnrichment();
1466
+ checkEose();
1467
+ }
1468
+ }
1469
+ );
1470
+ const activitySince = Math.floor(Date.now() / 1e3) - RANKING_ACTIVITY_WINDOW_SECS;
1471
+ const resultsSub = this.pool.subscribe(
1472
+ { kinds: [KIND_JOB_RESULT], "#t": ["elisym"], since: activitySince },
1473
+ (event) => {
1474
+ if (!verifyEvent(event)) {
1475
+ return;
1476
+ }
1477
+ opts.onPaidJob?.(event.pubkey, event.created_at);
1478
+ },
1479
+ {
1480
+ oneose: () => {
1481
+ eoseSeen.results = true;
1482
+ checkEose();
1483
+ }
1484
+ }
1485
+ );
1486
+ return {
1487
+ close: (reason) => {
1488
+ capSub.close(reason);
1489
+ resultsSub.close(reason);
1490
+ enrichmentAbort.abort();
1491
+ opts.signal?.removeEventListener("abort", onExternalAbort);
1492
+ }
1493
+ };
1494
+ }
1332
1495
  /**
1333
1496
  * Publish a capability card (kind:31990) as a provider.
1334
1497
  * Solana address is validated for Base58 format only - full decode
@@ -2544,8 +2707,11 @@ var NostrPool = class {
2544
2707
  throw new Error(`Failed to publish to all ${this.relays.length} relays`);
2545
2708
  }
2546
2709
  }
2547
- subscribe(filter, onEvent) {
2548
- const rawSub = this.pool.subscribeMany(this.relays, filter, { onevent: onEvent });
2710
+ subscribe(filter, onEvent, opts) {
2711
+ const rawSub = this.pool.subscribeMany(this.relays, filter, {
2712
+ onevent: onEvent,
2713
+ oneose: opts?.oneose
2714
+ });
2549
2715
  const tracked = {
2550
2716
  close: (reason) => {
2551
2717
  this.activeSubscriptions.delete(tracked);
@@ -3173,6 +3339,6 @@ function makeCensor() {
3173
3339
  };
3174
3340
  }
3175
3341
 
3176
- export { BoundedSet, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, ElisymIdentity, GlobalConfigSchema, INPUT_REDACT_PATHS, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, KNOWN_ASSETS, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, NATIVE_SOL, NostrPool, PROTOCOL_FEE_BPS, PROTOCOL_PROGRAM_ID_DEVNET, PROTOCOL_TREASURY, PaymentRequestSchema, PingService, RELAYS, SECRET_REDACT_PATHS, SessionSpendLimitEntrySchema, SolanaPaymentStrategy, USDC_SOLANA_DEVNET, aggregateNetworkStats, assertExpiry, assertLamports, assetByKey, assetKey, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatAssetAmount, formatFeeBreakdown, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parseAssetAmount, parsePaymentRequest, pickPercentileFee, resolveAssetFromPaymentRequest, resolveKnownAsset, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
3342
+ export { BoundedSet, DEFAULTS, DEFAULT_KIND_OFFSET, DEFAULT_REDACT_PATHS, DiscoveryService, ELISYM_PROTOCOL_TAG, ElisymClient, ElisymIdentity, GlobalConfigSchema, INPUT_REDACT_PATHS, KIND_APP_HANDLER, KIND_JOB_FEEDBACK, KIND_JOB_REQUEST, KIND_JOB_REQUEST_BASE, KIND_JOB_RESULT, KIND_JOB_RESULT_BASE, KIND_PING, KIND_PONG, KNOWN_ASSETS, LAMPORTS_PER_SOL, LIMITS, MarketplaceService, MediaService, NATIVE_SOL, NostrPool, PROTOCOL_PROGRAM_ID_DEVNET, PaymentRequestSchema, PingService, RELAYS, SECRET_REDACT_PATHS, SessionSpendLimitEntrySchema, SolanaPaymentStrategy, USDC_SOLANA_DEVNET, aggregateNetworkStats, assertExpiry, assertLamports, assetByKey, assetKey, buildPaymentInstructions, calculateProtocolFee, clearPriorityFeeCache, clearProtocolConfigCache, clearQuickVerifyCache, compareAgentsByRank, computeRankKey, createPaymentRequestWithOnchainConfig, createSlidingWindowLimiter, estimatePriorityFeeMicroLamports, estimateSolFeeLamports, formatAssetAmount, formatFeeBreakdown, formatSol, getProtocolConfig, getProtocolProgramId, jobRequestKind, jobResultKind, makeCensor, nip44Decrypt, nip44Encrypt, parseAssetAmount, parsePaymentRequest, pickPercentileFee, resolveAssetFromPaymentRequest, resolveKnownAsset, timeAgo, toDTag, truncateKey, validateAgentName, validateExpiry, verifyJobPaymentQuick };
3177
3343
  //# sourceMappingURL=index.js.map
3178
3344
  //# sourceMappingURL=index.js.map