@stacknet/stacks 0.1.1 → 0.2.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.
@@ -226,6 +226,8 @@ interface AgentFromPromptInput {
226
226
  }
227
227
  interface AgentsClientConfig {
228
228
  baseUrl?: string;
229
+ /** JWT auth token for authenticated requests */
230
+ authToken?: string;
229
231
  /**
230
232
  * Use the coprocessor API (/cpx/agent/agents) instead of legacy (/agents).
231
233
  * Defaults to true. Set to false for backwards compatibility.
@@ -1150,5 +1152,33 @@ interface BillingClientConfig {
1150
1152
  baseUrl?: string;
1151
1153
  authToken?: string;
1152
1154
  }
1155
+ type PaymentMethod = 'stripe' | 'solana';
1156
+ interface SolSubscriptionResult {
1157
+ subscription: {
1158
+ id: string;
1159
+ planId: string;
1160
+ planName: string;
1161
+ status: string;
1162
+ tokensGranted: number;
1163
+ periodEnd: number;
1164
+ paymentMethod: 'solana';
1165
+ txSignature: string;
1166
+ };
1167
+ }
1168
+ interface SolPrepaidResult {
1169
+ alreadyCredited: boolean;
1170
+ tokensCredited?: number;
1171
+ amountCents?: number;
1172
+ paymentRef?: string;
1173
+ paymentMethod: 'solana';
1174
+ }
1175
+ interface TopupResult {
1176
+ success: boolean;
1177
+ tokensCredited: number;
1178
+ amountCents: number;
1179
+ paymentMethod: PaymentMethod;
1180
+ paymentRef: string;
1181
+ tokenBalance: number;
1182
+ }
1153
1183
 
1154
- export { type DelegationChainLink as $, ALL_CAPABILITIES_BITMASK as A, type BillingClientConfig as B, CAPABILITY_BITS as C, type CapabilityKey as D, type ChatCompletionChunk as E, type ChatCompletionRequest as F, type ChatCompletionResponse as G, type CommentResponse as H, type CommentsResponse as I, type ConfigureOAuthInput as J, type ConfigureStripeInput as K, type ConfigureWeb3Input as L, type ConsensusStateSummary as M, type ConsensusStatus as N, type ContextDomain as O, type ContextResponse as P, type ContextsListResponse as Q, type CreateCheckoutSessionResponse as R, type CreateContextInput as S, type TaskType as T, type CreateDelegationInput as U, type CreateDomainInput as V, type CreateKeyResponse as W, type CreatePostInput as X, type CreatePostResponse as Y, type CreateStackRequest as Z, type Delegation as _, type TaskState as a, type StackMember as a$, type DelegationFilters as a0, type DelegationResponse as a1, type DelegationScope as a2, type DelegationsListResponse as a3, type DomainResponse as a4, type DomainsListResponse as a5, type FeedResponse as a6, type FileUploadResponse as a7, type FilesClientConfig as a8, type HistoryFilters as a9, type PointRecord as aA, type PointRecordResponse as aB, type PointSpend as aC, type PointSpendResponse as aD, type PointsClientConfig as aE, type PostResponse as aF, type ProfileResponse as aG, type RemixesResponse as aH, type Skill as aI, type SkillCreateInput as aJ, type SkillResponse as aK, type SkillUpdateInput as aL, type SkillsClientConfig as aM, type SkillsListResponse as aN, type SocialAuthor as aO, type SocialClientConfig as aP, type SocialComment as aQ, type SocialPost as aR, type SocialRemix as aS, type SpendDestination as aT, type SpendPointsInput as aU, type StackCapabilities as aV, type StackConfig as aW, type StackKeyInfo as aX, type StackKeysListResponse as aY, type StackListResponse as aZ, type StackManagementClientConfig as a_, type HistoryResponse as aa, type ImaginationCharacter as ab, type ImaginationMetadata as ac, type ImaginationSource as ad, type InitNetworkResponse as ae, type LeaderStatus as af, type LikeCheckResponse as ag, type LikeResponse as ah, type MCPContent as ai, type MCPMessage as aj, type MCPSession as ak, type MCPSessionConfig as al, type MCPToolResult as am, type MPCNode as an, type MagmaFile as ao, type MediaType as ap, type Message as aq, type MeteredUsage as ar, type ModelLayerInfo as as, type ModelLayersResponse as at, type NetworkClientConfig as au, type NetworkStatus as av, type PaginationMeta as aw, type PaymentRequiredResponse as ax, type PointBalance as ay, type PointContext as az, type TaskStatus as b, type StackMemberStats as b0, type StackModelAlias as b1, type StackOAuthProvider as b2, type StackResponse as b3, type StackStripeProvider as b4, type StackWeb3Provider as b5, type TaskPayload as b6, type TaskResponse as b7, type UsageRecord as b8, type UserClientConfig as b9, type UserProfile as ba, type UserProfileResponse as bb, type UserProfileUpdateInput as bc, type Widget as bd, type WidgetCreateInput as be, type WidgetResponse as bf, type WidgetSystemPromptResponse as bg, type WidgetUpdateInput as bh, type WidgetsClientConfig as bi, type WidgetsListResponse as bj, type WorkflowData as bk, bitmaskToCapabilities as bl, capabilitiesToBitmask as bm, type SkillVerifyResponse as bn, type SkillMapResponse as bo, type SkillMapPromptResponse as bp, type SkillSummaryResponse as bq, type Orientation as br, type ActionProof as c, type AddPointsInput as d, type Agent as e, type AgentCreateInput as f, type AgentExecuteRequest as g, type AgentExecuteResponse as h, type AgentFromPromptInput as i, type AgentResponse as j, type AgentTrigger as k, type AgentUpdateInput as l, type AgentWorkflow as m, type AgentWorkflowEdge as n, type AgentWorkflowNode as o, type AgentsClientConfig as p, type AgentsListResponse as q, type AllowlistConfig as r, type AllowlistMode as s, type AllowlistUpdateInput as t, type AuthMetrics as u, type BillingPlan as v, type BillingPlansResponse as w, type BillingPortalResponse as x, type BillingState as y, type BillingTier as z };
1184
+ export { type DelegationChainLink as $, ALL_CAPABILITIES_BITMASK as A, type BillingClientConfig as B, CAPABILITY_BITS as C, type CapabilityKey as D, type ChatCompletionChunk as E, type ChatCompletionRequest as F, type ChatCompletionResponse as G, type CommentResponse as H, type CommentsResponse as I, type ConfigureOAuthInput as J, type ConfigureStripeInput as K, type ConfigureWeb3Input as L, type ConsensusStateSummary as M, type ConsensusStatus as N, type ContextDomain as O, type ContextResponse as P, type ContextsListResponse as Q, type CreateCheckoutSessionResponse as R, type CreateContextInput as S, type TaskType as T, type CreateDelegationInput as U, type CreateDomainInput as V, type CreateKeyResponse as W, type CreatePostInput as X, type CreatePostResponse as Y, type CreateStackRequest as Z, type Delegation as _, type TaskState as a, type StackMember as a$, type DelegationFilters as a0, type DelegationResponse as a1, type DelegationScope as a2, type DelegationsListResponse as a3, type DomainResponse as a4, type DomainsListResponse as a5, type FeedResponse as a6, type FileUploadResponse as a7, type FilesClientConfig as a8, type HistoryFilters as a9, type PointRecord as aA, type PointRecordResponse as aB, type PointSpend as aC, type PointSpendResponse as aD, type PointsClientConfig as aE, type PostResponse as aF, type ProfileResponse as aG, type RemixesResponse as aH, type Skill as aI, type SkillCreateInput as aJ, type SkillResponse as aK, type SkillUpdateInput as aL, type SkillsClientConfig as aM, type SkillsListResponse as aN, type SocialAuthor as aO, type SocialClientConfig as aP, type SocialComment as aQ, type SocialPost as aR, type SocialRemix as aS, type SpendDestination as aT, type SpendPointsInput as aU, type StackCapabilities as aV, type StackConfig as aW, type StackKeyInfo as aX, type StackKeysListResponse as aY, type StackListResponse as aZ, type StackManagementClientConfig as a_, type HistoryResponse as aa, type ImaginationCharacter as ab, type ImaginationMetadata as ac, type ImaginationSource as ad, type InitNetworkResponse as ae, type LeaderStatus as af, type LikeCheckResponse as ag, type LikeResponse as ah, type MCPContent as ai, type MCPMessage as aj, type MCPSession as ak, type MCPSessionConfig as al, type MCPToolResult as am, type MPCNode as an, type MagmaFile as ao, type MediaType as ap, type Message as aq, type MeteredUsage as ar, type ModelLayerInfo as as, type ModelLayersResponse as at, type NetworkClientConfig as au, type NetworkStatus as av, type PaginationMeta as aw, type PaymentRequiredResponse as ax, type PointBalance as ay, type PointContext as az, type TaskStatus as b, type StackMemberStats as b0, type StackModelAlias as b1, type StackOAuthProvider as b2, type StackResponse as b3, type StackStripeProvider as b4, type StackWeb3Provider as b5, type TaskPayload as b6, type TaskResponse as b7, type UsageRecord as b8, type UserClientConfig as b9, type UserProfile as ba, type UserProfileResponse as bb, type UserProfileUpdateInput as bc, type Widget as bd, type WidgetCreateInput as be, type WidgetResponse as bf, type WidgetSystemPromptResponse as bg, type WidgetUpdateInput as bh, type WidgetsClientConfig as bi, type WidgetsListResponse as bj, type WorkflowData as bk, bitmaskToCapabilities as bl, capabilitiesToBitmask as bm, type SkillVerifyResponse as bn, type SkillMapResponse as bo, type SkillMapPromptResponse as bp, type SkillSummaryResponse as bq, type Orientation as br, type PaymentMethod as bs, type SolPrepaidResult as bt, type SolSubscriptionResult as bu, type TopupResult as bv, type ActionProof as c, type AddPointsInput as d, type Agent as e, type AgentCreateInput as f, type AgentExecuteRequest as g, type AgentExecuteResponse as h, type AgentFromPromptInput as i, type AgentResponse as j, type AgentTrigger as k, type AgentUpdateInput as l, type AgentWorkflow as m, type AgentWorkflowEdge as n, type AgentWorkflowNode as o, type AgentsClientConfig as p, type AgentsListResponse as q, type AllowlistConfig as r, type AllowlistMode as s, type AllowlistUpdateInput as t, type AuthMetrics as u, type BillingPlan as v, type BillingPlansResponse as w, type BillingPortalResponse as x, type BillingState as y, type BillingTier as z };
@@ -226,6 +226,8 @@ interface AgentFromPromptInput {
226
226
  }
227
227
  interface AgentsClientConfig {
228
228
  baseUrl?: string;
229
+ /** JWT auth token for authenticated requests */
230
+ authToken?: string;
229
231
  /**
230
232
  * Use the coprocessor API (/cpx/agent/agents) instead of legacy (/agents).
231
233
  * Defaults to true. Set to false for backwards compatibility.
@@ -1150,5 +1152,33 @@ interface BillingClientConfig {
1150
1152
  baseUrl?: string;
1151
1153
  authToken?: string;
1152
1154
  }
1155
+ type PaymentMethod = 'stripe' | 'solana';
1156
+ interface SolSubscriptionResult {
1157
+ subscription: {
1158
+ id: string;
1159
+ planId: string;
1160
+ planName: string;
1161
+ status: string;
1162
+ tokensGranted: number;
1163
+ periodEnd: number;
1164
+ paymentMethod: 'solana';
1165
+ txSignature: string;
1166
+ };
1167
+ }
1168
+ interface SolPrepaidResult {
1169
+ alreadyCredited: boolean;
1170
+ tokensCredited?: number;
1171
+ amountCents?: number;
1172
+ paymentRef?: string;
1173
+ paymentMethod: 'solana';
1174
+ }
1175
+ interface TopupResult {
1176
+ success: boolean;
1177
+ tokensCredited: number;
1178
+ amountCents: number;
1179
+ paymentMethod: PaymentMethod;
1180
+ paymentRef: string;
1181
+ tokenBalance: number;
1182
+ }
1153
1183
 
1154
- export { type DelegationChainLink as $, ALL_CAPABILITIES_BITMASK as A, type BillingClientConfig as B, CAPABILITY_BITS as C, type CapabilityKey as D, type ChatCompletionChunk as E, type ChatCompletionRequest as F, type ChatCompletionResponse as G, type CommentResponse as H, type CommentsResponse as I, type ConfigureOAuthInput as J, type ConfigureStripeInput as K, type ConfigureWeb3Input as L, type ConsensusStateSummary as M, type ConsensusStatus as N, type ContextDomain as O, type ContextResponse as P, type ContextsListResponse as Q, type CreateCheckoutSessionResponse as R, type CreateContextInput as S, type TaskType as T, type CreateDelegationInput as U, type CreateDomainInput as V, type CreateKeyResponse as W, type CreatePostInput as X, type CreatePostResponse as Y, type CreateStackRequest as Z, type Delegation as _, type TaskState as a, type StackMember as a$, type DelegationFilters as a0, type DelegationResponse as a1, type DelegationScope as a2, type DelegationsListResponse as a3, type DomainResponse as a4, type DomainsListResponse as a5, type FeedResponse as a6, type FileUploadResponse as a7, type FilesClientConfig as a8, type HistoryFilters as a9, type PointRecord as aA, type PointRecordResponse as aB, type PointSpend as aC, type PointSpendResponse as aD, type PointsClientConfig as aE, type PostResponse as aF, type ProfileResponse as aG, type RemixesResponse as aH, type Skill as aI, type SkillCreateInput as aJ, type SkillResponse as aK, type SkillUpdateInput as aL, type SkillsClientConfig as aM, type SkillsListResponse as aN, type SocialAuthor as aO, type SocialClientConfig as aP, type SocialComment as aQ, type SocialPost as aR, type SocialRemix as aS, type SpendDestination as aT, type SpendPointsInput as aU, type StackCapabilities as aV, type StackConfig as aW, type StackKeyInfo as aX, type StackKeysListResponse as aY, type StackListResponse as aZ, type StackManagementClientConfig as a_, type HistoryResponse as aa, type ImaginationCharacter as ab, type ImaginationMetadata as ac, type ImaginationSource as ad, type InitNetworkResponse as ae, type LeaderStatus as af, type LikeCheckResponse as ag, type LikeResponse as ah, type MCPContent as ai, type MCPMessage as aj, type MCPSession as ak, type MCPSessionConfig as al, type MCPToolResult as am, type MPCNode as an, type MagmaFile as ao, type MediaType as ap, type Message as aq, type MeteredUsage as ar, type ModelLayerInfo as as, type ModelLayersResponse as at, type NetworkClientConfig as au, type NetworkStatus as av, type PaginationMeta as aw, type PaymentRequiredResponse as ax, type PointBalance as ay, type PointContext as az, type TaskStatus as b, type StackMemberStats as b0, type StackModelAlias as b1, type StackOAuthProvider as b2, type StackResponse as b3, type StackStripeProvider as b4, type StackWeb3Provider as b5, type TaskPayload as b6, type TaskResponse as b7, type UsageRecord as b8, type UserClientConfig as b9, type UserProfile as ba, type UserProfileResponse as bb, type UserProfileUpdateInput as bc, type Widget as bd, type WidgetCreateInput as be, type WidgetResponse as bf, type WidgetSystemPromptResponse as bg, type WidgetUpdateInput as bh, type WidgetsClientConfig as bi, type WidgetsListResponse as bj, type WorkflowData as bk, bitmaskToCapabilities as bl, capabilitiesToBitmask as bm, type SkillVerifyResponse as bn, type SkillMapResponse as bo, type SkillMapPromptResponse as bp, type SkillSummaryResponse as bq, type Orientation as br, type ActionProof as c, type AddPointsInput as d, type Agent as e, type AgentCreateInput as f, type AgentExecuteRequest as g, type AgentExecuteResponse as h, type AgentFromPromptInput as i, type AgentResponse as j, type AgentTrigger as k, type AgentUpdateInput as l, type AgentWorkflow as m, type AgentWorkflowEdge as n, type AgentWorkflowNode as o, type AgentsClientConfig as p, type AgentsListResponse as q, type AllowlistConfig as r, type AllowlistMode as s, type AllowlistUpdateInput as t, type AuthMetrics as u, type BillingPlan as v, type BillingPlansResponse as w, type BillingPortalResponse as x, type BillingState as y, type BillingTier as z };
1184
+ export { type DelegationChainLink as $, ALL_CAPABILITIES_BITMASK as A, type BillingClientConfig as B, CAPABILITY_BITS as C, type CapabilityKey as D, type ChatCompletionChunk as E, type ChatCompletionRequest as F, type ChatCompletionResponse as G, type CommentResponse as H, type CommentsResponse as I, type ConfigureOAuthInput as J, type ConfigureStripeInput as K, type ConfigureWeb3Input as L, type ConsensusStateSummary as M, type ConsensusStatus as N, type ContextDomain as O, type ContextResponse as P, type ContextsListResponse as Q, type CreateCheckoutSessionResponse as R, type CreateContextInput as S, type TaskType as T, type CreateDelegationInput as U, type CreateDomainInput as V, type CreateKeyResponse as W, type CreatePostInput as X, type CreatePostResponse as Y, type CreateStackRequest as Z, type Delegation as _, type TaskState as a, type StackMember as a$, type DelegationFilters as a0, type DelegationResponse as a1, type DelegationScope as a2, type DelegationsListResponse as a3, type DomainResponse as a4, type DomainsListResponse as a5, type FeedResponse as a6, type FileUploadResponse as a7, type FilesClientConfig as a8, type HistoryFilters as a9, type PointRecord as aA, type PointRecordResponse as aB, type PointSpend as aC, type PointSpendResponse as aD, type PointsClientConfig as aE, type PostResponse as aF, type ProfileResponse as aG, type RemixesResponse as aH, type Skill as aI, type SkillCreateInput as aJ, type SkillResponse as aK, type SkillUpdateInput as aL, type SkillsClientConfig as aM, type SkillsListResponse as aN, type SocialAuthor as aO, type SocialClientConfig as aP, type SocialComment as aQ, type SocialPost as aR, type SocialRemix as aS, type SpendDestination as aT, type SpendPointsInput as aU, type StackCapabilities as aV, type StackConfig as aW, type StackKeyInfo as aX, type StackKeysListResponse as aY, type StackListResponse as aZ, type StackManagementClientConfig as a_, type HistoryResponse as aa, type ImaginationCharacter as ab, type ImaginationMetadata as ac, type ImaginationSource as ad, type InitNetworkResponse as ae, type LeaderStatus as af, type LikeCheckResponse as ag, type LikeResponse as ah, type MCPContent as ai, type MCPMessage as aj, type MCPSession as ak, type MCPSessionConfig as al, type MCPToolResult as am, type MPCNode as an, type MagmaFile as ao, type MediaType as ap, type Message as aq, type MeteredUsage as ar, type ModelLayerInfo as as, type ModelLayersResponse as at, type NetworkClientConfig as au, type NetworkStatus as av, type PaginationMeta as aw, type PaymentRequiredResponse as ax, type PointBalance as ay, type PointContext as az, type TaskStatus as b, type StackMemberStats as b0, type StackModelAlias as b1, type StackOAuthProvider as b2, type StackResponse as b3, type StackStripeProvider as b4, type StackWeb3Provider as b5, type TaskPayload as b6, type TaskResponse as b7, type UsageRecord as b8, type UserClientConfig as b9, type UserProfile as ba, type UserProfileResponse as bb, type UserProfileUpdateInput as bc, type Widget as bd, type WidgetCreateInput as be, type WidgetResponse as bf, type WidgetSystemPromptResponse as bg, type WidgetUpdateInput as bh, type WidgetsClientConfig as bi, type WidgetsListResponse as bj, type WorkflowData as bk, bitmaskToCapabilities as bl, capabilitiesToBitmask as bm, type SkillVerifyResponse as bn, type SkillMapResponse as bo, type SkillMapPromptResponse as bp, type SkillSummaryResponse as bq, type Orientation as br, type PaymentMethod as bs, type SolPrepaidResult as bt, type SolSubscriptionResult as bu, type TopupResult as bv, type ActionProof as c, type AddPointsInput as d, type Agent as e, type AgentCreateInput as f, type AgentExecuteRequest as g, type AgentExecuteResponse as h, type AgentFromPromptInput as i, type AgentResponse as j, type AgentTrigger as k, type AgentUpdateInput as l, type AgentWorkflow as m, type AgentWorkflowEdge as n, type AgentWorkflowNode as o, type AgentsClientConfig as p, type AgentsListResponse as q, type AllowlistConfig as r, type AllowlistMode as s, type AllowlistUpdateInput as t, type AuthMetrics as u, type BillingPlan as v, type BillingPlansResponse as w, type BillingPortalResponse as x, type BillingState as y, type BillingTier as z };
@@ -1,4 +1,4 @@
1
- 'use strict';var d="https://stacknet.magma-rpc.com",u=d;var g="http://geoff.magma-rpc.com";var l={"Content-Type":"application/json"};var f=class{baseUrl;apiKey;timeout;constructor(e={}){this.baseUrl=(e.baseUrl||u).replace(/\/$/,""),this.apiKey=e.apiKey,this.timeout=e.timeout||6e4;}async*chatCompletions(e){let t=e.messages.filter(n=>n.role==="user"),s=t[t.length-1]?.content||"",r=await this.submitTask({type:"ai-prompt",model:e.model,prompt:s,sessionId:e.sessionId,temperature:e.temperature,maxTokens:e.max_tokens,stream:true});yield*this.streamTaskResults(r,e.model);}async submitTask(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Task submission failed: ${n}`)}let s=await t.json(),r=s.taskId||s.id;if(!r)throw new Error("Task submission did not return a taskId");return r}async submitTaskFull(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let r=await t.text();throw new Error(`Task submission failed: ${r}`)}let s=await t.json();return {taskId:s.taskId||s.id,output:s.output,status:s.status}}async getTask(e){let t=await fetch(`${this.baseUrl}/tasks/${e}`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Failed to get task: ${t.statusText}`);return t.json()}async*streamTaskResults(e,t){let s=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!s.ok)throw new Error(`Stream failed: ${s.statusText}`);if(!s.body)throw new Error("Response body is null");let r=s.body.getReader(),n=new TextDecoder,i="",c="",p=Math.floor(Date.now()/1e3);try{for(;;){let{done:h,value:Y}=await r.read();if(h){yield {id:e,object:"chat.completion.chunk",created:p,model:t,choices:[{index:0,delta:{},finish_reason:"stop"}]};break}i+=n.decode(Y,{stream:!0});let A=i.split(`
2
- `);i=A.pop()||"";for(let v of A)if(v.startsWith("data: "))try{let E=JSON.parse(v.slice(6));if(Array.isArray(E)&&E.length>0){let m=E[0].result||"";if(m&&m!==c){let F=m.substring(c.length);c=m,F&&(yield {id:e,object:"chat.completion.chunk",created:p,model:t,choices:[{index:0,delta:{role:"assistant",content:F},finish_reason:null}]});}}}catch{}}}finally{r.releaseLock();}}async*streamTaskRaw(e){let t=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Stream failed: ${t.statusText}`);if(!t.body)throw new Error("Response body is null");let s=t.body.getReader(),r=new TextDecoder,n="";try{for(;;){let{done:i,value:c}=await s.read();if(i)break;n+=r.decode(c,{stream:!0});let p=n.split(`
3
- `);n=p.pop()||"";for(let h of p)if(h.startsWith("data: "))try{yield JSON.parse(h.slice(6));}catch{}}}finally{s.releaseLock();}}async healthCheck(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNode(){let e=await fetch(`${this.baseUrl}/node`);if(!e.ok)throw new Error(`Failed to get node info: ${e.statusText}`);return e.json()}};function q(a){return new f(a)}var V=q();async function M(a){let e=await crypto.subtle.digest("SHA-256",a);return `baf${Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,52)}`}var y=class{baseUrl;localServerUrl;constructor(e={}){this.baseUrl=e.baseUrl||g,this.localServerUrl=e.localServerUrl||u;}async uploadFile(e){let t=await e.arrayBuffer(),s=await M(t),r=this.arrayBufferToBase64(t);return typeof localStorage<"u"&&localStorage.setItem(`file:${s}`,JSON.stringify({cid:s,name:e.name,type:e.type,size:e.size,data:r})),{cid:s,name:e.name,size:e.size,type:e.type,url:`data:${e.type};base64,${r}`}}async uploadText(e,t){let s=new Blob([e],{type:"text/plain"}),r=new File([s],t,{type:"text/plain"});return this.uploadFile(r)}async storeImagination(e){let t=e.createdBy||"anonymous",r=(await fetch(`${this.localServerUrl}/imaginations/${e.id}`)).ok,n={id:e.id,title:e.title,sources:e.sources,summary:e.summary,character:e.character,workflow:e.workflow,is_public:e.is_public||false,creator_mid:t};if(r){let i=await fetch(`${this.localServerUrl}/imaginations/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok)throw new Error(`Failed to update imagination: ${i.statusText}`);return typeof localStorage<"u"&&localStorage.setItem(`imagination:${e.id}`,e.id),e.id}else {let i=await fetch(`${this.localServerUrl}/imaginations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!i.ok)throw new Error(`Failed to store imagination: ${i.statusText}`);let p=(await i.json()).imagination?.id||e.id;return typeof localStorage<"u"&&localStorage.setItem(`imagination:${p}`,p),p}}async getImagination(e){try{let t=await fetch(`${this.localServerUrl}/imaginations/${e}`);if(!t.ok)return null;let s=await t.json();return s.imagination?{id:s.imagination.id,title:s.imagination.title,createdAt:new Date(s.imagination.created_at).toISOString(),createdBy:s.imagination.creator_mid,sources:s.imagination.sources,summary:s.imagination.summary,character:s.imagination.character,workflow:s.imagination.workflow,is_public:s.imagination.is_public}:null}catch(t){return console.error("Failed to retrieve imagination:",t),null}}async getImaginationByCID(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);if(!t.ok)return null;let s=await t.json();return typeof localStorage<"u"&&localStorage.setItem(`imagination:${s.id}`,e),s}catch(t){return console.error("Failed to retrieve imagination by CID:",t),null}}async listImaginations(e){try{let t=e||"anonymous",s=await fetch(`${this.localServerUrl}/imaginations?creator_mid=${encodeURIComponent(t)}`);if(!s.ok)return console.warn("Failed to fetch imaginations from P2P, falling back to localStorage"),this.listImaginationsFromLocalStorage();let n=(await s.json()).imaginations.map(i=>({id:i.id,title:i.title,createdAt:new Date(i.created_at).toISOString(),createdBy:i.creator_mid,sources:i.sources,summary:i.summary,character:i.character,workflow:i.workflow,is_public:i.is_public}));return typeof localStorage<"u"&&n.forEach(i=>{localStorage.setItem(`imagination:${i.id}`,i.id);}),n}catch(t){return console.error("Failed to list imaginations:",t),this.listImaginationsFromLocalStorage()}}async listImaginationsFromLocalStorage(){if(typeof localStorage>"u")return [];let e=[];for(let t=0;t<localStorage.length;t++){let s=localStorage.key(t);if(s&&s.startsWith("imagination:")){let r=s.replace("imagination:",""),n=await this.getImagination(r);n&&e.push(n);}}return e}async getFile(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);return t.ok?await t.blob():null}catch(t){return console.error("Failed to retrieve file:",t),null}}arrayBufferToBase64(e){let t=new Uint8Array(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}};function O(a){return new y(a)}var X=O();var w=class{baseUrl;timeout;sessions=new Map;constructor(e={}){this.baseUrl=e.baseUrl||"http://localhost:3006",this.timeout=e.timeout||3e4;}async createSession(e="default"){let t=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;try{let s={id:t,agentId:e,status:"active",createdAt:new Date};this.sessions.set(t,s);try{await fetch(`${this.baseUrl}/mcp/sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t,agentId:e,clientInfo:{name:"stacknet-sdk",version:"0.1.0"}})});}catch{}return s}catch(s){throw new Error(`Failed to create MCP session: ${s}`)}}getSession(e){return this.sessions.get(e)}async closeSession(e){let t=this.sessions.get(e);if(t){t.status="closed";try{await fetch(`${this.baseUrl}/mcp/sessions/${e}`,{method:"DELETE"});}catch{}this.sessions.delete(e);}}async sendMessage(e,t){let s=this.sessions.get(e);if(!s||s.status!=="active")throw new Error("Invalid or inactive session");try{let r=await fetch(`${this.baseUrl}/mcp/sessions/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:[{role:"user",content:{type:"text",text:t}}]})});if(!r.ok)throw new Error(`MCP request failed: ${r.statusText}`);return r.json()}catch(r){throw new Error(`Failed to send message: ${r}`)}}async callTool(e,t,s={}){let r=this.sessions.get(e);if(!r||r.status!=="active")throw new Error("Invalid or inactive session");try{let n=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok)throw new Error(`Tool call failed: ${n.statusText}`);return n.json()}catch(n){throw new Error(`Failed to call tool: ${n}`)}}async listTools(e){let t=this.sessions.get(e);if(!t||t.status!=="active")throw new Error("Invalid or inactive session");try{let s=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools`);return s.ok?(await s.json()).tools||[]:[]}catch{return []}}getActiveSessions(){return Array.from(this.sessions.values()).filter(e=>e.status==="active")}async closeAllSessions(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(t=>this.closeSession(t)));}};function I(a){return new w(a)}var Q=I();var Z={database:"log",chat:"response",auth:"response",stream:"response",api:"response",history:"response",vote:"response",document:"response",suggestions:"response",task:"response",agent:"response",imagination:"response"},o=class extends Error{type;surface;statusCode;constructor(e,t){super();let[s,r]=e.split(":");this.type=s,this.cause=t,this.surface=r,this.message=ee(e),this.statusCode=te(this.type);}toJSON(){return {code:`${this.type}:${this.surface}`,message:this.message,cause:this.cause,statusCode:this.statusCode}}toResponse(){let e=`${this.type}:${this.surface}`,t=Z[this.surface],{message:s,cause:r,statusCode:n}=this;return t==="log"?(console.error({code:e,message:s,cause:r}),Response.json({code:"",message:"Something went wrong. Please try again later."},{status:n})):Response.json({code:e,message:s,cause:r},{status:n})}};function ee(a){if(a.includes("database"))return "An error occurred while executing a database query.";switch(a){case "bad_request:api":return "The request couldn't be processed. Please check your input and try again.";case "unauthorized:auth":return "You need to sign in before continuing.";case "unauthorized:api":return "Your session has expired. Please sign in again.";case "forbidden:auth":return "Your account does not have access to this feature.";case "rate_limit:chat":return "You have exceeded your maximum number of messages for the day. Please try again later.";case "not_found:chat":return "The requested chat was not found.";case "forbidden:chat":return "This chat belongs to another user.";case "unauthorized:chat":return "You need to sign in to view this chat.";case "offline:chat":return "We're having trouble sending your message. Please check your internet connection.";case "not_found:task":return "The requested task was not found.";case "forbidden:task":return "You do not have access to this task.";case "not_found:agent":return "The requested agent was not found.";case "forbidden:agent":return "You do not have access to this agent.";case "not_found:imagination":return "The requested imagination was not found.";case "forbidden:imagination":return "You do not have access to this imagination.";case "not_found:document":return "The requested document was not found.";case "forbidden:document":return "This document belongs to another user.";case "unauthorized:document":return "You need to sign in to view this document.";case "bad_request:document":return "The request to create or update the document was invalid.";default:return "Something went wrong. Please try again later."}}function te(a){switch(a){case "bad_request":return 400;case "unauthorized":return 401;case "payment_required":return 402;case "forbidden":return 403;case "not_found":return 404;case "rate_limit":return 429;case "offline":return 503;case "internal":return 500;default:return 500}}var k=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get socialUrl(){return `${this.baseUrl}/social`}async getFeed(e={}){let{page:t=1,limit:s=10,mediaType:r}=e,n=new URLSearchParams({page:String(t),limit:String(s)});r&&n.set("media_type",r);let i=await fetch(`${this.socialUrl}/feed?${n}`);if(!i.ok)throw new o("bad_request:api",`Failed to fetch feed: ${i.statusText}`);return i.json()}async getPost(e){let t=await fetch(`${this.socialUrl}/posts/${e}`);if(!t.ok)throw new o(t.status===404?"not_found:api":"bad_request:api",`Failed to fetch post: ${t.statusText}`);return t.json()}async getComments(e){let t=await fetch(`${this.socialUrl}/posts/${e}/comments`);if(!t.ok)throw new o("bad_request:api",`Failed to fetch comments: ${t.statusText}`);return t.json()}async getRemixes(e){let t=await fetch(`${this.socialUrl}/posts/${e}/remixes`);if(!t.ok)throw new o("bad_request:api",`Failed to fetch remixes: ${t.statusText}`);return t.json()}async checkLike(e,t){let s=await fetch(`${this.socialUrl}/posts/${e}/likes/check?userMid=${encodeURIComponent(t)}`);if(!s.ok)throw new o("bad_request:api",`Failed to check like status: ${s.statusText}`);return s.json()}async likePost(e,t){let s=await fetch(`${this.socialUrl}/like`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new o("bad_request:api",`Failed to like post: ${s.statusText}`);return s.json()}async unlikePost(e,t){let s=await fetch(`${this.socialUrl}/unlike`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new o("bad_request:api",`Failed to unlike post: ${s.statusText}`);return s.json()}async addComment(e,t,s){let r=await fetch(`${this.socialUrl}/comment`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t,content:s})});if(!r.ok)throw new o("bad_request:api",`Failed to add comment: ${r.statusText}`);return r.json()}async createPost(e){let t=await fetch(`${this.socialUrl}/post`,{method:"POST",headers:l,body:JSON.stringify({userMid:e.creatorMid,content:e.content,mediaUrl:e.mediaUrl,mediaType:e.mediaType,orientation:e.orientation,posterUrl:e.posterUrl,remixOf:e.remixOf})});if(!t.ok)throw new o("bad_request:api",`Failed to create post: ${t.statusText}`);return t.json()}async trackView(e,t){await fetch(`${this.socialUrl}/posts/${e}/view`,{method:"POST",headers:l,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:l,body:JSON.stringify({userMid:t})}).catch(()=>{});}async getProfile(e){try{let t=await fetch(`${this.socialUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new o("bad_request:api",`Failed to fetch profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof o)throw t;return null}}};function j(a={}){return new k(a)}var se=j();var S=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||u,this.useCpxApi=e.useCpxApi!==false;}get agentsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/agents`:`${this.baseUrl}/agents`}async list(e={}){let t=new URLSearchParams;e.userMid&&t.set("userMid",e.userMid);let s=t.toString(),r=`${this.agentsUrl}${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new o("bad_request:api",`Failed to list agents: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.agentsUrl}/${e}`);if(!t.ok)throw new o(t.status===404?"not_found:api":"bad_request:api",`Failed to get agent: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.agentsUrl,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new o("bad_request:api",s.error||`Failed to create agent: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.agentsUrl}/${e}`,{method:"PUT",headers:l,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new o("bad_request:api",r.error||`Failed to update agent: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.agentsUrl}/${e}`,{method:"DELETE"});if(!t.ok)throw new o("bad_request:api",`Failed to delete agent: ${t.statusText}`);return t.json()}async enable(e){let t=await fetch(`${this.agentsUrl}/${e}/enable`,{method:"POST"});if(!t.ok)throw new o("bad_request:api",`Failed to enable agent: ${t.statusText}`);return t.json()}async disable(e){let t=await fetch(`${this.agentsUrl}/${e}/disable`,{method:"POST"});if(!t.ok)throw new o("bad_request:api",`Failed to disable agent: ${t.statusText}`);return t.json()}async execute(e,t={}){let s=await fetch(`${this.agentsUrl}/${e}/execute`,{method:"POST",headers:l,body:JSON.stringify(t)});if(!s.ok)throw new o("bad_request:api",`Failed to execute agent: ${s.statusText}`);return s.json()}async createFromPrompt(e){let t=await fetch(`${this.agentsUrl}/from-prompt`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok)throw new o("bad_request:api",`Failed to generate agent from prompt: ${t.statusText}`);let s=await t.json();return this.create({...s,created_by:e.created_by})}};function L(a={}){return new S(a)}var re=L();var C=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get widgetsUrl(){return `${this.baseUrl}/widgets`}async list(e={}){let t=new URLSearchParams;e.creatorMid?t.set("creator_mid",e.creatorMid):e.scope&&t.set("scope",e.scope);let s=t.toString(),r=`${this.widgetsUrl}${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new o("bad_request:api",`Failed to list widgets: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.widgetsUrl}/${e}`);if(!t.ok)throw new o(t.status===404?"not_found:api":"bad_request:api",`Failed to get widget: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.widgetsUrl,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new o("bad_request:api",s.error||`Failed to create widget: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.widgetsUrl}/${e}`,{method:"PUT",headers:l,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new o("bad_request:api",r.error||`Failed to update widget: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.widgetsUrl}/${e}`,{method:"DELETE"});if(!t.ok)throw new o("bad_request:api",`Failed to delete widget: ${t.statusText}`);return t.json()}async getSystemPrompt(){let e=await fetch(`${this.widgetsUrl}/system-prompt`);if(!e.ok)throw new o("bad_request:api",`Failed to get widget system prompt: ${e.statusText}`);return e.json()}async trackUsage(e){await fetch(`${this.widgetsUrl}/${e}/usage`,{method:"POST"}).catch(()=>{});}};function D(a={}){return new C(a)}var ne=D();var b=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get userUrl(){return `${this.baseUrl}/user`}async getProfile(e){try{let t=await fetch(`${this.userUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new o("bad_request:api",`Failed to get user profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof o)throw t;return null}}async updateProfile(e,t){let s=await fetch(`${this.userUrl}/profile/${e}`,{method:"PUT",headers:l,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new o("bad_request:api",r.error||`Failed to update user profile: ${s.statusText}`)}return s.json()}};function N(a={}){return new b(a)}var oe=N();var P=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get filesUrl(){return `${this.baseUrl}/files`}async upload(e,t){let s=new FormData;s.append("file",e,t);let r=await fetch(`${this.filesUrl}/upload`,{method:"POST",body:s});if(!r.ok)throw new o("bad_request:api",`Failed to upload file: ${r.statusText}`);return r.json()}async uploadFromUrl(e){let t=await fetch(`${this.filesUrl}/upload-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})});if(!t.ok)throw new o("bad_request:api",`Failed to upload file from URL: ${t.statusText}`);return t.json()}getFileUrl(e){return `${this.filesUrl}/${e}`}};function K(a={}){return new P(a)}var ie=K();var $=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||g,this.useCpxApi=e.useCpxApi!==false;}get skillsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/skills`:`${this.baseUrl}/skills`}async list(e){let t=new URLSearchParams;e?.precompiled?(t.set("precompiled","true"),e?.contentType&&t.set("content_type",e.contentType)):e?.contentType?t.set("content_type",e.contentType):e?.creatorMid?t.set("creator_mid",e.creatorMid):e?.scope&&e.scope!=="all"&&t.set("scope",e.scope);let s=t.toString()?`${this.skillsUrl}?${t.toString()}`:this.skillsUrl,r=await fetch(s);if(!r.ok)throw new Error(`Failed to list skills: ${r.statusText}`);return r.json()}async get(e){let t=await fetch(`${this.skillsUrl}/${e}`);if(!t.ok)throw new Error(`Skill not found: ${e}`);return t.json()}async create(e){let t=await fetch(this.skillsUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to create skill: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.skillsUrl}/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new Error(r.error||`Failed to update skill: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.skillsUrl}/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to delete skill: ${t.statusText}`)}return t.json()}async trackUsage(e){try{await fetch(`${this.skillsUrl}/${e}/usage`,{method:"POST"});}catch{}}async verify(e){let t=await fetch(`${this.skillsUrl}/${e}/verify`);if(!t.ok)throw new Error(`Failed to verify skill: ${t.statusText}`);return t.json()}async rehash(e){let t=await fetch(`${this.skillsUrl}/${e}/rehash`,{method:"POST"});if(!t.ok)throw new Error(`Failed to rehash skill: ${t.statusText}`);return t.json()}async rehashAll(){let e=await fetch(`${this.skillsUrl}/rehash-all`,{method:"POST"});if(!e.ok)throw new Error(`Failed to rehash all skills: ${e.statusText}`);return e.json()}async getMap(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map${t}`);if(!s.ok)throw new Error(`Failed to get skill map: ${s.statusText}`);return s.json()}async getMapPrompt(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map/prompt${t}`);if(!s.ok)throw new Error(`Failed to get skill map prompt: ${s.statusText}`);return s.json()}async getNonCodeMap(){let e=await fetch(`${this.skillsUrl}/map/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill map: ${e.statusText}`);return e.json()}async getNonCodeSummary(){let e=await fetch(`${this.skillsUrl}/summary/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill summary: ${e.statusText}`);return e.json()}};function B(a){return new $(a)}var ae=B();var T=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||g;}get pointsUrl(){return `${this.baseUrl}/cpx/points`}async initNetworkDomain(){let e=await fetch(`${this.pointsUrl}/init`,{method:"POST",headers:l});if(!e.ok){let t=await e.json().catch(()=>({}));throw new o("bad_request:api",t.error||`Failed to initialize network domain: ${e.statusText}`)}return e.json()}async listDomains(){let e=await fetch(`${this.pointsUrl}/domains`);if(!e.ok)throw new o("bad_request:api",`Failed to list domains: ${e.statusText}`);return e.json()}async getDomain(e){let t=await fetch(`${this.pointsUrl}/domains/${e}`);if(t.status===404)return null;if(!t.ok)throw new o("bad_request:api",`Failed to get domain: ${t.statusText}`);return t.json()}async createDomain(e){let t=await fetch(`${this.pointsUrl}/domains`,{method:"POST",headers:l,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new o("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new o("bad_request:api",s.error||`Failed to create domain: ${t.statusText}`)}return t.json()}async listContexts(e){let t=e?`?domainId=${e}`:"",s=await fetch(`${this.pointsUrl}/contexts${t}`);if(!s.ok)throw new o("bad_request:api",`Failed to list contexts: ${s.statusText}`);return s.json()}async getContext(e){let t=await fetch(`${this.pointsUrl}/contexts/${e}`);if(t.status===404)return null;if(!t.ok)throw new o("bad_request:api",`Failed to get context: ${t.statusText}`);return t.json()}async createContext(e){let t=await fetch(`${this.pointsUrl}/contexts`,{method:"POST",headers:l,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new o("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new o("bad_request:api",s.error||`Failed to create context: ${t.statusText}`)}return t.json()}async listDelegations(e={}){let t=new URLSearchParams;e.domainId&&t.set("domainId",e.domainId),e.delegator&&t.set("delegator",e.delegator),e.delegate&&t.set("delegate",e.delegate),e.activeOnly&&t.set("activeOnly","true");let s=t.toString(),r=`${this.pointsUrl}/delegations${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new o("bad_request:api",`Failed to list delegations: ${n.statusText}`);return n.json()}async createDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new o("bad_request:api",s.error||`Failed to create delegation: ${t.statusText}`)}return t.json()}async revokeDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new o("bad_request:api",s.error||`Failed to revoke delegation: ${t.statusText}`)}return t.json()}async addPoints(e){let t=await fetch(`${this.pointsUrl}/add`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new o("bad_request:api",s.error||`Failed to add points: ${t.statusText}`)}return t.json()}async spendPoints(e){let t=await fetch(`${this.pointsUrl}/spend`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new o("bad_request:api",s.error||`Failed to spend points: ${t.statusText}`)}return t.json()}async getBalance(e,t={}){let s=new URLSearchParams;t.domainId&&s.set("domainId",t.domainId),t.contextId&&s.set("contextId",t.contextId);let r=s.toString(),n=`${this.pointsUrl}/balance/${e}${r?`?${r}`:""}`,i=await fetch(n);if(!i.ok)throw new o("bad_request:api",`Failed to get balance: ${i.statusText}`);return i.json()}async getHistory(e={}){let t=new URLSearchParams;e.mid&&t.set("mid",e.mid),e.domainId&&t.set("domainId",e.domainId),e.contextId&&t.set("contextId",e.contextId),e.periodStart&&t.set("periodStart",e.periodStart.toString()),e.periodEnd&&t.set("periodEnd",e.periodEnd.toString()),e.taskId&&t.set("taskId",e.taskId),e.limit&&t.set("limit",e.limit.toString()),e.offset&&t.set("offset",e.offset.toString());let s=t.toString(),r=`${this.pointsUrl}/history${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new o("bad_request:api",`Failed to get history: ${n.statusText}`);return n.json()}};function W(a={}){return new T(a)}var le=W();var J="/api/v2",x=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${J}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let c=await n.json().catch(()=>({})),p=n.status===404?"not_found":n.status===401?"unauthorized":"bad_request";throw new o(`${p}:api`,c.error?.message||c.error||`Request failed: ${n.statusText}`)}let i=await n.json();return i&&typeof i=="object"&&"data"in i?i.data:i}async createStack(e){return this.request("POST","/stacks",e)}async listStacks(){return this.request("GET","/stacks")}async getStack(e){return this.request("GET",`/stacks/${e}`)}async updateStack(e,t){return this.request("PATCH",`/stacks/${e}`,t)}async deleteStack(e){return this.request("DELETE",`/stacks/${e}`)}async configureOAuthProvider(e,t,s){return this.request("POST",`/stacks/${e}/oauth/${t}`,s)}async removeOAuthProvider(e,t){return this.request("DELETE",`/stacks/${e}/oauth/${t}`)}async configureWeb3Provider(e,t,s){return this.request("POST",`/stacks/${e}/web3/${t}`,s)}async removeWeb3Provider(e,t){return this.request("DELETE",`/stacks/${e}/web3/${t}`)}async configureStripeProvider(e,t){return this.request("POST",`/stacks/${e}/stripe`,t)}async getStripeProvider(e){return this.request("GET",`/stacks/${e}/stripe`)}async removeStripeProvider(e){return this.request("DELETE",`/stacks/${e}/stripe`)}async createPaymentIntent(e,t,s){return this.request("POST",`/stacks/${e}/stripe/payment-intent`,{amountCents:t,metadata:s})}async createKey(e,t,s){return this.request("POST",`/stacks/${e}/keys`,{name:t,permission:s})}async listKeys(e){return this.request("GET",`/stacks/${e}/keys`)}async revokeKey(e,t){return this.request("DELETE",`/stacks/${e}/keys/${t}`)}async getAllowlist(e){return this.request("GET",`/stacks/${e}/auth/allowlist`)}async updateAllowlist(e,t){return this.request("PUT",`/stacks/${e}/auth/allowlist`,t)}async updateCapabilities(e,t){return this.request("PATCH",`/stacks/${e}`,{capabilityBitmask:t})}async getModelLayers(e){return this.request("GET",`/stacks/${e}/model-layers`)}async updateModelAlias(e,t,s,r){return this.request("PATCH",`/stacks/${e}/model-layers`,{layer:t,capability:s,alias:r})}async resetModelAlias(e,t,s){return this.request("DELETE",`/stacks/${e}/model-layers/${t}/${s}`)}async uploadLogo(e,t){let s=`${this.baseUrl}${J}/stacks/${e}/logo`,r=new FormData;r.append("logo",t);let n={};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);let i=await fetch(s,{method:"POST",headers:n,body:r});if(!i.ok){let p=await i.json().catch(()=>({}));throw new o("bad_request:api",p.error?.message||`Failed to upload logo: ${i.statusText}`)}let c=await i.json();return c&&typeof c=="object"&&"data"in c?c.data:c}async deleteLogo(e){return this.request("DELETE",`/stacks/${e}/logo`)}async getMemberStats(e){return this.request("GET",`/stacks/${e}/members/stats`)}async getMembers(e,t){let s=new URLSearchParams;t?.limit&&s.set("limit",String(t.limit)),t?.offset&&s.set("offset",String(t.offset)),t?.role&&s.set("role",t.role);let r=s.toString()?`?${s}`:"";return this.request("GET",`/stacks/${e}/members${r}`)}async updateMemberRole(e,t,s){return this.request("PATCH",`/stacks/${e}/members/${encodeURIComponent(t)}/role`,{role:s})}async getUsageRecords(e,t){let s=new URLSearchParams;t?.page&&s.set("page",String(t.page)),t?.limit&&s.set("limit",String(t.limit)),t?.days&&s.set("days",String(t.days)),t?.model&&s.set("model",t.model);let r=s.toString()?`?${s}`:"";return this.request("GET",`/stacks/${e}/usage/records${r}`)}};function G(a={}){return new x(a)}var ce=G();var U="/api/v2",R=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async request(e,t){let s=await fetch(t,{method:e,headers:this.headers});if(!s.ok){let n=await s.json().catch(()=>({}));throw new o("bad_request:api",n.error?.message||`Request failed: ${s.statusText}`)}let r=await s.json();return r&&typeof r=="object"&&"data"in r?r.data:r}async checkHealth(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNetworkStatus(){return this.request("GET",`${this.baseUrl}${U}/network/status`)}async getMPCNodes(){return this.request("GET",`${this.baseUrl}${U}/network/nodes`)}async getNodeHealth(e){return this.request("GET",`${this.baseUrl}${U}/network/nodes/${e}/health`)}async getConsensusStatus(){return this.request("GET",`${this.baseUrl}/consensus/status`)}async getLeaderStatus(){return this.request("GET",`${this.baseUrl}/consensus/leader`)}async getAuthMetrics(e){let t=e?`/stacks/${e}/metrics`:"/metrics";return this.request("GET",`${this.baseUrl}${U}${t}`)}};function H(a={}){return new R(a)}var ue=H();var pe="/api/v2",_=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${pe}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let c=await n.json().catch(()=>({}));throw new o(n.status===402?"payment_required:api":"bad_request:api",c.error?.message||`Request failed: ${n.statusText}`)}let i=await n.json();return i&&typeof i=="object"&&"data"in i?i.data:i}async getPlans(e){return this.request("GET",`/stacks/${e}/billing/plans`)}async getBillingState(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing`)}async createCheckoutSession(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/checkout`,{identity_id:t,plan_id:s,success_url:r,cancel_url:n})}async createBillingPortal(e,t,s){return this.request("POST",`/stacks/${e}/billing/portal`,{identity_id:t,return_url:s})}async recordUsage(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/usage`,{identity_id:t,usage_type:s,quantity:r,idempotency_key:n})}async getCurrentUsage(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/usage`)}async linkStripeCustomer(e,t,s,r){return this.request("POST",`/stacks/${e}/billing/link`,{identity_id:t,stripe_customer_id:s,checkout_session_id:r})}async hasPaymentMethod(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/payment-method`)}};function z(a={}){return new _(a)}var de=z();
4
- exports.AgentsClient=S;exports.BillingClient=_;exports.FilesClient=P;exports.MCPClient=w;exports.MagmaClient=y;exports.NetworkClient=R;exports.PointsClient=T;exports.SkillsClient=$;exports.SocialClient=k;exports.StackManagementClient=x;exports.TaskNetworkClient=f;exports.UserClient=b;exports.WidgetsClient=C;exports.agentsClient=re;exports.billingClient=de;exports.createAgentsClient=L;exports.createBillingClient=z;exports.createFilesClient=K;exports.createMCPClient=I;exports.createMagmaClient=O;exports.createNetworkClient=H;exports.createPointsClient=W;exports.createSkillsClient=B;exports.createSocialClient=j;exports.createStackManagementClient=G;exports.createTaskNetworkClient=q;exports.createUserClient=N;exports.createWidgetsClient=D;exports.filesClient=ie;exports.magmaClient=X;exports.mcpClient=Q;exports.networkClient=ue;exports.pointsClient=le;exports.skillsClient=ae;exports.socialClient=se;exports.stackManagementClient=ce;exports.taskNetworkClient=V;exports.userClient=oe;exports.widgetsClient=ne;
1
+ 'use strict';var d="https://stacknet.magma-rpc.com",u=d;var h="http://geoff.magma-rpc.com";var l={"Content-Type":"application/json"};var f=class{baseUrl;apiKey;timeout;constructor(e={}){this.baseUrl=(e.baseUrl||u).replace(/\/$/,""),this.apiKey=e.apiKey,this.timeout=e.timeout||6e4;}async*chatCompletions(e){let t=e.messages.filter(n=>n.role==="user"),s=t[t.length-1]?.content||"",r=await this.submitTask({type:"ai-prompt",model:e.model,prompt:s,sessionId:e.sessionId,temperature:e.temperature,maxTokens:e.max_tokens,stream:true});yield*this.streamTaskResults(r,e.model);}async submitTask(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Task submission failed: ${n}`)}let s=await t.json(),r=s.taskId||s.id;if(!r)throw new Error("Task submission did not return a taskId");return r}async submitTaskFull(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let r=await t.text();throw new Error(`Task submission failed: ${r}`)}let s=await t.json();return {taskId:s.taskId||s.id,output:s.output,status:s.status}}async getTask(e){let t=await fetch(`${this.baseUrl}/tasks/${e}`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Failed to get task: ${t.statusText}`);return t.json()}async*streamTaskResults(e,t){let s=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!s.ok)throw new Error(`Stream failed: ${s.statusText}`);if(!s.body)throw new Error("Response body is null");let r=s.body.getReader(),n=new TextDecoder,o="",c="",p=Math.floor(Date.now()/1e3);try{for(;;){let{done:g,value:Y}=await r.read();if(g){yield {id:e,object:"chat.completion.chunk",created:p,model:t,choices:[{index:0,delta:{},finish_reason:"stop"}]};break}o+=n.decode(Y,{stream:!0});let A=o.split(`
2
+ `);o=A.pop()||"";for(let v of A)if(v.startsWith("data: "))try{let E=JSON.parse(v.slice(6));if(Array.isArray(E)&&E.length>0){let m=E[0].result||"";if(m&&m!==c){let q=m.substring(c.length);c=m,q&&(yield {id:e,object:"chat.completion.chunk",created:p,model:t,choices:[{index:0,delta:{role:"assistant",content:q},finish_reason:null}]});}}}catch{}}}finally{r.releaseLock();}}async*streamTaskRaw(e){let t=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Stream failed: ${t.statusText}`);if(!t.body)throw new Error("Response body is null");let s=t.body.getReader(),r=new TextDecoder,n="";try{for(;;){let{done:o,value:c}=await s.read();if(o)break;n+=r.decode(c,{stream:!0});let p=n.split(`
3
+ `);n=p.pop()||"";for(let g of p)if(g.startsWith("data: "))try{yield JSON.parse(g.slice(6));}catch{}}}finally{s.releaseLock();}}async healthCheck(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNode(){let e=await fetch(`${this.baseUrl}/node`);if(!e.ok)throw new Error(`Failed to get node info: ${e.statusText}`);return e.json()}};function F(a){return new f(a)}var V=F();async function O(a){let e=await crypto.subtle.digest("SHA-256",a);return `baf${Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,52)}`}var y=class{baseUrl;localServerUrl;constructor(e={}){this.baseUrl=e.baseUrl||h,this.localServerUrl=e.localServerUrl||u;}async uploadFile(e){let t=await e.arrayBuffer(),s=await O(t),r=this.arrayBufferToBase64(t);return typeof localStorage<"u"&&localStorage.setItem(`file:${s}`,JSON.stringify({cid:s,name:e.name,type:e.type,size:e.size,data:r})),{cid:s,name:e.name,size:e.size,type:e.type,url:`data:${e.type};base64,${r}`}}async uploadText(e,t){let s=new Blob([e],{type:"text/plain"}),r=new File([s],t,{type:"text/plain"});return this.uploadFile(r)}async storeImagination(e){let t=e.createdBy||"anonymous",r=(await fetch(`${this.localServerUrl}/imaginations/${e.id}`)).ok,n={id:e.id,title:e.title,sources:e.sources,summary:e.summary,character:e.character,workflow:e.workflow,is_public:e.is_public||false,creator_mid:t};if(r){let o=await fetch(`${this.localServerUrl}/imaginations/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to update imagination: ${o.statusText}`);return typeof localStorage<"u"&&localStorage.setItem(`imagination:${e.id}`,e.id),e.id}else {let o=await fetch(`${this.localServerUrl}/imaginations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to store imagination: ${o.statusText}`);let p=(await o.json()).imagination?.id||e.id;return typeof localStorage<"u"&&localStorage.setItem(`imagination:${p}`,p),p}}async getImagination(e){try{let t=await fetch(`${this.localServerUrl}/imaginations/${e}`);if(!t.ok)return null;let s=await t.json();return s.imagination?{id:s.imagination.id,title:s.imagination.title,createdAt:new Date(s.imagination.created_at).toISOString(),createdBy:s.imagination.creator_mid,sources:s.imagination.sources,summary:s.imagination.summary,character:s.imagination.character,workflow:s.imagination.workflow,is_public:s.imagination.is_public}:null}catch(t){return console.error("Failed to retrieve imagination:",t),null}}async getImaginationByCID(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);if(!t.ok)return null;let s=await t.json();return typeof localStorage<"u"&&localStorage.setItem(`imagination:${s.id}`,e),s}catch(t){return console.error("Failed to retrieve imagination by CID:",t),null}}async listImaginations(e){try{let t=e||"anonymous",s=await fetch(`${this.localServerUrl}/imaginations?creator_mid=${encodeURIComponent(t)}`);if(!s.ok)return console.warn("Failed to fetch imaginations from P2P, falling back to localStorage"),this.listImaginationsFromLocalStorage();let n=(await s.json()).imaginations.map(o=>({id:o.id,title:o.title,createdAt:new Date(o.created_at).toISOString(),createdBy:o.creator_mid,sources:o.sources,summary:o.summary,character:o.character,workflow:o.workflow,is_public:o.is_public}));return typeof localStorage<"u"&&n.forEach(o=>{localStorage.setItem(`imagination:${o.id}`,o.id);}),n}catch(t){return console.error("Failed to list imaginations:",t),this.listImaginationsFromLocalStorage()}}async listImaginationsFromLocalStorage(){if(typeof localStorage>"u")return [];let e=[];for(let t=0;t<localStorage.length;t++){let s=localStorage.key(t);if(s&&s.startsWith("imagination:")){let r=s.replace("imagination:",""),n=await this.getImagination(r);n&&e.push(n);}}return e}async getFile(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);return t.ok?await t.blob():null}catch(t){return console.error("Failed to retrieve file:",t),null}}arrayBufferToBase64(e){let t=new Uint8Array(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}};function M(a){return new y(a)}var X=M();var w=class{baseUrl;timeout;sessions=new Map;constructor(e={}){this.baseUrl=e.baseUrl||"http://localhost:3006",this.timeout=e.timeout||3e4;}async createSession(e="default"){let t=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;try{let s={id:t,agentId:e,status:"active",createdAt:new Date};this.sessions.set(t,s);try{await fetch(`${this.baseUrl}/mcp/sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t,agentId:e,clientInfo:{name:"stacknet-sdk",version:"0.1.0"}})});}catch{}return s}catch(s){throw new Error(`Failed to create MCP session: ${s}`)}}getSession(e){return this.sessions.get(e)}async closeSession(e){let t=this.sessions.get(e);if(t){t.status="closed";try{await fetch(`${this.baseUrl}/mcp/sessions/${e}`,{method:"DELETE"});}catch{}this.sessions.delete(e);}}async sendMessage(e,t){let s=this.sessions.get(e);if(!s||s.status!=="active")throw new Error("Invalid or inactive session");try{let r=await fetch(`${this.baseUrl}/mcp/sessions/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:[{role:"user",content:{type:"text",text:t}}]})});if(!r.ok)throw new Error(`MCP request failed: ${r.statusText}`);return r.json()}catch(r){throw new Error(`Failed to send message: ${r}`)}}async callTool(e,t,s={}){let r=this.sessions.get(e);if(!r||r.status!=="active")throw new Error("Invalid or inactive session");try{let n=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok)throw new Error(`Tool call failed: ${n.statusText}`);return n.json()}catch(n){throw new Error(`Failed to call tool: ${n}`)}}async listTools(e){let t=this.sessions.get(e);if(!t||t.status!=="active")throw new Error("Invalid or inactive session");try{let s=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools`);return s.ok?(await s.json()).tools||[]:[]}catch{return []}}getActiveSessions(){return Array.from(this.sessions.values()).filter(e=>e.status==="active")}async closeAllSessions(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(t=>this.closeSession(t)));}};function I(a){return new w(a)}var Q=I();var Z={database:"log",chat:"response",auth:"response",stream:"response",api:"response",history:"response",vote:"response",document:"response",suggestions:"response",task:"response",agent:"response",imagination:"response"},i=class extends Error{type;surface;statusCode;constructor(e,t){super();let[s,r]=e.split(":");this.type=s,this.cause=t,this.surface=r,this.message=ee(e),this.statusCode=te(this.type);}toJSON(){return {code:`${this.type}:${this.surface}`,message:this.message,cause:this.cause,statusCode:this.statusCode}}toResponse(){let e=`${this.type}:${this.surface}`,t=Z[this.surface],{message:s,cause:r,statusCode:n}=this;return t==="log"?(console.error({code:e,message:s,cause:r}),Response.json({code:"",message:"Something went wrong. Please try again later."},{status:n})):Response.json({code:e,message:s,cause:r},{status:n})}};function ee(a){if(a.includes("database"))return "An error occurred while executing a database query.";switch(a){case "bad_request:api":return "The request couldn't be processed. Please check your input and try again.";case "unauthorized:auth":return "You need to sign in before continuing.";case "unauthorized:api":return "Your session has expired. Please sign in again.";case "forbidden:auth":return "Your account does not have access to this feature.";case "rate_limit:chat":return "You have exceeded your maximum number of messages for the day. Please try again later.";case "not_found:chat":return "The requested chat was not found.";case "forbidden:chat":return "This chat belongs to another user.";case "unauthorized:chat":return "You need to sign in to view this chat.";case "offline:chat":return "We're having trouble sending your message. Please check your internet connection.";case "not_found:task":return "The requested task was not found.";case "forbidden:task":return "You do not have access to this task.";case "not_found:agent":return "The requested agent was not found.";case "forbidden:agent":return "You do not have access to this agent.";case "not_found:imagination":return "The requested imagination was not found.";case "forbidden:imagination":return "You do not have access to this imagination.";case "not_found:document":return "The requested document was not found.";case "forbidden:document":return "This document belongs to another user.";case "unauthorized:document":return "You need to sign in to view this document.";case "bad_request:document":return "The request to create or update the document was invalid.";default:return "Something went wrong. Please try again later."}}function te(a){switch(a){case "bad_request":return 400;case "unauthorized":return 401;case "payment_required":return 402;case "forbidden":return 403;case "not_found":return 404;case "rate_limit":return 429;case "offline":return 503;case "internal":return 500;default:return 500}}var k=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get socialUrl(){return `${this.baseUrl}/social`}async getFeed(e={}){let{page:t=1,limit:s=10,mediaType:r}=e,n=new URLSearchParams({page:String(t),limit:String(s)});r&&n.set("media_type",r);let o=await fetch(`${this.socialUrl}/feed?${n}`);if(!o.ok)throw new i("bad_request:api",`Failed to fetch feed: ${o.statusText}`);return o.json()}async getPost(e){let t=await fetch(`${this.socialUrl}/posts/${e}`);if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to fetch post: ${t.statusText}`);return t.json()}async getComments(e){let t=await fetch(`${this.socialUrl}/posts/${e}/comments`);if(!t.ok)throw new i("bad_request:api",`Failed to fetch comments: ${t.statusText}`);return t.json()}async getRemixes(e){let t=await fetch(`${this.socialUrl}/posts/${e}/remixes`);if(!t.ok)throw new i("bad_request:api",`Failed to fetch remixes: ${t.statusText}`);return t.json()}async checkLike(e,t){let s=await fetch(`${this.socialUrl}/posts/${e}/likes/check?userMid=${encodeURIComponent(t)}`);if(!s.ok)throw new i("bad_request:api",`Failed to check like status: ${s.statusText}`);return s.json()}async likePost(e,t){let s=await fetch(`${this.socialUrl}/like`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new i("bad_request:api",`Failed to like post: ${s.statusText}`);return s.json()}async unlikePost(e,t){let s=await fetch(`${this.socialUrl}/unlike`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new i("bad_request:api",`Failed to unlike post: ${s.statusText}`);return s.json()}async addComment(e,t,s){let r=await fetch(`${this.socialUrl}/comment`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t,content:s})});if(!r.ok)throw new i("bad_request:api",`Failed to add comment: ${r.statusText}`);return r.json()}async createPost(e){let t=await fetch(`${this.socialUrl}/post`,{method:"POST",headers:l,body:JSON.stringify({userMid:e.creatorMid,content:e.content,mediaUrl:e.mediaUrl,mediaType:e.mediaType,orientation:e.orientation,posterUrl:e.posterUrl,remixOf:e.remixOf})});if(!t.ok)throw new i("bad_request:api",`Failed to create post: ${t.statusText}`);return t.json()}async trackView(e,t){await fetch(`${this.socialUrl}/posts/${e}/view`,{method:"POST",headers:l,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:l,body:JSON.stringify({userMid:t})}).catch(()=>{});}async getProfile(e){try{let t=await fetch(`${this.socialUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new i("bad_request:api",`Failed to fetch profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof i)throw t;return null}}};function j(a={}){return new k(a)}var se=j();var S=class{baseUrl;useCpxApi;authToken;constructor(e={}){this.baseUrl=e.baseUrl||u,this.useCpxApi=e.useCpxApi!==false,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}get agentsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/agents`:`${this.baseUrl}/agents`}async list(e={}){let t=new URLSearchParams;e.userMid&&t.set("userMid",e.userMid);let s=t.toString(),r=`${this.agentsUrl}${s?`?${s}`:""}`,n=await fetch(r,{headers:this.headers});if(!n.ok)throw new i("bad_request:api",`Failed to list agents: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.agentsUrl}/${e}`,{headers:this.headers});if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to get agent: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.agentsUrl,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create agent: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.agentsUrl}/${e}`,{method:"PUT",headers:this.headers,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update agent: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.agentsUrl}/${e}`,{method:"DELETE",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to delete agent: ${t.statusText}`);return t.json()}async enable(e){let t=await fetch(`${this.agentsUrl}/${e}/enable`,{method:"POST",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to enable agent: ${t.statusText}`);return t.json()}async disable(e){let t=await fetch(`${this.agentsUrl}/${e}/disable`,{method:"POST",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to disable agent: ${t.statusText}`);return t.json()}async execute(e,t={}){let s=await fetch(`${this.agentsUrl}/${e}/execute`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!s.ok)throw new i("bad_request:api",`Failed to execute agent: ${s.statusText}`);return s.json()}async createFromPrompt(e){let t=await fetch(`${this.agentsUrl}/from-prompt`,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok)throw new i("bad_request:api",`Failed to generate agent from prompt: ${t.statusText}`);let s=await t.json();return this.create({...s,created_by:e.created_by})}};function L(a={}){return new S(a)}var re=L();var b=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get widgetsUrl(){return `${this.baseUrl}/widgets`}async list(e={}){let t=new URLSearchParams;e.creatorMid?t.set("creator_mid",e.creatorMid):e.scope&&t.set("scope",e.scope);let s=t.toString(),r=`${this.widgetsUrl}${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to list widgets: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.widgetsUrl}/${e}`);if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to get widget: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.widgetsUrl,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create widget: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.widgetsUrl}/${e}`,{method:"PUT",headers:l,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update widget: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.widgetsUrl}/${e}`,{method:"DELETE"});if(!t.ok)throw new i("bad_request:api",`Failed to delete widget: ${t.statusText}`);return t.json()}async getSystemPrompt(){let e=await fetch(`${this.widgetsUrl}/system-prompt`);if(!e.ok)throw new i("bad_request:api",`Failed to get widget system prompt: ${e.statusText}`);return e.json()}async trackUsage(e){await fetch(`${this.widgetsUrl}/${e}/usage`,{method:"POST"}).catch(()=>{});}};function D(a={}){return new b(a)}var ne=D();var C=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get userUrl(){return `${this.baseUrl}/user`}async getProfile(e){try{let t=await fetch(`${this.userUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new i("bad_request:api",`Failed to get user profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof i)throw t;return null}}async updateProfile(e,t){let s=await fetch(`${this.userUrl}/profile/${e}`,{method:"PUT",headers:l,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update user profile: ${s.statusText}`)}return s.json()}};function N(a={}){return new C(a)}var ie=N();var P=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get filesUrl(){return `${this.baseUrl}/files`}async upload(e,t){let s=new FormData;s.append("file",e,t);let r=await fetch(`${this.filesUrl}/upload`,{method:"POST",body:s});if(!r.ok)throw new i("bad_request:api",`Failed to upload file: ${r.statusText}`);return r.json()}async uploadFromUrl(e){let t=await fetch(`${this.filesUrl}/upload-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})});if(!t.ok)throw new i("bad_request:api",`Failed to upload file from URL: ${t.statusText}`);return t.json()}getFileUrl(e){return `${this.filesUrl}/${e}`}};function K(a={}){return new P(a)}var oe=K();var $=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||h,this.useCpxApi=e.useCpxApi!==false;}get skillsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/skills`:`${this.baseUrl}/skills`}async list(e){let t=new URLSearchParams;e?.precompiled?(t.set("precompiled","true"),e?.contentType&&t.set("content_type",e.contentType)):e?.contentType?t.set("content_type",e.contentType):e?.creatorMid?t.set("creator_mid",e.creatorMid):e?.scope&&e.scope!=="all"&&t.set("scope",e.scope);let s=t.toString()?`${this.skillsUrl}?${t.toString()}`:this.skillsUrl,r=await fetch(s);if(!r.ok)throw new Error(`Failed to list skills: ${r.statusText}`);return r.json()}async get(e){let t=await fetch(`${this.skillsUrl}/${e}`);if(!t.ok)throw new Error(`Skill not found: ${e}`);return t.json()}async create(e){let t=await fetch(this.skillsUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to create skill: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.skillsUrl}/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new Error(r.error||`Failed to update skill: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.skillsUrl}/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to delete skill: ${t.statusText}`)}return t.json()}async trackUsage(e){try{await fetch(`${this.skillsUrl}/${e}/usage`,{method:"POST"});}catch{}}async verify(e){let t=await fetch(`${this.skillsUrl}/${e}/verify`);if(!t.ok)throw new Error(`Failed to verify skill: ${t.statusText}`);return t.json()}async rehash(e){let t=await fetch(`${this.skillsUrl}/${e}/rehash`,{method:"POST"});if(!t.ok)throw new Error(`Failed to rehash skill: ${t.statusText}`);return t.json()}async rehashAll(){let e=await fetch(`${this.skillsUrl}/rehash-all`,{method:"POST"});if(!e.ok)throw new Error(`Failed to rehash all skills: ${e.statusText}`);return e.json()}async getMap(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map${t}`);if(!s.ok)throw new Error(`Failed to get skill map: ${s.statusText}`);return s.json()}async getMapPrompt(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map/prompt${t}`);if(!s.ok)throw new Error(`Failed to get skill map prompt: ${s.statusText}`);return s.json()}async getNonCodeMap(){let e=await fetch(`${this.skillsUrl}/map/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill map: ${e.statusText}`);return e.json()}async getNonCodeSummary(){let e=await fetch(`${this.skillsUrl}/summary/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill summary: ${e.statusText}`);return e.json()}};function B(a){return new $(a)}var ae=B();var T=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}get pointsUrl(){return `${this.baseUrl}/cpx/points`}async initNetworkDomain(){let e=await fetch(`${this.pointsUrl}/init`,{method:"POST",headers:l});if(!e.ok){let t=await e.json().catch(()=>({}));throw new i("bad_request:api",t.error||`Failed to initialize network domain: ${e.statusText}`)}return e.json()}async listDomains(){let e=await fetch(`${this.pointsUrl}/domains`);if(!e.ok)throw new i("bad_request:api",`Failed to list domains: ${e.statusText}`);return e.json()}async getDomain(e){let t=await fetch(`${this.pointsUrl}/domains/${e}`);if(t.status===404)return null;if(!t.ok)throw new i("bad_request:api",`Failed to get domain: ${t.statusText}`);return t.json()}async createDomain(e){let t=await fetch(`${this.pointsUrl}/domains`,{method:"POST",headers:l,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new i("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create domain: ${t.statusText}`)}return t.json()}async listContexts(e){let t=e?`?domainId=${e}`:"",s=await fetch(`${this.pointsUrl}/contexts${t}`);if(!s.ok)throw new i("bad_request:api",`Failed to list contexts: ${s.statusText}`);return s.json()}async getContext(e){let t=await fetch(`${this.pointsUrl}/contexts/${e}`);if(t.status===404)return null;if(!t.ok)throw new i("bad_request:api",`Failed to get context: ${t.statusText}`);return t.json()}async createContext(e){let t=await fetch(`${this.pointsUrl}/contexts`,{method:"POST",headers:l,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new i("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create context: ${t.statusText}`)}return t.json()}async listDelegations(e={}){let t=new URLSearchParams;e.domainId&&t.set("domainId",e.domainId),e.delegator&&t.set("delegator",e.delegator),e.delegate&&t.set("delegate",e.delegate),e.activeOnly&&t.set("activeOnly","true");let s=t.toString(),r=`${this.pointsUrl}/delegations${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to list delegations: ${n.statusText}`);return n.json()}async createDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create delegation: ${t.statusText}`)}return t.json()}async revokeDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to revoke delegation: ${t.statusText}`)}return t.json()}async addPoints(e){let t=await fetch(`${this.pointsUrl}/add`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to add points: ${t.statusText}`)}return t.json()}async spendPoints(e){let t=await fetch(`${this.pointsUrl}/spend`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to spend points: ${t.statusText}`)}return t.json()}async getBalance(e,t={}){let s=new URLSearchParams;t.domainId&&s.set("domainId",t.domainId),t.contextId&&s.set("contextId",t.contextId);let r=s.toString(),n=`${this.pointsUrl}/balance/${e}${r?`?${r}`:""}`,o=await fetch(n);if(!o.ok)throw new i("bad_request:api",`Failed to get balance: ${o.statusText}`);return o.json()}async getHistory(e={}){let t=new URLSearchParams;e.mid&&t.set("mid",e.mid),e.domainId&&t.set("domainId",e.domainId),e.contextId&&t.set("contextId",e.contextId),e.periodStart&&t.set("periodStart",e.periodStart.toString()),e.periodEnd&&t.set("periodEnd",e.periodEnd.toString()),e.taskId&&t.set("taskId",e.taskId),e.limit&&t.set("limit",e.limit.toString()),e.offset&&t.set("offset",e.offset.toString());let s=t.toString(),r=`${this.pointsUrl}/history${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to get history: ${n.statusText}`);return n.json()}};function W(a={}){return new T(a)}var le=W();var J="/api/v2",x=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${J}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let c=await n.json().catch(()=>({})),p=n.status===404?"not_found":n.status===401?"unauthorized":"bad_request";throw new i(`${p}:api`,c.error?.message||c.error||`Request failed: ${n.statusText}`)}let o=await n.json();return o&&typeof o=="object"&&"data"in o?o.data:o}async createStack(e){return this.request("POST","/stacks",e)}async listStacks(){return this.request("GET","/stacks")}async getStack(e){return this.request("GET",`/stacks/${e}`)}async updateStack(e,t){return this.request("PATCH",`/stacks/${e}`,t)}async deleteStack(e){return this.request("DELETE",`/stacks/${e}`)}async configureOAuthProvider(e,t,s){return this.request("POST",`/stacks/${e}/oauth/${t}`,s)}async removeOAuthProvider(e,t){return this.request("DELETE",`/stacks/${e}/oauth/${t}`)}async configureWeb3Provider(e,t,s){return this.request("POST",`/stacks/${e}/web3/${t}`,s)}async removeWeb3Provider(e,t){return this.request("DELETE",`/stacks/${e}/web3/${t}`)}async configureStripeProvider(e,t){return this.request("POST",`/stacks/${e}/stripe`,t)}async getStripeProvider(e){return this.request("GET",`/stacks/${e}/stripe`)}async removeStripeProvider(e){return this.request("DELETE",`/stacks/${e}/stripe`)}async createPaymentIntent(e,t,s){return this.request("POST",`/stacks/${e}/stripe/payment-intent`,{amountCents:t,metadata:s})}async createKey(e,t,s){return this.request("POST",`/stacks/${e}/keys`,{name:t,permission:s})}async listKeys(e){return this.request("GET",`/stacks/${e}/keys`)}async revokeKey(e,t){return this.request("DELETE",`/stacks/${e}/keys/${t}`)}async getAllowlist(e){return this.request("GET",`/stacks/${e}/auth/allowlist`)}async updateAllowlist(e,t){return this.request("PUT",`/stacks/${e}/auth/allowlist`,t)}async updateCapabilities(e,t){return this.request("PATCH",`/stacks/${e}`,{capabilityBitmask:t})}async getModelLayers(e){return this.request("GET",`/stacks/${e}/model-layers`)}async updateModelAlias(e,t,s,r){return this.request("PATCH",`/stacks/${e}/model-layers`,{layer:t,capability:s,alias:r})}async resetModelAlias(e,t,s){return this.request("DELETE",`/stacks/${e}/model-layers/${t}/${s}`)}async uploadLogo(e,t){let s=`${this.baseUrl}${J}/stacks/${e}/logo`,r=new FormData;r.append("logo",t);let n={};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);let o=await fetch(s,{method:"POST",headers:n,body:r});if(!o.ok){let p=await o.json().catch(()=>({}));throw new i("bad_request:api",p.error?.message||`Failed to upload logo: ${o.statusText}`)}let c=await o.json();return c&&typeof c=="object"&&"data"in c?c.data:c}async deleteLogo(e){return this.request("DELETE",`/stacks/${e}/logo`)}async getMemberStats(e){return this.request("GET",`/stacks/${e}/members/stats`)}async getMembers(e,t){let s=new URLSearchParams;t?.limit&&s.set("limit",String(t.limit)),t?.offset&&s.set("offset",String(t.offset)),t?.role&&s.set("role",t.role);let r=s.toString()?`?${s}`:"";return this.request("GET",`/stacks/${e}/members${r}`)}async updateMemberRole(e,t,s){return this.request("PATCH",`/stacks/${e}/members/${encodeURIComponent(t)}/role`,{role:s})}async getUsageRecords(e,t){let s=new URLSearchParams;t?.page&&s.set("page",String(t.page)),t?.limit&&s.set("limit",String(t.limit)),t?.days&&s.set("days",String(t.days)),t?.model&&s.set("model",t.model);let r=s.toString()?`?${s}`:"";return this.request("GET",`/stacks/${e}/usage/records${r}`)}};function G(a={}){return new x(a)}var ce=G();var U="/api/v2",R=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async request(e,t){let s=await fetch(t,{method:e,headers:this.headers});if(!s.ok){let n=await s.json().catch(()=>({}));throw new i("bad_request:api",n.error?.message||`Request failed: ${s.statusText}`)}let r=await s.json();return r&&typeof r=="object"&&"data"in r?r.data:r}async checkHealth(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNetworkStatus(){return this.request("GET",`${this.baseUrl}${U}/network/status`)}async getMPCNodes(){return this.request("GET",`${this.baseUrl}${U}/network/nodes`)}async getNodeHealth(e){return this.request("GET",`${this.baseUrl}${U}/network/nodes/${e}/health`)}async getConsensusStatus(){return this.request("GET",`${this.baseUrl}/consensus/status`)}async getLeaderStatus(){return this.request("GET",`${this.baseUrl}/consensus/leader`)}async getAuthMetrics(e){let t=e?`/stacks/${e}/metrics`:"/metrics";return this.request("GET",`${this.baseUrl}${U}${t}`)}};function H(a={}){return new R(a)}var ue=H();var pe="/api/v2",_=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${pe}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let c=await n.json().catch(()=>({}));throw new i(n.status===402?"payment_required:api":"bad_request:api",c.error?.message||`Request failed: ${n.statusText}`)}let o=await n.json();return o&&typeof o=="object"&&"data"in o?o.data:o}async getPlans(e){return this.request("GET",`/stacks/${e}/billing/plans`)}async getBillingState(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing`)}async createCheckoutSession(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/checkout`,{identity_id:t,plan_id:s,success_url:r,cancel_url:n})}async createBillingPortal(e,t,s){return this.request("POST",`/stacks/${e}/billing/portal`,{identity_id:t,return_url:s})}async recordUsage(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/usage`,{identity_id:t,usage_type:s,quantity:r,idempotency_key:n})}async getCurrentUsage(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/usage`)}async linkStripeCustomer(e,t,s,r){return this.request("POST",`/stacks/${e}/billing/link`,{identity_id:t,stripe_customer_id:s,checkout_session_id:r})}async hasPaymentMethod(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/payment-method`)}async subscribeSol(e,t,s){return this.request("POST",`/stacks/${e}/subscribe-sol`,{planId:t,txSignature:s})}async prepaidSol(e,t,s,r){return this.request("POST",`/stacks/${e}/prepaid-sol`,{amountCents:t,txSignature:s,scope:r})}async topup(e,t,s){return this.request("POST","/account/topup",{amount_cents:e,payment_method:t,payment_ref:s})}};function z(a={}){return new _(a)}var de=z();
4
+ exports.AgentsClient=S;exports.BillingClient=_;exports.FilesClient=P;exports.MCPClient=w;exports.MagmaClient=y;exports.NetworkClient=R;exports.PointsClient=T;exports.SkillsClient=$;exports.SocialClient=k;exports.StackManagementClient=x;exports.TaskNetworkClient=f;exports.UserClient=C;exports.WidgetsClient=b;exports.agentsClient=re;exports.billingClient=de;exports.createAgentsClient=L;exports.createBillingClient=z;exports.createFilesClient=K;exports.createMCPClient=I;exports.createMagmaClient=M;exports.createNetworkClient=H;exports.createPointsClient=W;exports.createSkillsClient=B;exports.createSocialClient=j;exports.createStackManagementClient=G;exports.createTaskNetworkClient=F;exports.createUserClient=N;exports.createWidgetsClient=D;exports.filesClient=oe;exports.magmaClient=X;exports.mcpClient=Q;exports.networkClient=ue;exports.pointsClient=le;exports.skillsClient=ae;exports.socialClient=se;exports.stackManagementClient=ce;exports.taskNetworkClient=V;exports.userClient=ie;exports.widgetsClient=ne;
@@ -1,4 +1,4 @@
1
- import { F as ChatCompletionRequest, E as ChatCompletionChunk, b6 as TaskPayload, ao as MagmaFile, ac as ImaginationMetadata, al as MCPSessionConfig, ak as MCPSession, am as MCPToolResult, aP as SocialClientConfig, ap as MediaType, a6 as FeedResponse, aF as PostResponse, I as CommentsResponse, aH as RemixesResponse, ag as LikeCheckResponse, ah as LikeResponse, H as CommentResponse, X as CreatePostInput, Y as CreatePostResponse, aG as ProfileResponse, p as AgentsClientConfig, q as AgentsListResponse, e as Agent, f as AgentCreateInput, j as AgentResponse, l as AgentUpdateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bh as WidgetUpdateInput, bg as WidgetSystemPromptResponse, b9 as UserClientConfig, ba as UserProfile, bc as UserProfileUpdateInput, bb as UserProfileResponse, a8 as FilesClientConfig, a7 as FileUploadResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aI as Skill, aJ as SkillCreateInput, aK as SkillResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, bo as SkillMapResponse, bp as SkillMapPromptResponse, bq as SkillSummaryResponse, aE as PointsClientConfig, ae as InitNetworkResponse, a5 as DomainsListResponse, O as ContextDomain, V as CreateDomainInput, a4 as DomainResponse, Q as ContextsListResponse, az as PointContext, S as CreateContextInput, P as ContextResponse, a0 as DelegationFilters, a3 as DelegationsListResponse, U as CreateDelegationInput, a1 as DelegationResponse, d as AddPointsInput, aB as PointRecordResponse, aU as SpendPointsInput, aD as PointSpendResponse, ay as PointBalance, a9 as HistoryFilters, aa as HistoryResponse, a_ as StackManagementClientConfig, Z as CreateStackRequest, b3 as StackResponse, aZ as StackListResponse, aW as StackConfig, J as ConfigureOAuthInput, b2 as StackOAuthProvider, L as ConfigureWeb3Input, b5 as StackWeb3Provider, K as ConfigureStripeInput, b4 as StackStripeProvider, W as CreateKeyResponse, aY as StackKeysListResponse, r as AllowlistConfig, t as AllowlistUpdateInput, at as ModelLayersResponse, b0 as StackMemberStats, a$ as StackMember, au as NetworkClientConfig, av as NetworkStatus, an as MPCNode, N as ConsensusStatus, af as LeaderStatus, u as AuthMetrics, B as BillingClientConfig, w as BillingPlansResponse, y as BillingState, R as CreateCheckoutSessionResponse, x as BillingPortalResponse } from '../billing-BaJlf_S8.cjs';
1
+ import { F as ChatCompletionRequest, E as ChatCompletionChunk, b6 as TaskPayload, ao as MagmaFile, ac as ImaginationMetadata, al as MCPSessionConfig, ak as MCPSession, am as MCPToolResult, aP as SocialClientConfig, ap as MediaType, a6 as FeedResponse, aF as PostResponse, I as CommentsResponse, aH as RemixesResponse, ag as LikeCheckResponse, ah as LikeResponse, H as CommentResponse, X as CreatePostInput, Y as CreatePostResponse, aG as ProfileResponse, p as AgentsClientConfig, q as AgentsListResponse, e as Agent, f as AgentCreateInput, j as AgentResponse, l as AgentUpdateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bh as WidgetUpdateInput, bg as WidgetSystemPromptResponse, b9 as UserClientConfig, ba as UserProfile, bc as UserProfileUpdateInput, bb as UserProfileResponse, a8 as FilesClientConfig, a7 as FileUploadResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aI as Skill, aJ as SkillCreateInput, aK as SkillResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, bo as SkillMapResponse, bp as SkillMapPromptResponse, bq as SkillSummaryResponse, aE as PointsClientConfig, ae as InitNetworkResponse, a5 as DomainsListResponse, O as ContextDomain, V as CreateDomainInput, a4 as DomainResponse, Q as ContextsListResponse, az as PointContext, S as CreateContextInput, P as ContextResponse, a0 as DelegationFilters, a3 as DelegationsListResponse, U as CreateDelegationInput, a1 as DelegationResponse, d as AddPointsInput, aB as PointRecordResponse, aU as SpendPointsInput, aD as PointSpendResponse, ay as PointBalance, a9 as HistoryFilters, aa as HistoryResponse, a_ as StackManagementClientConfig, Z as CreateStackRequest, b3 as StackResponse, aZ as StackListResponse, aW as StackConfig, J as ConfigureOAuthInput, b2 as StackOAuthProvider, L as ConfigureWeb3Input, b5 as StackWeb3Provider, K as ConfigureStripeInput, b4 as StackStripeProvider, W as CreateKeyResponse, aY as StackKeysListResponse, r as AllowlistConfig, t as AllowlistUpdateInput, at as ModelLayersResponse, b0 as StackMemberStats, a$ as StackMember, au as NetworkClientConfig, av as NetworkStatus, an as MPCNode, N as ConsensusStatus, af as LeaderStatus, u as AuthMetrics, B as BillingClientConfig, w as BillingPlansResponse, y as BillingState, R as CreateCheckoutSessionResponse, x as BillingPortalResponse } from '../billing-eQZIWeNW.cjs';
2
2
 
3
3
  /**
4
4
  * TaskNetworkClient - OpenAI-compatible SDK for StackNet
@@ -260,7 +260,10 @@ declare const socialClient: SocialClient;
260
260
  declare class AgentsClient {
261
261
  private baseUrl;
262
262
  private useCpxApi;
263
+ private authToken;
263
264
  constructor(config?: AgentsClientConfig);
265
+ setAuthToken(token: string | null): void;
266
+ private get headers();
264
267
  private get agentsUrl();
265
268
  /**
266
269
  * List all agents
@@ -739,6 +742,37 @@ declare class BillingClient {
739
742
  card_last_four?: string;
740
743
  card_brand?: string;
741
744
  }>;
745
+ /**
746
+ * Subscribe to a plan using SOL payment.
747
+ * Client must build and sign the SOL transaction first,
748
+ * then pass the on-chain tx signature here for verification.
749
+ */
750
+ subscribeSol(stackId: string, planId: string, txSignature: string): Promise<{
751
+ subscription: {
752
+ id: string;
753
+ planId: string;
754
+ planName: string;
755
+ status: string;
756
+ tokensGranted: number;
757
+ };
758
+ }>;
759
+ /**
760
+ * One-time prepaid credit via SOL payment.
761
+ */
762
+ prepaidSol(stackId: string, amountCents: number, txSignature: string, scope?: 'global' | 'stack'): Promise<{
763
+ alreadyCredited: boolean;
764
+ tokensCredited?: number;
765
+ amountCents?: number;
766
+ paymentRef?: string;
767
+ }>;
768
+ /**
769
+ * Top up account via x402 payment proof (SOL or Stripe).
770
+ */
771
+ topup(amountCents: number, paymentMethod: 'solana' | 'stripe', paymentRef: string): Promise<{
772
+ success: boolean;
773
+ tokensCredited: number;
774
+ tokenBalance: number;
775
+ }>;
742
776
  }
743
777
  /**
744
778
  * Create a BillingClient instance
@@ -1,4 +1,4 @@
1
- import { F as ChatCompletionRequest, E as ChatCompletionChunk, b6 as TaskPayload, ao as MagmaFile, ac as ImaginationMetadata, al as MCPSessionConfig, ak as MCPSession, am as MCPToolResult, aP as SocialClientConfig, ap as MediaType, a6 as FeedResponse, aF as PostResponse, I as CommentsResponse, aH as RemixesResponse, ag as LikeCheckResponse, ah as LikeResponse, H as CommentResponse, X as CreatePostInput, Y as CreatePostResponse, aG as ProfileResponse, p as AgentsClientConfig, q as AgentsListResponse, e as Agent, f as AgentCreateInput, j as AgentResponse, l as AgentUpdateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bh as WidgetUpdateInput, bg as WidgetSystemPromptResponse, b9 as UserClientConfig, ba as UserProfile, bc as UserProfileUpdateInput, bb as UserProfileResponse, a8 as FilesClientConfig, a7 as FileUploadResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aI as Skill, aJ as SkillCreateInput, aK as SkillResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, bo as SkillMapResponse, bp as SkillMapPromptResponse, bq as SkillSummaryResponse, aE as PointsClientConfig, ae as InitNetworkResponse, a5 as DomainsListResponse, O as ContextDomain, V as CreateDomainInput, a4 as DomainResponse, Q as ContextsListResponse, az as PointContext, S as CreateContextInput, P as ContextResponse, a0 as DelegationFilters, a3 as DelegationsListResponse, U as CreateDelegationInput, a1 as DelegationResponse, d as AddPointsInput, aB as PointRecordResponse, aU as SpendPointsInput, aD as PointSpendResponse, ay as PointBalance, a9 as HistoryFilters, aa as HistoryResponse, a_ as StackManagementClientConfig, Z as CreateStackRequest, b3 as StackResponse, aZ as StackListResponse, aW as StackConfig, J as ConfigureOAuthInput, b2 as StackOAuthProvider, L as ConfigureWeb3Input, b5 as StackWeb3Provider, K as ConfigureStripeInput, b4 as StackStripeProvider, W as CreateKeyResponse, aY as StackKeysListResponse, r as AllowlistConfig, t as AllowlistUpdateInput, at as ModelLayersResponse, b0 as StackMemberStats, a$ as StackMember, au as NetworkClientConfig, av as NetworkStatus, an as MPCNode, N as ConsensusStatus, af as LeaderStatus, u as AuthMetrics, B as BillingClientConfig, w as BillingPlansResponse, y as BillingState, R as CreateCheckoutSessionResponse, x as BillingPortalResponse } from '../billing-BaJlf_S8.js';
1
+ import { F as ChatCompletionRequest, E as ChatCompletionChunk, b6 as TaskPayload, ao as MagmaFile, ac as ImaginationMetadata, al as MCPSessionConfig, ak as MCPSession, am as MCPToolResult, aP as SocialClientConfig, ap as MediaType, a6 as FeedResponse, aF as PostResponse, I as CommentsResponse, aH as RemixesResponse, ag as LikeCheckResponse, ah as LikeResponse, H as CommentResponse, X as CreatePostInput, Y as CreatePostResponse, aG as ProfileResponse, p as AgentsClientConfig, q as AgentsListResponse, e as Agent, f as AgentCreateInput, j as AgentResponse, l as AgentUpdateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bh as WidgetUpdateInput, bg as WidgetSystemPromptResponse, b9 as UserClientConfig, ba as UserProfile, bc as UserProfileUpdateInput, bb as UserProfileResponse, a8 as FilesClientConfig, a7 as FileUploadResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aI as Skill, aJ as SkillCreateInput, aK as SkillResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, bo as SkillMapResponse, bp as SkillMapPromptResponse, bq as SkillSummaryResponse, aE as PointsClientConfig, ae as InitNetworkResponse, a5 as DomainsListResponse, O as ContextDomain, V as CreateDomainInput, a4 as DomainResponse, Q as ContextsListResponse, az as PointContext, S as CreateContextInput, P as ContextResponse, a0 as DelegationFilters, a3 as DelegationsListResponse, U as CreateDelegationInput, a1 as DelegationResponse, d as AddPointsInput, aB as PointRecordResponse, aU as SpendPointsInput, aD as PointSpendResponse, ay as PointBalance, a9 as HistoryFilters, aa as HistoryResponse, a_ as StackManagementClientConfig, Z as CreateStackRequest, b3 as StackResponse, aZ as StackListResponse, aW as StackConfig, J as ConfigureOAuthInput, b2 as StackOAuthProvider, L as ConfigureWeb3Input, b5 as StackWeb3Provider, K as ConfigureStripeInput, b4 as StackStripeProvider, W as CreateKeyResponse, aY as StackKeysListResponse, r as AllowlistConfig, t as AllowlistUpdateInput, at as ModelLayersResponse, b0 as StackMemberStats, a$ as StackMember, au as NetworkClientConfig, av as NetworkStatus, an as MPCNode, N as ConsensusStatus, af as LeaderStatus, u as AuthMetrics, B as BillingClientConfig, w as BillingPlansResponse, y as BillingState, R as CreateCheckoutSessionResponse, x as BillingPortalResponse } from '../billing-eQZIWeNW.js';
2
2
 
3
3
  /**
4
4
  * TaskNetworkClient - OpenAI-compatible SDK for StackNet
@@ -260,7 +260,10 @@ declare const socialClient: SocialClient;
260
260
  declare class AgentsClient {
261
261
  private baseUrl;
262
262
  private useCpxApi;
263
+ private authToken;
263
264
  constructor(config?: AgentsClientConfig);
265
+ setAuthToken(token: string | null): void;
266
+ private get headers();
264
267
  private get agentsUrl();
265
268
  /**
266
269
  * List all agents
@@ -739,6 +742,37 @@ declare class BillingClient {
739
742
  card_last_four?: string;
740
743
  card_brand?: string;
741
744
  }>;
745
+ /**
746
+ * Subscribe to a plan using SOL payment.
747
+ * Client must build and sign the SOL transaction first,
748
+ * then pass the on-chain tx signature here for verification.
749
+ */
750
+ subscribeSol(stackId: string, planId: string, txSignature: string): Promise<{
751
+ subscription: {
752
+ id: string;
753
+ planId: string;
754
+ planName: string;
755
+ status: string;
756
+ tokensGranted: number;
757
+ };
758
+ }>;
759
+ /**
760
+ * One-time prepaid credit via SOL payment.
761
+ */
762
+ prepaidSol(stackId: string, amountCents: number, txSignature: string, scope?: 'global' | 'stack'): Promise<{
763
+ alreadyCredited: boolean;
764
+ tokensCredited?: number;
765
+ amountCents?: number;
766
+ paymentRef?: string;
767
+ }>;
768
+ /**
769
+ * Top up account via x402 payment proof (SOL or Stripe).
770
+ */
771
+ topup(amountCents: number, paymentMethod: 'solana' | 'stripe', paymentRef: string): Promise<{
772
+ success: boolean;
773
+ tokensCredited: number;
774
+ tokenBalance: number;
775
+ }>;
742
776
  }
743
777
  /**
744
778
  * Create a BillingClient instance