@stacknet/stacks 0.1.2 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +136 -0
- package/dist/{billing-BqscteyZ.d.cts → billing-cj0eSVrp.d.cts} +61 -1
- package/dist/{billing-BqscteyZ.d.ts → billing-cj0eSVrp.d.ts} +61 -1
- package/dist/clients/index.cjs +4 -4
- package/dist/clients/index.d.cts +27 -1
- package/dist/clients/index.d.ts +27 -1
- package/dist/clients/index.js +4 -4
- package/dist/{index-DVzKiF_0.d.cts → index-B_dUFmAg.d.cts} +31 -6
- package/dist/{index-DVzKiF_0.d.ts → index-B_dUFmAg.d.ts} +31 -6
- package/dist/index.cjs +12 -16
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +12 -16
- package/dist/proxy/index.cjs +2 -2
- package/dist/proxy/index.d.cts +1 -1
- package/dist/proxy/index.d.ts +1 -1
- package/dist/proxy/index.js +2 -2
- package/dist/streaming/index.cjs +8 -12
- package/dist/streaming/index.js +8 -12
- package/dist/types/index.d.cts +1 -1
- package/dist/types/index.d.ts +1 -1
- package/package.json +15 -13
- package/src/clients/agents.ts +0 -233
- package/src/clients/billing.ts +0 -197
- package/src/clients/coder.ts +0 -655
- package/src/clients/files.ts +0 -86
- package/src/clients/index.ts +0 -93
- package/src/clients/magma.ts +0 -299
- package/src/clients/mcp.ts +0 -208
- package/src/clients/network.ts +0 -118
- package/src/clients/points.ts +0 -403
- package/src/clients/skills.ts +0 -236
- package/src/clients/social.ts +0 -286
- package/src/clients/stack-management.ts +0 -279
- package/src/clients/task-network.ts +0 -303
- package/src/clients/user.ts +0 -84
- package/src/clients/widgets.ts +0 -171
- package/src/index.ts +0 -387
- package/src/managers/index.ts +0 -10
- package/src/managers/task-manager.ts +0 -310
- package/src/proxy/forwarder.ts +0 -146
- package/src/proxy/index.ts +0 -32
- package/src/proxy/route-handlers.ts +0 -950
- package/src/streaming/component-stream.ts +0 -319
- package/src/streaming/index.ts +0 -21
- package/src/streaming/sse.ts +0 -241
- package/src/types/agent.ts +0 -106
- package/src/types/billing.ts +0 -121
- package/src/types/chat.ts +0 -58
- package/src/types/coder.ts +0 -345
- package/src/types/credential.ts +0 -111
- package/src/types/file.ts +0 -15
- package/src/types/imagination.ts +0 -50
- package/src/types/index.ts +0 -20
- package/src/types/mcp.ts +0 -35
- package/src/types/network.ts +0 -97
- package/src/types/points.ts +0 -250
- package/src/types/skill.ts +0 -107
- package/src/types/social.ts +0 -109
- package/src/types/stack.ts +0 -269
- package/src/types/task.ts +0 -41
- package/src/types/user.ts +0 -29
- package/src/types/widget.ts +0 -57
- package/src/utils/constants.ts +0 -26
- package/src/utils/errors.ts +0 -169
- package/src/utils/helpers.ts +0 -85
- package/src/utils/index.ts +0 -7
package/dist/clients/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as ChatCompletionRequest, z as ChatCompletionChunk, bi as TaskPayload, al as MagmaFile, a9 as ImaginationMetadata, ai as MCPSessionConfig, ah as MCPSession, aj as MCPToolResult, aZ as SocialClientConfig, an as MediaType, a3 as FeedResponse, aL as PostResponse, G as CommentsResponse, aN as RemixesResponse, ad as LikeCheckResponse, ae as LikeResponse, F as CommentResponse, U as CreatePostInput, V as CreatePostResponse, aw as NotificationCounts, au as NotificationAction, ax as NotificationListResponse, am as MarkViewedInput, aM as ProfileResponse, n as AgentsClientConfig, o as AgentsListResponse, c as Agent, d as AgentCreateInput, h as AgentResponse, j as AgentUpdateInput, e as AgentExecuteRequest, f as AgentExecuteResponse, g as AgentFromPromptInput, by as WidgetsClientConfig, bz as WidgetsListResponse, bt as Widget, bu as WidgetCreateInput, bv as WidgetResponse, bx as WidgetUpdateInput, bw as WidgetSystemPromptResponse, bp as UserClientConfig, bq as UserProfile, bs as UserProfileUpdateInput, br as UserProfileResponse, a5 as FilesClientConfig, a4 as FileUploadResponse, aW as SkillsClientConfig, aX as SkillsListResponse, aO as Skill, aP as SkillCreateInput, aS as SkillResponse, aU as SkillUpdateInput, aV as SkillVerifyResponse, aR as SkillMapResponse, aQ as SkillMapPromptResponse, aT as SkillSummaryResponse, aK as PointsClientConfig, ab as InitNetworkResponse, a2 as DomainsListResponse, M as ContextDomain, S as CreateDomainInput, a1 as DomainResponse, O as ContextsListResponse, aF as PointContext, Q as CreateContextInput, N as ContextResponse, Z as DelegationFilters, a0 as DelegationsListResponse, R as CreateDelegationInput, _ as DelegationResponse, b as AddPointsInput, aH as PointRecordResponse, b4 as SpendPointsInput, aJ as PointSpendResponse, aE as PointBalance, a6 as HistoryFilters, a7 as HistoryResponse, ba as StackManagementClientConfig, W as CreateStackRequest, bf as StackResponse, b9 as StackListResponse, b6 as StackConfig, H as ConfigureOAuthInput, be as StackOAuthProvider, J as ConfigureWeb3Input, bh as StackWeb3Provider, I as ConfigureStripeInput, bg as StackStripeProvider, T as CreateKeyResponse, b8 as StackKeysListResponse, p as AllowlistConfig, r as AllowlistUpdateInput, ar as ModelLayersResponse, bc as StackMemberStats, bb as StackMember, as as NetworkClientConfig, at as NetworkStatus, ak as MPCNode, L as ConsensusStatus, ac as LeaderStatus, s as AuthMetrics, B as BillingClientConfig, u as BillingPlansResponse, w as BillingState, P as CreateCheckoutSessionResponse, v as BillingPortalResponse } from '../billing-cj0eSVrp.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* TaskNetworkClient - OpenAI-compatible SDK for StackNet
|
|
@@ -238,6 +238,29 @@ declare class SocialClient {
|
|
|
238
238
|
* Track a play on audio/video post
|
|
239
239
|
*/
|
|
240
240
|
trackPlay(postId: string, userMid?: string): Promise<void>;
|
|
241
|
+
private get notificationsUrl();
|
|
242
|
+
/** Unviewed counts for the authenticated user, grouped by action. */
|
|
243
|
+
getNotificationCounts(): Promise<NotificationCounts>;
|
|
244
|
+
/** Recent notification rows for the authenticated user. */
|
|
245
|
+
getNotifications(options?: {
|
|
246
|
+
sinceId?: number;
|
|
247
|
+
beforeId?: number;
|
|
248
|
+
action?: NotificationAction;
|
|
249
|
+
limit?: number;
|
|
250
|
+
unviewedOnly?: boolean;
|
|
251
|
+
}): Promise<NotificationListResponse>;
|
|
252
|
+
/** Mark notifications viewed (by id list, up_to_id, and/or action). */
|
|
253
|
+
markNotificationsViewed(input: MarkViewedInput): Promise<{
|
|
254
|
+
updated: number;
|
|
255
|
+
}>;
|
|
256
|
+
/**
|
|
257
|
+
* Permanently remove notifications. Used by clients that want
|
|
258
|
+
* "view = remove" semantics (the geoff hover panel and /activity page
|
|
259
|
+
* both call this on render). Body shape mirrors mark-viewed.
|
|
260
|
+
*/
|
|
261
|
+
clearNotifications(input: MarkViewedInput): Promise<{
|
|
262
|
+
deleted: number;
|
|
263
|
+
}>;
|
|
241
264
|
/**
|
|
242
265
|
* Get user profile by MID
|
|
243
266
|
*/
|
|
@@ -260,7 +283,10 @@ declare const socialClient: SocialClient;
|
|
|
260
283
|
declare class AgentsClient {
|
|
261
284
|
private baseUrl;
|
|
262
285
|
private useCpxApi;
|
|
286
|
+
private authToken;
|
|
263
287
|
constructor(config?: AgentsClientConfig);
|
|
288
|
+
setAuthToken(token: string | null): void;
|
|
289
|
+
private get headers();
|
|
264
290
|
private get agentsUrl();
|
|
265
291
|
/**
|
|
266
292
|
* List all agents
|
package/dist/clients/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var
|
|
2
|
-
`);
|
|
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 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||g,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 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 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"},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 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 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 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 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 C(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`)}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
|
-
export{S as AgentsClient,_ as BillingClient,P as FilesClient,w as MCPClient,y as MagmaClient,R as NetworkClient,T as PointsClient,$ as SkillsClient,k as SocialClient,x as StackManagementClient,f as TaskNetworkClient,C as UserClient,b as WidgetsClient,re as agentsClient,
|
|
1
|
+
var p="https://stacknet.magma-rpc.com",u=p;var h="https://stacknet.magma-rpc.com";var c={"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="",l="",d=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:d,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!==l){let q=m.substring(l.length);l=m,q&&(yield {id:e,object:"chat.completion.chunk",created:d,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:l}=await s.read();if(o)break;n+=r.decode(l,{stream:!0});let d=n.split(`
|
|
3
|
+
`);n=d.pop()||"";for(let g of d)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 I(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 I(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 d=(await o.json()).imagination?.id||e.id;return typeof localStorage<"u"&&localStorage.setItem(`imagination:${d}`,d),d}}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 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 M(a){return new w(a)}var Q=M();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:c,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:c,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:c,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:c,body:JSON.stringify({userMid:e.creatorMid,title:e.title,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:c,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:c,body:JSON.stringify({userMid:t})}).catch(()=>{});}get notificationsUrl(){return `${this.baseUrl}/notifications`}async getNotificationCounts(){let e=await fetch(`${this.notificationsUrl}/counts`,{credentials:"include"});if(!e.ok)throw new i(e.status===401?"unauthorized:api":"bad_request:api",`Failed to fetch notification counts: ${e.statusText}`);return e.json()}async getNotifications(e={}){let t=new URLSearchParams;e.sinceId!==void 0&&t.set("since_id",String(e.sinceId)),e.beforeId!==void 0&&t.set("before_id",String(e.beforeId)),e.action&&t.set("action",e.action),e.limit!==void 0&&t.set("limit",String(e.limit)),e.unviewedOnly&&t.set("unviewed","true");let s=t.toString(),r=await fetch(`${this.notificationsUrl}${s?`?${s}`:""}`,{credentials:"include"});if(!r.ok)throw new i(r.status===401?"unauthorized:api":"bad_request:api",`Failed to fetch notifications: ${r.statusText}`);return r.json()}async markNotificationsViewed(e){let t=await fetch(`${this.notificationsUrl}/mark-viewed`,{method:"POST",credentials:"include",headers:c,body:JSON.stringify({up_to_id:e.upToId,ids:e.ids,action:e.action})});if(!t.ok)throw new i(t.status===401?"unauthorized:api":"bad_request:api",`Failed to mark notifications viewed: ${t.statusText}`);return t.json()}async clearNotifications(e){let t=await fetch(`${this.notificationsUrl}/clear`,{method:"POST",credentials:"include",headers:c,body:JSON.stringify({up_to_id:e.upToId,ids:e.ids,action:e.action})});if(!t.ok)throw new i(t.status===401?"unauthorized:api":"bad_request:api",`Failed to clear notifications: ${t.statusText}`);return t.json()}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={...c};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:c,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:c,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 N(a={}){return new b(a)}var ne=N();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:c,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 D(a={}){return new C(a)}var ie=D();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:c});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:c,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:c,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:c,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:c,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:c,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 ce=W();var J="/api/v2",x=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||p,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...c};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 l=await n.json().catch(()=>({})),d=n.status===404?"not_found":n.status===401?"unauthorized":"bad_request";throw new i(`${d}:api`,l.error?.message||l.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 d=await o.json().catch(()=>({}));throw new i("bad_request:api",d.error?.message||`Failed to upload logo: ${o.statusText}`)}let l=await o.json();return l&&typeof l=="object"&&"data"in l?l.data:l}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 le=G();var U="/api/v2",R=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||p,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...c};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 de="/api/v2",_=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||p,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...c};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${de}${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 l=await n.json().catch(()=>({}));throw new i(n.status===402?"payment_required:api":"bad_request:api",l.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 pe=z();
|
|
4
|
+
export{S as AgentsClient,_ as BillingClient,P as FilesClient,w as MCPClient,y as MagmaClient,R as NetworkClient,T as PointsClient,$ as SkillsClient,k as SocialClient,x as StackManagementClient,f as TaskNetworkClient,C as UserClient,b as WidgetsClient,re as agentsClient,pe as billingClient,L as createAgentsClient,z as createBillingClient,K as createFilesClient,M as createMCPClient,O as createMagmaClient,H as createNetworkClient,W as createPointsClient,B as createSkillsClient,j as createSocialClient,G as createStackManagementClient,F as createTaskNetworkClient,D as createUserClient,N as createWidgetsClient,oe as filesClient,X as magmaClient,Q as mcpClient,ue as networkClient,ce as pointsClient,ae as skillsClient,se as socialClient,le as stackManagementClient,V as taskNetworkClient,ie as userClient,ne as widgetsClient};
|
|
@@ -4,7 +4,13 @@
|
|
|
4
4
|
interface ForwarderConfig {
|
|
5
5
|
baseUrl?: string;
|
|
6
6
|
defaultHeaders?: Record<string, string>;
|
|
7
|
+
/** Request timeout in milliseconds. Applied via AbortSignal to every
|
|
8
|
+
* outbound fetch. Default: 30_000 (30s). Previously declared but not
|
|
9
|
+
* wired — an upstream hang would leak file descriptors indefinitely. */
|
|
7
10
|
timeout?: number;
|
|
11
|
+
/** Hard cap on inbound JSON body size (bytes) read by `createProxyHandler`.
|
|
12
|
+
* Requests larger than this are rejected with 413. Default: 1 MiB. */
|
|
13
|
+
maxBodyBytes?: number;
|
|
8
14
|
}
|
|
9
15
|
interface RequestOptions {
|
|
10
16
|
method?: string;
|
|
@@ -25,19 +31,39 @@ declare function forwardJSON<T = unknown>(path: string, options?: RequestOptions
|
|
|
25
31
|
status: number;
|
|
26
32
|
}>;
|
|
27
33
|
/**
|
|
28
|
-
* Create a proxy handler that forwards requests
|
|
34
|
+
* Create a proxy handler that forwards requests.
|
|
35
|
+
*
|
|
36
|
+
* SECURITY: only a small whitelist of inbound headers is forwarded (see
|
|
37
|
+
* FORWARDABLE_REQUEST_HEADERS). Everything else — including `cookie`,
|
|
38
|
+
* `x-forwarded-for`, `host` — is stripped so a caller cannot poison the
|
|
39
|
+
* upstream's view of the request or smuggle the consumer app's cookies to
|
|
40
|
+
* a third-party StackNet endpoint.
|
|
29
41
|
*/
|
|
30
42
|
declare function createProxyHandler(path: string | ((req: Request) => string), config?: ForwarderConfig): (request: Request) => Promise<Response>;
|
|
31
43
|
|
|
32
44
|
/**
|
|
33
45
|
* Next.js API Route Handler Factories
|
|
34
46
|
*
|
|
35
|
-
* Create pre-configured route handlers for common patterns
|
|
47
|
+
* Create pre-configured route handlers for common patterns.
|
|
48
|
+
*
|
|
49
|
+
* SECURITY NOTES
|
|
50
|
+
* - Every path-position parameter is run through `validateId` before being
|
|
51
|
+
* interpolated into the upstream path. Without this, characters like `?`,
|
|
52
|
+
* `&`, `#`, or `/` in an id would smuggle extra query params or escape
|
|
53
|
+
* the intended namespace.
|
|
54
|
+
* - Every factory supports `extractAuth`; the forwarder receives an
|
|
55
|
+
* `Authorization` header so the upstream can attribute the request to
|
|
56
|
+
* the real caller instead of treating it as anonymous.
|
|
36
57
|
*/
|
|
37
58
|
|
|
38
59
|
interface RouteHandlerConfig extends ForwarderConfig {
|
|
39
60
|
requireAuth?: boolean;
|
|
40
61
|
enrichResponse?: (data: unknown) => Promise<unknown>;
|
|
62
|
+
/** Extract the caller's bearer token from the incoming Request and
|
|
63
|
+
* forward it upstream as `Authorization: Bearer <token>`. If unset,
|
|
64
|
+
* the handler passes through any inbound `Authorization` header
|
|
65
|
+
* verbatim. Without one of these the upstream sees no auth at all. */
|
|
66
|
+
extractAuth?: (request: Request) => string | null;
|
|
41
67
|
}
|
|
42
68
|
type RouteHandler = (request: Request, context?: {
|
|
43
69
|
params?: Record<string, string>;
|
|
@@ -48,6 +74,9 @@ interface CRUDRouteHandlers {
|
|
|
48
74
|
PUT?: RouteHandler;
|
|
49
75
|
DELETE?: RouteHandler;
|
|
50
76
|
}
|
|
77
|
+
/** Back-compat: `StackRouteHandlerConfig` used to be distinct; now every
|
|
78
|
+
* factory accepts `extractAuth`, so the two configs are identical. */
|
|
79
|
+
type StackRouteHandlerConfig = RouteHandlerConfig;
|
|
51
80
|
/**
|
|
52
81
|
* Create agent route handlers
|
|
53
82
|
*/
|
|
@@ -166,10 +195,6 @@ declare function createCoderExecRoutes(config?: RouteHandlerConfig): {
|
|
|
166
195
|
POST: RouteHandler;
|
|
167
196
|
};
|
|
168
197
|
};
|
|
169
|
-
interface StackRouteHandlerConfig extends RouteHandlerConfig {
|
|
170
|
-
/** Extract JWT from incoming request and forward as Authorization header */
|
|
171
|
-
extractAuth?: (request: Request) => string | null;
|
|
172
|
-
}
|
|
173
198
|
/**
|
|
174
199
|
* Create stack CRUD route handlers (list + create)
|
|
175
200
|
*/
|
|
@@ -4,7 +4,13 @@
|
|
|
4
4
|
interface ForwarderConfig {
|
|
5
5
|
baseUrl?: string;
|
|
6
6
|
defaultHeaders?: Record<string, string>;
|
|
7
|
+
/** Request timeout in milliseconds. Applied via AbortSignal to every
|
|
8
|
+
* outbound fetch. Default: 30_000 (30s). Previously declared but not
|
|
9
|
+
* wired — an upstream hang would leak file descriptors indefinitely. */
|
|
7
10
|
timeout?: number;
|
|
11
|
+
/** Hard cap on inbound JSON body size (bytes) read by `createProxyHandler`.
|
|
12
|
+
* Requests larger than this are rejected with 413. Default: 1 MiB. */
|
|
13
|
+
maxBodyBytes?: number;
|
|
8
14
|
}
|
|
9
15
|
interface RequestOptions {
|
|
10
16
|
method?: string;
|
|
@@ -25,19 +31,39 @@ declare function forwardJSON<T = unknown>(path: string, options?: RequestOptions
|
|
|
25
31
|
status: number;
|
|
26
32
|
}>;
|
|
27
33
|
/**
|
|
28
|
-
* Create a proxy handler that forwards requests
|
|
34
|
+
* Create a proxy handler that forwards requests.
|
|
35
|
+
*
|
|
36
|
+
* SECURITY: only a small whitelist of inbound headers is forwarded (see
|
|
37
|
+
* FORWARDABLE_REQUEST_HEADERS). Everything else — including `cookie`,
|
|
38
|
+
* `x-forwarded-for`, `host` — is stripped so a caller cannot poison the
|
|
39
|
+
* upstream's view of the request or smuggle the consumer app's cookies to
|
|
40
|
+
* a third-party StackNet endpoint.
|
|
29
41
|
*/
|
|
30
42
|
declare function createProxyHandler(path: string | ((req: Request) => string), config?: ForwarderConfig): (request: Request) => Promise<Response>;
|
|
31
43
|
|
|
32
44
|
/**
|
|
33
45
|
* Next.js API Route Handler Factories
|
|
34
46
|
*
|
|
35
|
-
* Create pre-configured route handlers for common patterns
|
|
47
|
+
* Create pre-configured route handlers for common patterns.
|
|
48
|
+
*
|
|
49
|
+
* SECURITY NOTES
|
|
50
|
+
* - Every path-position parameter is run through `validateId` before being
|
|
51
|
+
* interpolated into the upstream path. Without this, characters like `?`,
|
|
52
|
+
* `&`, `#`, or `/` in an id would smuggle extra query params or escape
|
|
53
|
+
* the intended namespace.
|
|
54
|
+
* - Every factory supports `extractAuth`; the forwarder receives an
|
|
55
|
+
* `Authorization` header so the upstream can attribute the request to
|
|
56
|
+
* the real caller instead of treating it as anonymous.
|
|
36
57
|
*/
|
|
37
58
|
|
|
38
59
|
interface RouteHandlerConfig extends ForwarderConfig {
|
|
39
60
|
requireAuth?: boolean;
|
|
40
61
|
enrichResponse?: (data: unknown) => Promise<unknown>;
|
|
62
|
+
/** Extract the caller's bearer token from the incoming Request and
|
|
63
|
+
* forward it upstream as `Authorization: Bearer <token>`. If unset,
|
|
64
|
+
* the handler passes through any inbound `Authorization` header
|
|
65
|
+
* verbatim. Without one of these the upstream sees no auth at all. */
|
|
66
|
+
extractAuth?: (request: Request) => string | null;
|
|
41
67
|
}
|
|
42
68
|
type RouteHandler = (request: Request, context?: {
|
|
43
69
|
params?: Record<string, string>;
|
|
@@ -48,6 +74,9 @@ interface CRUDRouteHandlers {
|
|
|
48
74
|
PUT?: RouteHandler;
|
|
49
75
|
DELETE?: RouteHandler;
|
|
50
76
|
}
|
|
77
|
+
/** Back-compat: `StackRouteHandlerConfig` used to be distinct; now every
|
|
78
|
+
* factory accepts `extractAuth`, so the two configs are identical. */
|
|
79
|
+
type StackRouteHandlerConfig = RouteHandlerConfig;
|
|
51
80
|
/**
|
|
52
81
|
* Create agent route handlers
|
|
53
82
|
*/
|
|
@@ -166,10 +195,6 @@ declare function createCoderExecRoutes(config?: RouteHandlerConfig): {
|
|
|
166
195
|
POST: RouteHandler;
|
|
167
196
|
};
|
|
168
197
|
};
|
|
169
|
-
interface StackRouteHandlerConfig extends RouteHandlerConfig {
|
|
170
|
-
/** Extract JWT from incoming request and forward as Authorization header */
|
|
171
|
-
extractAuth?: (request: Request) => string | null;
|
|
172
|
-
}
|
|
173
198
|
/**
|
|
174
199
|
* Create stack CRUD route handlers (list + create)
|
|
175
200
|
*/
|