@stacknet/stacks 0.1.0 → 0.1.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 +0 -102
- package/dist/{billing-BaJlf_S8.d.cts → billing-BqscteyZ.d.cts} +29 -1
- package/dist/{billing-BaJlf_S8.d.ts → billing-BqscteyZ.d.ts} +29 -1
- package/dist/clients/index.cjs +3 -3
- package/dist/clients/index.d.cts +32 -1
- package/dist/clients/index.d.ts +32 -1
- package/dist/clients/index.js +3 -3
- package/dist/index.cjs +5 -5
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/types/index.d.cts +1 -1
- package/dist/types/index.d.ts +1 -1
- package/package.json +1 -1
- package/src/clients/billing.ts +40 -0
- package/src/types/billing.ts +34 -0
package/dist/index.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
export { AgentsClient, BillingClient, FilesClient, MCPClient, MagmaClient, MagmaClientConfig, NetworkClient, PointsClient, SkillsClient, SocialClient, StackManagementClient, TaskNetworkClient, TaskNetworkConfig, UserClient, WidgetsClient, agentsClient, billingClient, createAgentsClient, createBillingClient, createFilesClient, createMCPClient, createMagmaClient, createNetworkClient, createPointsClient, createSkillsClient, createSocialClient, createStackManagementClient, createTaskNetworkClient, createUserClient, createWidgetsClient, filesClient, magmaClient, mcpClient, networkClient, pointsClient, skillsClient, socialClient, stackManagementClient, taskNetworkClient, userClient, widgetsClient } from './clients/index.js';
|
|
2
2
|
import { CoderClientConfig, CoderSandboxCreateInput, CoderSession, CoderExecuteRequest, CoderExecuteResponse, CoderStreamEvent, CoderTool, CoderToolResult, CoderFileContent, CoderFileWriteInput, CoderFileInfo, CoderSearchResult, CoderDiffInput, CoderCommandInput, CoderCommandResult, CoderSandbox, CoderSandboxExecInput, CoderSandboxExecResult } from './types/index.js';
|
|
3
3
|
export { AuthMethod, BillingCredentialData, CoderMetrics, CoderSandboxConfig, CoderSessionStatus, CoderStreamEventType, CredentialLinkProof, CredentialType, EmailCredentialData, GlobalIdentity, OAuthCredentialData, Session, StackCredential, StackIdentity, StripeConnectCredentialData, Web3Chain, Web3CredentialData } from './types/index.js';
|
|
4
|
-
import { T as TaskType, a as TaskState, b as TaskStatus } from './billing-
|
|
5
|
-
export { A as ALL_CAPABILITIES_BITMASK, c as ActionProof, d as AddPointsInput, e as Agent, f as AgentCreateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, j as AgentResponse, k as AgentTrigger, l as AgentUpdateInput, m as AgentWorkflow, n as AgentWorkflowEdge, o as AgentWorkflowNode, p as AgentsClientConfig, q as AgentsListResponse, r as AllowlistConfig, s as AllowlistMode, t as AllowlistUpdateInput, u as AuthMetrics, B as BillingClientConfig, v as BillingPlan, w as BillingPlansResponse, x as BillingPortalResponse, y as BillingState, z as BillingTier, C as CAPABILITY_BITS, D as CapabilityKey, E as ChatCompletionChunk, F as ChatCompletionRequest, G as ChatCompletionResponse, H as CommentResponse, I as CommentsResponse, J as ConfigureOAuthInput, K as ConfigureStripeInput, L as ConfigureWeb3Input, M as ConsensusStateSummary, N as ConsensusStatus, O as ContextDomain, P as ContextResponse, Q as ContextsListResponse, R as CreateCheckoutSessionResponse, S as CreateContextInput, U as CreateDelegationInput, V as CreateDomainInput, W as CreateKeyResponse, X as CreatePostInput, Y as CreatePostResponse, Z as CreateStackRequest, _ as Delegation, $ as DelegationChainLink, a0 as DelegationFilters, a1 as DelegationResponse, a2 as DelegationScope, a3 as DelegationsListResponse, a4 as DomainResponse, a5 as DomainsListResponse, a6 as FeedResponse, a7 as FileUploadResponse, a8 as FilesClientConfig, a9 as HistoryFilters, aa as HistoryResponse, ab as ImaginationCharacter, ac as ImaginationMetadata, ad as ImaginationSource, ae as InitNetworkResponse, af as LeaderStatus, ag as LikeCheckResponse, ah as LikeResponse, ai as MCPContent, aj as MCPMessage, ak as MCPSession, al as MCPSessionConfig, am as MCPToolResult, an as MPCNode, ao as MagmaFile, ap as MediaType, aq as Message, ar as MeteredUsage, as as ModelLayerInfo, at as ModelLayersResponse, au as NetworkClientConfig, av as NetworkStatus, aw as PaginationMeta, ax as PaymentRequiredResponse, ay as PointBalance, az as PointContext, aA as PointRecord, aB as PointRecordResponse, aC as PointSpend, aD as PointSpendResponse, aE as PointsClientConfig, aF as PostResponse, aG as ProfileResponse, aH as RemixesResponse, aI as Skill, aJ as SkillCreateInput, aK as SkillResponse, aL as SkillUpdateInput, aM as SkillsClientConfig, aN as SkillsListResponse, aO as SocialAuthor, aP as SocialClientConfig, aQ as SocialComment, aR as SocialPost, aS as SocialRemix, aT as SpendDestination, aU as SpendPointsInput, aV as StackCapabilities, aW as StackConfig, aX as StackKeyInfo, aY as StackKeysListResponse, aZ as StackListResponse, a_ as StackManagementClientConfig, a$ as StackMember, b0 as StackMemberStats, b1 as StackModelAlias, b2 as StackOAuthProvider, b3 as StackResponse, b4 as StackStripeProvider, b5 as StackWeb3Provider, b6 as TaskPayload, b7 as TaskResponse, b8 as UsageRecord, b9 as UserClientConfig, ba as UserProfile, bb as UserProfileResponse, bc as UserProfileUpdateInput, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bg as WidgetSystemPromptResponse, bh as WidgetUpdateInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bk as WorkflowData, bl as bitmaskToCapabilities, bm as capabilitiesToBitmask } from './billing-
|
|
4
|
+
import { T as TaskType, a as TaskState, b as TaskStatus } from './billing-BqscteyZ.js';
|
|
5
|
+
export { A as ALL_CAPABILITIES_BITMASK, c as ActionProof, d as AddPointsInput, e as Agent, f as AgentCreateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, j as AgentResponse, k as AgentTrigger, l as AgentUpdateInput, m as AgentWorkflow, n as AgentWorkflowEdge, o as AgentWorkflowNode, p as AgentsClientConfig, q as AgentsListResponse, r as AllowlistConfig, s as AllowlistMode, t as AllowlistUpdateInput, u as AuthMetrics, B as BillingClientConfig, v as BillingPlan, w as BillingPlansResponse, x as BillingPortalResponse, y as BillingState, z as BillingTier, C as CAPABILITY_BITS, D as CapabilityKey, E as ChatCompletionChunk, F as ChatCompletionRequest, G as ChatCompletionResponse, H as CommentResponse, I as CommentsResponse, J as ConfigureOAuthInput, K as ConfigureStripeInput, L as ConfigureWeb3Input, M as ConsensusStateSummary, N as ConsensusStatus, O as ContextDomain, P as ContextResponse, Q as ContextsListResponse, R as CreateCheckoutSessionResponse, S as CreateContextInput, U as CreateDelegationInput, V as CreateDomainInput, W as CreateKeyResponse, X as CreatePostInput, Y as CreatePostResponse, Z as CreateStackRequest, _ as Delegation, $ as DelegationChainLink, a0 as DelegationFilters, a1 as DelegationResponse, a2 as DelegationScope, a3 as DelegationsListResponse, a4 as DomainResponse, a5 as DomainsListResponse, a6 as FeedResponse, a7 as FileUploadResponse, a8 as FilesClientConfig, a9 as HistoryFilters, aa as HistoryResponse, ab as ImaginationCharacter, ac as ImaginationMetadata, ad as ImaginationSource, ae as InitNetworkResponse, af as LeaderStatus, ag as LikeCheckResponse, ah as LikeResponse, ai as MCPContent, aj as MCPMessage, ak as MCPSession, al as MCPSessionConfig, am as MCPToolResult, an as MPCNode, ao as MagmaFile, ap as MediaType, aq as Message, ar as MeteredUsage, as as ModelLayerInfo, at as ModelLayersResponse, au as NetworkClientConfig, av as NetworkStatus, aw as PaginationMeta, ax as PaymentRequiredResponse, ay as PointBalance, az as PointContext, aA as PointRecord, aB as PointRecordResponse, aC as PointSpend, aD as PointSpendResponse, aE as PointsClientConfig, aF as PostResponse, aG as ProfileResponse, aH as RemixesResponse, aI as Skill, aJ as SkillCreateInput, aK as SkillResponse, aL as SkillUpdateInput, aM as SkillsClientConfig, aN as SkillsListResponse, aO as SocialAuthor, aP as SocialClientConfig, aQ as SocialComment, aR as SocialPost, aS as SocialRemix, aT as SpendDestination, aU as SpendPointsInput, aV as StackCapabilities, aW as StackConfig, aX as StackKeyInfo, aY as StackKeysListResponse, aZ as StackListResponse, a_ as StackManagementClientConfig, a$ as StackMember, b0 as StackMemberStats, b1 as StackModelAlias, b2 as StackOAuthProvider, b3 as StackResponse, b4 as StackStripeProvider, b5 as StackWeb3Provider, b6 as TaskPayload, b7 as TaskResponse, b8 as UsageRecord, b9 as UserClientConfig, ba as UserProfile, bb as UserProfileResponse, bc as UserProfileUpdateInput, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bg as WidgetSystemPromptResponse, bh as WidgetUpdateInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bk as WorkflowData, bl as bitmaskToCapabilities, bm as capabilitiesToBitmask } from './billing-BqscteyZ.js';
|
|
6
6
|
export { ArtifactToolCall, ArtifactToolResult, ComponentStreamAdapter, DataStreamWriter, SSEEvent, SSEWriter, createComponentStreamAdapter, createSSEResponse, createSSEWriter, extractToolResults, hasToolCalls, parseSSEStream } from './streaming/index.js';
|
|
7
7
|
export { C as CRUDRouteHandlers, F as ForwarderConfig, R as RequestOptions, a as RouteHandler, b as RouteHandlerConfig, S as StackRouteHandlerConfig, c as createAgentDetailRoutes, d as createAgentExecuteRoute, e as createAgentRoutes, f as createAgentToggleRoutes, g as createCoderExecRoutes, h as createCoderExecuteRoute, i as createCoderFilesRoutes, j as createCoderSandboxRoutes, k as createCoderSessionDetailRoutes, l as createCoderSessionRoutes, m as createCoderToolsRoutes, n as createImaginationRoutes, o as createProxyHandler, p as createSkillDetailRoutes, q as createSkillRoutes, r as createStackDetailRoutes, s as createStackKeysRoutes, t as createStackMembersRoutes, u as createStackRoutes, v as createWidgetDetailRoutes, w as createWidgetRoutes, x as forwardJSON, y as forwardRequest } from './index-DVzKiF_0.js';
|
|
8
8
|
|
package/dist/index.js
CHANGED
|
@@ -1,17 +1,17 @@
|
|
|
1
|
-
var R="https://stacknet.magma-rpc.com",h=R;var T="http://geoff.magma-rpc.com",b="task:",
|
|
1
|
+
var R="https://stacknet.magma-rpc.com",h=R;var T="http://geoff.magma-rpc.com",b="task:",P="chat:tasks:",J=86400*7,x={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"},p={"Content-Type":"application/json"};var $=class{baseUrl;apiKey;timeout;constructor(e={}){this.baseUrl=(e.baseUrl||h).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,a="",i="",d=Math.floor(Date.now()/1e3);try{for(;;){let{done:u,value:g}=await r.read();if(u){yield {id:e,object:"chat.completion.chunk",created:d,model:t,choices:[{index:0,delta:{},finish_reason:"stop"}]};break}a+=n.decode(g,{stream:!0});let m=a.split(`
|
|
2
2
|
`);a=m.pop()||"";for(let f of m)if(f.startsWith("data: "))try{let S=JSON.parse(f.slice(6));if(Array.isArray(S)&&S.length>0){let C=S[0].result||"";if(C&&C!==i){let V=C.substring(i.length);i=C,V&&(yield {id:e,object:"chat.completion.chunk",created:d,model:t,choices:[{index:0,delta:{role:"assistant",content:V},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:a,value:i}=await s.read();if(a)break;n+=r.decode(i,{stream:!0});let d=n.split(`
|
|
3
|
-
`);n=d.pop()||"";for(let u of d)if(u.startsWith("data: "))try{yield JSON.parse(u.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 X(o){return new $(o)}var he=X();function G(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let e=Math.random()*16|0;return (o==="x"?e:e&3|8).toString(16)})}async function z(o){let e=await crypto.subtle.digest("SHA-256",o);return `baf${Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,52)}`}function Q(o){return new Promise(e=>setTimeout(e,o))}async function fe(o,e={}){let{maxAttempts:t=3,initialDelay:s=1e3,maxDelay:r=3e4,backoffFactor:n=2}=e,a,i=s;for(let d=1;d<=t;d++)try{return await o()}catch(u){if(a=u,d===t)break;await Q(i),i=Math.min(i*n,r);}throw a}function ye(o){return !o||o.startsWith(":")?null:o.startsWith("event:")?{event:o.slice(6).trim()}:o.startsWith("data:")?{data:o.slice(5).trim()}:null}var U=class{baseUrl;localServerUrl;constructor(e={}){this.baseUrl=e.baseUrl||T,this.localServerUrl=e.localServerUrl||h;}async uploadFile(e){let t=await e.arrayBuffer(),s=await z(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 a=await fetch(`${this.localServerUrl}/imaginations/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok)throw new Error(`Failed to update imagination: ${a.statusText}`);return typeof localStorage<"u"&&localStorage.setItem(`imagination:${e.id}`,e.id),e.id}else {let a=await fetch(`${this.localServerUrl}/imaginations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok)throw new Error(`Failed to store imagination: ${a.statusText}`);let d=(await a.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(a=>({id:a.id,title:a.title,createdAt:new Date(a.created_at).toISOString(),createdBy:a.creator_mid,sources:a.sources,summary:a.summary,character:a.character,workflow:a.workflow,is_public:a.is_public}));return typeof localStorage<"u"&&n.forEach(a=>{localStorage.setItem(`imagination:${a.id}`,a.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 Z(o){return new U(o)}var we=Z();var I=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 ee(o){return new I(o)}var Se=ee();var te={database:"log",chat:"response",auth:"response",stream:"response",api:"response",history:"response",vote:"response",document:"response",suggestions:"response",task:"response",agent:"response",imagination:"response"},c=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=se(e),this.statusCode=be(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=te[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 se(o){if(o.includes("database"))return "An error occurred while executing a database query.";switch(o){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 be(o){switch(o){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 E=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}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 a=await fetch(`${this.socialUrl}/feed?${n}`);if(!a.ok)throw new c("bad_request:api",`Failed to fetch feed: ${a.statusText}`);return a.json()}async getPost(e){let t=await fetch(`${this.socialUrl}/posts/${e}`);if(!t.ok)throw new c(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 c("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 c("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 c("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:p,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new c("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:p,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new c("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:p,body:JSON.stringify({postId:e,userMid:t,content:s})});if(!r.ok)throw new c("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:p,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 c("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:p,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:p,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 c("bad_request:api",`Failed to fetch profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof c)throw t;return null}}};function re(o={}){return new E(o)}var ke=re();var A=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||h,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 c("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 c(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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("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 c("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 c("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 c("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:p,body:JSON.stringify(t)});if(!s.ok)throw new c("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:p,body:JSON.stringify(e)});if(!t.ok)throw new c("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 ne(o={}){return new A(o)}var Ce=ne();var _=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}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 c("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 c(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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("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 c("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 c("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 ae(o={}){return new _(o)}var Re=ae();var v=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}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 c("bad_request:api",`Failed to get user profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof c)throw t;return null}}async updateProfile(e,t){let s=await fetch(`${this.userUrl}/profile/${e}`,{method:"PUT",headers:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to update user profile: ${s.statusText}`)}return s.json()}};function oe(o={}){return new v(o)}var Te=oe();var O=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}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 c("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 c("bad_request:api",`Failed to upload file from URL: ${t.statusText}`);return t.json()}getFileUrl(e){return `${this.filesUrl}/${e}`}};function ie(o={}){return new O(o)}var xe=ie();var j=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||T,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 ce(o){return new j(o)}var Pe=ce();var D=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||T;}get pointsUrl(){return `${this.baseUrl}/cpx/points`}async initNetworkDomain(){let e=await fetch(`${this.pointsUrl}/init`,{method:"POST",headers:p});if(!e.ok){let t=await e.json().catch(()=>({}));throw new c("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 c("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 c("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:p,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new c("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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 c("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 c("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:p,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new c("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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 c("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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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 c("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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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}`:""}`,a=await fetch(n);if(!a.ok)throw new c("bad_request:api",`Failed to get balance: ${a.statusText}`);return a.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 c("bad_request:api",`Failed to get history: ${n.statusText}`);return n.json()}};function de(o={}){return new D(o)}var $e=de();var L=class{baseUrl;apiKey;timeout;defaultModel;defaultMaxIterations;constructor(e={}){this.baseUrl=e.baseUrl||h,this.apiKey=e.apiKey,this.timeout=e.timeout||3e5,this.defaultModel=e.defaultModel||"geoff-code-1:1",this.defaultMaxIterations=e.defaultMaxIterations||20;}get coderUrl(){return `${this.baseUrl}/coder`}get headers(){let e={...p};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}async createSession(e,t){let s=await fetch(`${this.coderUrl}/sessions`,{method:"POST",headers:this.headers,body:JSON.stringify({workingDirectory:e,sandbox:t})});if(!s.ok){let n=await s.json().catch(()=>({}));throw new c("bad_request:api",n.error||`Failed to create coder session: ${s.statusText}`)}return (await s.json()).session}async getSession(e){let t=await fetch(`${this.coderUrl}/sessions/${e}`,{headers:this.headers});if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to get coder session: ${t.statusText}`);return (await t.json()).session}async listSessions(e={}){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit.toString());let s=t.toString(),r=`${this.coderUrl}/sessions${s?`?${s}`:""}`,n=await fetch(r,{headers:this.headers});if(!n.ok)throw new c("bad_request:api",`Failed to list coder sessions: ${n.statusText}`);return (await n.json()).sessions}async abortSession(e){let t=await fetch(`${this.coderUrl}/sessions/${e}/abort`,{method:"POST",headers:this.headers});if(!t.ok)throw new c("bad_request:api",`Failed to abort coder session: ${t.statusText}`);return (await t.json()).session}async execute(e){let t={prompt:e.prompt,workingDirectory:e.workingDirectory,maxIterations:e.maxIterations||this.defaultMaxIterations,model:e.model||this.defaultModel,maxTokens:e.maxTokens,temperature:e.temperature,sessionId:e.sessionId,sandboxId:e.sandboxId,sandbox:e.sandbox,stream:false},s=await fetch(`${this.coderUrl}/execute`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to execute coder: ${s.statusText}`)}return s.json()}async*executeStream(e){let t={prompt:e.prompt,workingDirectory:e.workingDirectory,maxIterations:e.maxIterations||this.defaultMaxIterations,model:e.model||this.defaultModel,maxTokens:e.maxTokens,temperature:e.temperature,sessionId:e.sessionId,sandboxId:e.sandboxId,sandbox:e.sandbox,stream:true},s=new AbortController,r=setTimeout(()=>s.abort(),this.timeout),n=await fetch(`${this.coderUrl}/execute`,{method:"POST",headers:{...this.headers,Accept:"text/event-stream",Connection:"keep-alive","Cache-Control":"no-cache"},body:JSON.stringify(t),signal:s.signal,keepalive:true});if(!n.ok){let u=await n.json().catch(()=>({}));throw new c("bad_request:api",u.error||`Failed to execute coder stream: ${n.statusText}`)}let a=n.body?.getReader();if(!a)throw new c("bad_request:stream","No response body");let i=new TextDecoder,d="";try{for(;;){let{done:u,value:g}=await a.read();if(u)break;d+=i.decode(g,{stream:!0});let m=d.split(`
|
|
3
|
+
`);n=d.pop()||"";for(let u of d)if(u.startsWith("data: "))try{yield JSON.parse(u.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 X(o){return new $(o)}var he=X();function G(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,o=>{let e=Math.random()*16|0;return (o==="x"?e:e&3|8).toString(16)})}async function z(o){let e=await crypto.subtle.digest("SHA-256",o);return `baf${Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,52)}`}function Q(o){return new Promise(e=>setTimeout(e,o))}async function fe(o,e={}){let{maxAttempts:t=3,initialDelay:s=1e3,maxDelay:r=3e4,backoffFactor:n=2}=e,a,i=s;for(let d=1;d<=t;d++)try{return await o()}catch(u){if(a=u,d===t)break;await Q(i),i=Math.min(i*n,r);}throw a}function ye(o){return !o||o.startsWith(":")?null:o.startsWith("event:")?{event:o.slice(6).trim()}:o.startsWith("data:")?{data:o.slice(5).trim()}:null}var U=class{baseUrl;localServerUrl;constructor(e={}){this.baseUrl=e.baseUrl||T,this.localServerUrl=e.localServerUrl||h;}async uploadFile(e){let t=await e.arrayBuffer(),s=await z(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 a=await fetch(`${this.localServerUrl}/imaginations/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok)throw new Error(`Failed to update imagination: ${a.statusText}`);return typeof localStorage<"u"&&localStorage.setItem(`imagination:${e.id}`,e.id),e.id}else {let a=await fetch(`${this.localServerUrl}/imaginations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!a.ok)throw new Error(`Failed to store imagination: ${a.statusText}`);let d=(await a.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(a=>({id:a.id,title:a.title,createdAt:new Date(a.created_at).toISOString(),createdBy:a.creator_mid,sources:a.sources,summary:a.summary,character:a.character,workflow:a.workflow,is_public:a.is_public}));return typeof localStorage<"u"&&n.forEach(a=>{localStorage.setItem(`imagination:${a.id}`,a.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 Z(o){return new U(o)}var we=Z();var I=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 ee(o){return new I(o)}var Se=ee();var te={database:"log",chat:"response",auth:"response",stream:"response",api:"response",history:"response",vote:"response",document:"response",suggestions:"response",task:"response",agent:"response",imagination:"response"},c=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=se(e),this.statusCode=be(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=te[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 se(o){if(o.includes("database"))return "An error occurred while executing a database query.";switch(o){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 be(o){switch(o){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 E=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}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 a=await fetch(`${this.socialUrl}/feed?${n}`);if(!a.ok)throw new c("bad_request:api",`Failed to fetch feed: ${a.statusText}`);return a.json()}async getPost(e){let t=await fetch(`${this.socialUrl}/posts/${e}`);if(!t.ok)throw new c(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 c("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 c("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 c("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:p,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new c("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:p,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new c("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:p,body:JSON.stringify({postId:e,userMid:t,content:s})});if(!r.ok)throw new c("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:p,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 c("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:p,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:p,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 c("bad_request:api",`Failed to fetch profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof c)throw t;return null}}};function re(o={}){return new E(o)}var ke=re();var A=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||h,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 c("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 c(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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("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 c("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 c("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 c("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:p,body:JSON.stringify(t)});if(!s.ok)throw new c("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:p,body:JSON.stringify(e)});if(!t.ok)throw new c("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 ne(o={}){return new A(o)}var Ce=ne();var _=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}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 c("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 c(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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("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 c("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 c("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 ae(o={}){return new _(o)}var Re=ae();var v=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}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 c("bad_request:api",`Failed to get user profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof c)throw t;return null}}async updateProfile(e,t){let s=await fetch(`${this.userUrl}/profile/${e}`,{method:"PUT",headers:p,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to update user profile: ${s.statusText}`)}return s.json()}};function oe(o={}){return new v(o)}var Te=oe();var O=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}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 c("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 c("bad_request:api",`Failed to upload file from URL: ${t.statusText}`);return t.json()}getFileUrl(e){return `${this.filesUrl}/${e}`}};function ie(o={}){return new O(o)}var Pe=ie();var j=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||T,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 ce(o){return new j(o)}var xe=ce();var D=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||T;}get pointsUrl(){return `${this.baseUrl}/cpx/points`}async initNetworkDomain(){let e=await fetch(`${this.pointsUrl}/init`,{method:"POST",headers:p});if(!e.ok){let t=await e.json().catch(()=>({}));throw new c("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 c("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 c("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:p,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new c("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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 c("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 c("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:p,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new c("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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 c("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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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 c("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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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:p,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new c("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}`:""}`,a=await fetch(n);if(!a.ok)throw new c("bad_request:api",`Failed to get balance: ${a.statusText}`);return a.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 c("bad_request:api",`Failed to get history: ${n.statusText}`);return n.json()}};function de(o={}){return new D(o)}var $e=de();var L=class{baseUrl;apiKey;timeout;defaultModel;defaultMaxIterations;constructor(e={}){this.baseUrl=e.baseUrl||h,this.apiKey=e.apiKey,this.timeout=e.timeout||3e5,this.defaultModel=e.defaultModel||"geoff-code-1:1",this.defaultMaxIterations=e.defaultMaxIterations||20;}get coderUrl(){return `${this.baseUrl}/coder`}get headers(){let e={...p};return this.apiKey&&(e.Authorization=`Bearer ${this.apiKey}`),e}async createSession(e,t){let s=await fetch(`${this.coderUrl}/sessions`,{method:"POST",headers:this.headers,body:JSON.stringify({workingDirectory:e,sandbox:t})});if(!s.ok){let n=await s.json().catch(()=>({}));throw new c("bad_request:api",n.error||`Failed to create coder session: ${s.statusText}`)}return (await s.json()).session}async getSession(e){let t=await fetch(`${this.coderUrl}/sessions/${e}`,{headers:this.headers});if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to get coder session: ${t.statusText}`);return (await t.json()).session}async listSessions(e={}){let t=new URLSearchParams;e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit.toString());let s=t.toString(),r=`${this.coderUrl}/sessions${s?`?${s}`:""}`,n=await fetch(r,{headers:this.headers});if(!n.ok)throw new c("bad_request:api",`Failed to list coder sessions: ${n.statusText}`);return (await n.json()).sessions}async abortSession(e){let t=await fetch(`${this.coderUrl}/sessions/${e}/abort`,{method:"POST",headers:this.headers});if(!t.ok)throw new c("bad_request:api",`Failed to abort coder session: ${t.statusText}`);return (await t.json()).session}async execute(e){let t={prompt:e.prompt,workingDirectory:e.workingDirectory,maxIterations:e.maxIterations||this.defaultMaxIterations,model:e.model||this.defaultModel,maxTokens:e.maxTokens,temperature:e.temperature,sessionId:e.sessionId,sandboxId:e.sandboxId,sandbox:e.sandbox,stream:false},s=await fetch(`${this.coderUrl}/execute`,{method:"POST",headers:this.headers,body:JSON.stringify(t),signal:AbortSignal.timeout(this.timeout)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to execute coder: ${s.statusText}`)}return s.json()}async*executeStream(e){let t={prompt:e.prompt,workingDirectory:e.workingDirectory,maxIterations:e.maxIterations||this.defaultMaxIterations,model:e.model||this.defaultModel,maxTokens:e.maxTokens,temperature:e.temperature,sessionId:e.sessionId,sandboxId:e.sandboxId,sandbox:e.sandbox,stream:true},s=new AbortController,r=setTimeout(()=>s.abort(),this.timeout),n=await fetch(`${this.coderUrl}/execute`,{method:"POST",headers:{...this.headers,Accept:"text/event-stream",Connection:"keep-alive","Cache-Control":"no-cache"},body:JSON.stringify(t),signal:s.signal,keepalive:true});if(!n.ok){let u=await n.json().catch(()=>({}));throw new c("bad_request:api",u.error||`Failed to execute coder stream: ${n.statusText}`)}let a=n.body?.getReader();if(!a)throw new c("bad_request:stream","No response body");let i=new TextDecoder,d="";try{for(;;){let{done:u,value:g}=await a.read();if(u)break;d+=i.decode(g,{stream:!0});let m=d.split(`
|
|
4
4
|
`);d=m.pop()||"";for(let f of m)if(f.startsWith("data: ")){let S=f.slice(6);if(S==="[DONE]")return;try{yield JSON.parse(S);}catch{}}}}finally{clearTimeout(r),a.releaseLock();}}async getTools(){let e=await fetch(`${this.coderUrl}/tools`,{headers:this.headers});if(!e.ok)throw new c("bad_request:api",`Failed to get coder tools: ${e.statusText}`);return (await e.json()).tools}async callTool(e,t,s={}){let r=await fetch(`${this.coderUrl}/tools/${e}`,{method:"POST",headers:this.headers,body:JSON.stringify({arguments:t,sessionId:s.sessionId,sandboxId:s.sandboxId})});if(!r.ok){let n=await r.json().catch(()=>({}));throw new c("bad_request:api",n.error||`Failed to call tool ${e}: ${r.statusText}`)}return r.json()}async readFile(e,t={}){let s=new URLSearchParams({path:e});t.sessionId&&s.set("sessionId",t.sessionId),t.sandboxId&&s.set("sandboxId",t.sandboxId);let r=await fetch(`${this.coderUrl}/files/read?${s}`,{headers:this.headers});if(!r.ok)throw new c(r.status===404?"not_found:api":"bad_request:api",`Failed to read file: ${r.statusText}`);return r.json()}async writeFile(e,t={}){let s=await fetch(`${this.coderUrl}/files/write`,{method:"POST",headers:this.headers,body:JSON.stringify({...e,sessionId:t.sessionId,sandboxId:t.sandboxId})});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to write file: ${s.statusText}`)}return s.json()}async listFiles(e,t={}){let s=new URLSearchParams({path:e});t.recursive&&s.set("recursive","true"),t.maxDepth&&s.set("maxDepth",t.maxDepth.toString()),t.sessionId&&s.set("sessionId",t.sessionId),t.sandboxId&&s.set("sandboxId",t.sandboxId);let r=await fetch(`${this.coderUrl}/files/list?${s}`,{headers:this.headers});if(!r.ok)throw new c("bad_request:api",`Failed to list files: ${r.statusText}`);return (await r.json()).files}async searchFiles(e,t={}){let s=new URLSearchParams({pattern:e});t.path&&s.set("path",t.path),t.filePattern&&s.set("filePattern",t.filePattern),t.sessionId&&s.set("sessionId",t.sessionId),t.sandboxId&&s.set("sandboxId",t.sandboxId);let r=await fetch(`${this.coderUrl}/files/search?${s}`,{headers:this.headers});if(!r.ok)throw new c("bad_request:api",`Failed to search files: ${r.statusText}`);return (await r.json()).results}async applyDiff(e,t={}){let s=await fetch(`${this.coderUrl}/files/diff`,{method:"POST",headers:this.headers,body:JSON.stringify({...e,sessionId:t.sessionId,sandboxId:t.sandboxId})});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to apply diff: ${s.statusText}`)}return s.json()}async executeCommand(e,t={}){let s=await fetch(`${this.coderUrl}/exec`,{method:"POST",headers:this.headers,body:JSON.stringify({...e,sessionId:t.sessionId,sandboxId:t.sandboxId})});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to execute command: ${s.statusText}`)}return s.json()}async*executeCommandStream(e,t={}){let s=await fetch(`${this.coderUrl}/exec/stream`,{method:"POST",headers:{...this.headers,Accept:"text/event-stream"},body:JSON.stringify({...e,sessionId:t.sessionId,sandboxId:t.sandboxId})});if(!s.ok){let i=await s.json().catch(()=>({}));throw new c("bad_request:api",i.error||`Failed to execute command stream: ${s.statusText}`)}let r=s.body?.getReader();if(!r)throw new c("bad_request:stream","No response body");let n=new TextDecoder,a="";try{for(;;){let{done:i,value:d}=await r.read();if(i)break;a+=n.decode(d,{stream:!0});let u=a.split(`
|
|
5
|
-
`);a=u.pop()||"";for(let g of u)if(g.startsWith("data: ")){let m=g.slice(6);if(m==="[DONE]")return;try{yield JSON.parse(m);}catch{}}}}finally{r.releaseLock();}}async createSandbox(e={}){let t=await fetch(`${this.coderUrl}/sandbox`,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok){let r=await t.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to create sandbox: ${t.statusText}`)}return (await t.json()).sandbox}async getSandbox(e){let t=await fetch(`${this.coderUrl}/sandbox/${e}`,{headers:this.headers});if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to get sandbox: ${t.statusText}`);return (await t.json()).sandbox}async sandboxExec(e,t){let s=await fetch(`${this.coderUrl}/sandbox/${e}/exec`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to execute in sandbox: ${s.statusText}`)}return s.json()}async destroySandbox(e){let t=await fetch(`${this.coderUrl}/sandbox/${e}`,{method:"DELETE",headers:this.headers});if(!t.ok)throw new c("bad_request:api",`Failed to destroy sandbox: ${t.statusText}`);return t.json()}};function le(o={}){return new L(o)}var Ue=le();var ue="/api/v2",q=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||R,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...p};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${ue}${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 i=await n.json().catch(()=>({})),d=n.status===404?"not_found":n.status===401?"unauthorized":"bad_request";throw new c(`${d}:api`,i.error?.message||i.error||`Request failed: ${n.statusText}`)}let a=await n.json();return a&&typeof a=="object"&&"data"in a?a.data:a}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}${ue}/stacks/${e}/logo`,r=new FormData;r.append("logo",t);let n={};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);let a=await fetch(s,{method:"POST",headers:n,body:r});if(!a.ok){let d=await a.json().catch(()=>({}));throw new c("bad_request:api",d.error?.message||`Failed to upload logo: ${a.statusText}`)}let i=await a.json();return i&&typeof i=="object"&&"data"in i?i.data:i}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 pe(o={}){return new q(o)}var Ie=pe();var F="/api/v2",M=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||R,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...p};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 c("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}${F}/network/status`)}async getMPCNodes(){return this.request("GET",`${this.baseUrl}${F}/network/nodes`)}async getNodeHealth(e){return this.request("GET",`${this.baseUrl}${F}/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}${F}${t}`)}};function me(o={}){return new M(o)}var Ee=me();var Ae="/api/v2",N=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||R,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...p};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${Ae}${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 i=await n.json().catch(()=>({}));throw new c(n.status===402?"payment_required:api":"bad_request:api",i.error?.message||`Request failed: ${n.statusText}`)}let a=await n.json();return a&&typeof a=="object"&&"data"in a?a.data:a}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 ge(o={}){return new N(o)}var _e=ge();var H=class{redis;getRedisClient;taskTTL;constructor(e={}){this.redis=e.redis,this.getRedisClient=e.getRedisClient,this.taskTTL=e.taskTTL||J;}async getClient(){if(this.redis)return this.redis;if(this.getRedisClient)return this.redis=await this.getRedisClient(),this.redis;throw new Error("Redis client not configured. Provide redis or getRedisClient in config.")}async createTask(e,t,s,r="Starting..."){let n=await this.getClient(),a=G(),i=Date.now(),d={id:a,chatId:e,messageId:t,type:s,status:"pending",progress:0,message:r,createdAt:i,updatedAt:i};return await n.hSet(`${b}${a}`,this.taskToRedis(d)),await n.expire(`${b}${a}`,this.taskTTL),await n.sAdd(`${x}${e}`,a),await n.expire(`${x}${e}`,this.taskTTL),console.log(`[TaskManager] Created task ${a} for chat ${e} (${s})`),a}async updateProgress(e,t,s){let r=await this.getClient();await r.hSet(`${b}${e}`,{status:"generating",progress:t.toString(),message:s,updatedAt:Date.now().toString()}),await r.publish(`task:progress:${e}`,JSON.stringify({taskId:e,progress:t,message:s,status:"generating"})),console.log(`[TaskManager] Task ${e} progress: ${t}% - ${s}`);}async complete(e,t){let s=await this.getClient();await s.hSet(`${b}${e}`,{status:"complete",progress:"100",message:"Complete",result:JSON.stringify(t),updatedAt:Date.now().toString()}),await s.publish(`task:progress:${e}`,JSON.stringify({taskId:e,progress:100,message:"Complete",status:"complete",result:t})),console.log(`[TaskManager] Task ${e} completed`);}async fail(e,t){let s=await this.getClient();await s.hSet(`${b}${e}`,{status:"failed",message:t,error:t,updatedAt:Date.now().toString()}),await s.publish(`task:progress:${e}`,JSON.stringify({taskId:e,status:"failed",error:t})),console.log(`[TaskManager] Task ${e} failed: ${t}`);}async getTask(e){let s=await(await this.getClient()).hGetAll(`${b}${e}`);return !s||Object.keys(s).length===0?null:this.redisToTask(s)}async getTasksForChat(e){let s=await(await this.getClient()).sMembers(`${x}${e}`);if(!s||s.length===0)return [];let r=[];for(let n of s){let a=await this.getTask(n);a&&r.push(a);}return r.sort((n,a)=>a.createdAt-n.createdAt)}async getPendingTasksForChat(e){return (await this.getTasksForChat(e)).filter(s=>s.status==="pending"||s.status==="generating")}async deleteTask(e){let t=await this.getClient(),s=await this.getTask(e);s&&(await t.del(`${b}${e}`),await t.sRem(`${x}${s.chatId}`,e),console.log(`[TaskManager] Deleted task ${e}`));}async cleanupOldTasks(e,t=864e5){let s=await this.getTasksForChat(e),r=Date.now();for(let n of s)(n.status==="complete"||n.status==="failed")&&r-n.updatedAt>t&&await this.deleteTask(n.id);}async subscribeToTask(e,t){let s=await this.getClient(),r=`task:progress:${e}`;return await s.subscribe(r,n=>{try{let a=JSON.parse(n);t(a);}catch{}}),async()=>{await s.unsubscribe(r);}}taskToRedis(e){return {id:e.id,chatId:e.chatId,messageId:e.messageId,type:e.type,status:e.status,progress:e.progress.toString(),message:e.message,result:e.result||"",error:e.error||"",createdAt:e.createdAt.toString(),updatedAt:e.updatedAt.toString()}}redisToTask(e){return {id:e.id,chatId:e.chatId,messageId:e.messageId,type:e.type,status:e.status,progress:parseInt(e.progress,10),message:e.message,result:e.result||void 0,error:e.error||void 0,createdAt:parseInt(e.createdAt,10),updatedAt:parseInt(e.updatedAt,10)}}};function ve(o){return new H(o)}async function*Oe(o){if(!o.body)throw new Error("Response body is null");let e=o.body.getReader(),t=new TextDecoder,s="",r={};try{for(;;){let{done:n,value:a}=await e.read();if(n)break;s+=t.decode(a,{stream:!0});let i=s.split(`
|
|
5
|
+
`);a=u.pop()||"";for(let g of u)if(g.startsWith("data: ")){let m=g.slice(6);if(m==="[DONE]")return;try{yield JSON.parse(m);}catch{}}}}finally{r.releaseLock();}}async createSandbox(e={}){let t=await fetch(`${this.coderUrl}/sandbox`,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok){let r=await t.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to create sandbox: ${t.statusText}`)}return (await t.json()).sandbox}async getSandbox(e){let t=await fetch(`${this.coderUrl}/sandbox/${e}`,{headers:this.headers});if(!t.ok)throw new c(t.status===404?"not_found:api":"bad_request:api",`Failed to get sandbox: ${t.statusText}`);return (await t.json()).sandbox}async sandboxExec(e,t){let s=await fetch(`${this.coderUrl}/sandbox/${e}/exec`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new c("bad_request:api",r.error||`Failed to execute in sandbox: ${s.statusText}`)}return s.json()}async destroySandbox(e){let t=await fetch(`${this.coderUrl}/sandbox/${e}`,{method:"DELETE",headers:this.headers});if(!t.ok)throw new c("bad_request:api",`Failed to destroy sandbox: ${t.statusText}`);return t.json()}};function le(o={}){return new L(o)}var Ue=le();var ue="/api/v2",q=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||R,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...p};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${ue}${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 i=await n.json().catch(()=>({})),d=n.status===404?"not_found":n.status===401?"unauthorized":"bad_request";throw new c(`${d}:api`,i.error?.message||i.error||`Request failed: ${n.statusText}`)}let a=await n.json();return a&&typeof a=="object"&&"data"in a?a.data:a}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}${ue}/stacks/${e}/logo`,r=new FormData;r.append("logo",t);let n={};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);let a=await fetch(s,{method:"POST",headers:n,body:r});if(!a.ok){let d=await a.json().catch(()=>({}));throw new c("bad_request:api",d.error?.message||`Failed to upload logo: ${a.statusText}`)}let i=await a.json();return i&&typeof i=="object"&&"data"in i?i.data:i}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 pe(o={}){return new q(o)}var Ie=pe();var F="/api/v2",M=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||R,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...p};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 c("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}${F}/network/status`)}async getMPCNodes(){return this.request("GET",`${this.baseUrl}${F}/network/nodes`)}async getNodeHealth(e){return this.request("GET",`${this.baseUrl}${F}/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}${F}${t}`)}};function me(o={}){return new M(o)}var Ee=me();var Ae="/api/v2",N=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||R,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...p};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${Ae}${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 i=await n.json().catch(()=>({}));throw new c(n.status===402?"payment_required:api":"bad_request:api",i.error?.message||`Request failed: ${n.statusText}`)}let a=await n.json();return a&&typeof a=="object"&&"data"in a?a.data:a}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 ge(o={}){return new N(o)}var _e=ge();var H=class{redis;getRedisClient;taskTTL;constructor(e={}){this.redis=e.redis,this.getRedisClient=e.getRedisClient,this.taskTTL=e.taskTTL||J;}async getClient(){if(this.redis)return this.redis;if(this.getRedisClient)return this.redis=await this.getRedisClient(),this.redis;throw new Error("Redis client not configured. Provide redis or getRedisClient in config.")}async createTask(e,t,s,r="Starting..."){let n=await this.getClient(),a=G(),i=Date.now(),d={id:a,chatId:e,messageId:t,type:s,status:"pending",progress:0,message:r,createdAt:i,updatedAt:i};return await n.hSet(`${b}${a}`,this.taskToRedis(d)),await n.expire(`${b}${a}`,this.taskTTL),await n.sAdd(`${P}${e}`,a),await n.expire(`${P}${e}`,this.taskTTL),console.log(`[TaskManager] Created task ${a} for chat ${e} (${s})`),a}async updateProgress(e,t,s){let r=await this.getClient();await r.hSet(`${b}${e}`,{status:"generating",progress:t.toString(),message:s,updatedAt:Date.now().toString()}),await r.publish(`task:progress:${e}`,JSON.stringify({taskId:e,progress:t,message:s,status:"generating"})),console.log(`[TaskManager] Task ${e} progress: ${t}% - ${s}`);}async complete(e,t){let s=await this.getClient();await s.hSet(`${b}${e}`,{status:"complete",progress:"100",message:"Complete",result:JSON.stringify(t),updatedAt:Date.now().toString()}),await s.publish(`task:progress:${e}`,JSON.stringify({taskId:e,progress:100,message:"Complete",status:"complete",result:t})),console.log(`[TaskManager] Task ${e} completed`);}async fail(e,t){let s=await this.getClient();await s.hSet(`${b}${e}`,{status:"failed",message:t,error:t,updatedAt:Date.now().toString()}),await s.publish(`task:progress:${e}`,JSON.stringify({taskId:e,status:"failed",error:t})),console.log(`[TaskManager] Task ${e} failed: ${t}`);}async getTask(e){let s=await(await this.getClient()).hGetAll(`${b}${e}`);return !s||Object.keys(s).length===0?null:this.redisToTask(s)}async getTasksForChat(e){let s=await(await this.getClient()).sMembers(`${P}${e}`);if(!s||s.length===0)return [];let r=[];for(let n of s){let a=await this.getTask(n);a&&r.push(a);}return r.sort((n,a)=>a.createdAt-n.createdAt)}async getPendingTasksForChat(e){return (await this.getTasksForChat(e)).filter(s=>s.status==="pending"||s.status==="generating")}async deleteTask(e){let t=await this.getClient(),s=await this.getTask(e);s&&(await t.del(`${b}${e}`),await t.sRem(`${P}${s.chatId}`,e),console.log(`[TaskManager] Deleted task ${e}`));}async cleanupOldTasks(e,t=864e5){let s=await this.getTasksForChat(e),r=Date.now();for(let n of s)(n.status==="complete"||n.status==="failed")&&r-n.updatedAt>t&&await this.deleteTask(n.id);}async subscribeToTask(e,t){let s=await this.getClient(),r=`task:progress:${e}`;return await s.subscribe(r,n=>{try{let a=JSON.parse(n);t(a);}catch{}}),async()=>{await s.unsubscribe(r);}}taskToRedis(e){return {id:e.id,chatId:e.chatId,messageId:e.messageId,type:e.type,status:e.status,progress:e.progress.toString(),message:e.message,result:e.result||"",error:e.error||"",createdAt:e.createdAt.toString(),updatedAt:e.updatedAt.toString()}}redisToTask(e){return {id:e.id,chatId:e.chatId,messageId:e.messageId,type:e.type,status:e.status,progress:parseInt(e.progress,10),message:e.message,result:e.result||void 0,error:e.error||void 0,createdAt:parseInt(e.createdAt,10),updatedAt:parseInt(e.updatedAt,10)}}};function ve(o){return new H(o)}async function*Oe(o){if(!o.body)throw new Error("Response body is null");let e=o.body.getReader(),t=new TextDecoder,s="",r={};try{for(;;){let{done:n,value:a}=await e.read();if(n)break;s+=t.decode(a,{stream:!0});let i=s.split(`
|
|
6
6
|
`);s=i.pop()||"";for(let d of i){if(d===""){r.data!==void 0&&(yield r),r={};continue}if(d.startsWith(":"))continue;let u=d.indexOf(":");if(u===-1)continue;let g=d.slice(0,u),m=d.slice(u+1).trimStart();switch(g){case "event":r.event=m;break;case "data":try{r.data=JSON.parse(m);}catch{r.data=m;}break;case "id":r.id=m;break;case "retry":r.retry=parseInt(m,10);break}}}r.data!==void 0&&(yield r);}finally{e.releaseLock();}}function je(o,e){let t=new TextEncoder,s=new ReadableStream({async start(r){try{for await(let n of o){let a="";n.event&&(a+=`event: ${n.event}
|
|
7
7
|
`),n.id&&(a+=`id: ${n.id}
|
|
8
8
|
`),n.retry&&(a+=`retry: ${n.retry}
|
|
9
9
|
`);let i=typeof n.data=="string"?n.data:JSON.stringify(n.data);a+=`data: ${i}
|
|
10
10
|
|
|
11
|
-
`,r.enqueue(t.encode(a));}}catch(n){console.error("SSE stream error:",n);}finally{r.close();}}});return new Response(s,{headers:{...
|
|
11
|
+
`,r.enqueue(t.encode(a));}}catch(n){console.error("SSE stream error:",n);}finally{r.close();}}});return new Response(s,{headers:{...x,...e}})}var K=class{encoder=new TextEncoder;controller=null;stream;constructor(){this.stream=new ReadableStream({start:e=>{this.controller=e;}});}getStream(){return this.stream}getResponse(e){return new Response(this.stream,{headers:{...x,...e}})}write(e){if(!this.controller)return;let t="";e.event&&(t+=`event: ${e.event}
|
|
12
12
|
`),e.id&&(t+=`id: ${e.id}
|
|
13
13
|
`);let s=typeof e.data=="string"?e.data:JSON.stringify(e.data);t+=`data: ${s}
|
|
14
14
|
|
|
15
15
|
`,this.controller.enqueue(this.encoder.encode(t));}writeData(e){this.write({data:e});}writeComment(e){this.controller&&this.controller.enqueue(this.encoder.encode(`: ${e}
|
|
16
16
|
|
|
17
|
-
`));}close(){this.controller&&(this.controller.close(),this.controller=null);}error(e){this.controller&&(this.controller.error(e),this.controller=null);}};function De(){return new K}var W=class{constructor(e){this.dataStream=e;}processToolCalls(e){if(!(!e||e.length===0))for(let t of e)try{let s=JSON.parse(t.function.arguments),r=t.function.name;switch(r){case "create_document":this.handleCreateDocument(s,t.id);break;case "update_document":this.handleUpdateDocument(s,t.id);break;default:console.log(`[ComponentStream] Unknown tool: ${r}`);}}catch(s){console.error("[ComponentStream] Error processing tool call:",s);}}processToolResult(e){try{e.type==="artifact"?this.handleArtifactResult(e):e.type==="artifact_update"&&this.handleArtifactUpdate(e);}catch(t){console.error("[ComponentStream] Error processing tool result:",t);}}streamArtifact(e){this.dataStream.write({type:"data-kind",data:e.kind,transient:true}),this.dataStream.write({type:"data-id",data:e.id,transient:true}),this.dataStream.write({type:"data-title",data:e.title,transient:true}),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(e.content),this.dataStream.write({type:"data-finish",data:null,transient:true});}streamTextDelta(e){this.dataStream.write({type:"data-textDelta",data:e,transient:true});}streamContent(e,t=50){let s=this.splitIntoChunks(e,t);for(let r of s)this.dataStream.write({type:"data-textDelta",data:r,transient:true});}finish(){this.dataStream.write({type:"data-finish",data:null,transient:true});}handleCreateDocument(e,t){let{title:s,kind:r,content:n}=e,a=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;console.log(`[ComponentStream] Creating document: ${s} (${r})`),this.streamArtifact({id:a,kind:r,title:s,content:n}),this.dataStream.write({type:"tool-result",data:{toolCallId:t,toolName:"create_document",result:{id:a,title:s,kind:r,message:"Document created successfully"}}});}handleUpdateDocument(e,t){let{id:s,description:r,content:n}=e;console.log(`[ComponentStream] Updating document: ${s}`),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(n),this.dataStream.write({type:"data-finish",data:null,transient:true}),this.dataStream.write({type:"tool-result",data:{toolCallId:t,toolName:"update_document",result:{id:s,message:`Document updated: ${r}`}}});}handleArtifactResult(e){let{id:t,title:s,kind:r,content:n}=e;if(!t||!s||!r||!n){console.error("[ComponentStream] Invalid artifact result:",e);return}this.streamArtifact({id:t,kind:r,title:s,content:n});}handleArtifactUpdate(e){let{content:t}=e;if(!t){console.error("[ComponentStream] Invalid artifact update:",e);return}this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(t),this.dataStream.write({type:"data-finish",data:null,transient:true});}splitIntoChunks(e,t){let s=[],r=e.split(" "),n="";for(let a=0;a<r.length;a++){let i=a===0?r[a]:" "+r[a];n.length+i.length>t&&n.length>0?(s.push(n),n=i.trim()):n+=i;}return n.length>0&&s.push(n),s}};function Le(o){return !!(o?.tool_calls&&Array.isArray(o.tool_calls)&&o.tool_calls.length>0)}function qe(o){try{let e=JSON.parse(o);if(e.type&&(e.type==="artifact"||e.type==="artifact_update"))return [e]}catch{}return []}function Fe(o){return new W(o)}async function k(o,e={},t={}){let s=t.baseUrl||h,{method:r="GET",headers:n={},body:a,searchParams:i,stream:d}=e,u=`${s}${o}`;if(i){let f=new URLSearchParams;Object.entries(i).forEach(([B,C])=>{C!==void 0&&f.set(B,C);});let S=f.toString();S&&(u+=`?${S}`);}let g={method:r,headers:{...t.defaultHeaders,...n}};a&&r!=="GET"&&(g.headers={...g.headers,"Content-Type":"application/json"},g.body=JSON.stringify(a));let m=await fetch(u,g);return d&&m.body,m}async function l(o,e={},t={}){let s=await k(o,e,t);return {data:await s.json(),status:s.status}}function Me(o,e={}){return async t=>{let s=new URL(t.url),r=typeof o=="function"?o(t):o,n={};s.searchParams.forEach((m,f)=>{n[f]=m;});let a;if(t.method!=="GET"&&t.method!=="HEAD")try{a=await t.json();}catch{}let i={};t.headers.forEach((m,f)=>{i[f]=m;});let d=await k(r,{method:t.method,headers:i,body:a,searchParams:n},e);if((d.headers.get("content-type")||"").includes("text/event-stream"))return new Response(d.body,{status:d.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let g=await d.json();return Response.json(g,{status:d.status})}}function Ne(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("userMid"),n=s.searchParams.get("visibility"),a=r?`/agents?creator_mid=${encodeURIComponent(r)}`:n?`/agents?visibility=${n}`:"/agents",{data:i,status:d}=await l(a,{},{baseUrl:e}),u=i;return o.enrichResponse&&(u=await o.enrichResponse(i)),Response.json(u,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/agents",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function He(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/agents/${r}`,{},{baseUrl:e}),i=n;return o.enrichResponse&&(i=await o.enrichResponse(n)),Response.json(i,{status:a})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/agents/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/agents/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/agents/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})}}}function Ke(o={}){let e=o.baseUrl;return {POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],n=await t.json(),a=await k(`/agents/${r}/execute`,{method:"POST",body:n,stream:true},{baseUrl:e});if((a.headers.get("content-type")||"").includes("text/event-stream")&&a.body)return new Response(a.body,{status:a.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let d=await a.json();return Response.json(d,{status:a.status})}}}function We(o={}){let e=o.baseUrl;return {enable:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:a}=await l(`/agents/${r}/enable`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:a})}},disable:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:a}=await l(`/agents/${r}/disable`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:a})}}}}function Be(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("scope"),n=s.searchParams.get("creator_mid"),a="/skills";r?a+=`?scope=${encodeURIComponent(r)}`:n&&(a+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(a,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/skills",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Je(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/skills/${r}`,{},{baseUrl:e});return Response.json(n,{status:a})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/skills/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/skills/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/skills/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})}}}function Ge(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("scope"),n=s.searchParams.get("creator_mid"),a="/widgets";r?a+=`?scope=${encodeURIComponent(r)}`:n&&(a+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(a,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/widgets",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function ze(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/widgets/${r}`,{},{baseUrl:e});return Response.json(n,{status:a})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/widgets/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/widgets/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/widgets/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})}}}function Ye(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("id"),n=s.searchParams.get("creator_mid"),a="/imaginations";r?a=`/imaginations/${r}`:n&&(a+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(a,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/imaginations",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Ve(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("status"),n=s.searchParams.get("limit"),a="/coder/sessions",i=[];r&&i.push(`status=${encodeURIComponent(r)}`),n&&i.push(`limit=${encodeURIComponent(n)}`),i.length&&(a+=`?${i.join("&")}`);let{data:d,status:u}=await l(a,{},{baseUrl:e});return Response.json(d,{status:u})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/sessions",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Xe(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/coder/sessions/${r}`,{},{baseUrl:e});return Response.json(n,{status:a})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/coder/sessions/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/coder/sessions/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})},abort:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:a}=await l(`/coder/sessions/${r}/abort`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:a})}}}}function Qe(o={}){let e=o.baseUrl;return {POST:async t=>{let s=await t.json(),r=await k("/coder/execute",{method:"POST",body:s,stream:s.stream},{baseUrl:e});if((r.headers.get("content-type")||"").includes("text/event-stream")&&r.body)return new Response(r.body,{status:r.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let a=await r.json();return Response.json(a,{status:r.status})}}}function Ze(o={}){let e=o.baseUrl;return {GET:async()=>{let{data:t,status:s}=await l("/coder/tools",{},{baseUrl:e});return Response.json(t,{status:s})},call:{POST:async(t,s)=>{let r=s?.params?.tool||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/coder/tools/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})}}}}function et(o={}){let e=o.baseUrl;return {read:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("path")||"",n=s.searchParams.get("sessionId"),a=s.searchParams.get("sandboxId"),i=`/coder/files/read?path=${encodeURIComponent(r)}`;n&&(i+=`&sessionId=${encodeURIComponent(n)}`),a&&(i+=`&sandboxId=${encodeURIComponent(a)}`);let{data:d,status:u}=await l(i,{},{baseUrl:e});return Response.json(d,{status:u})}},write:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/files/write",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}},list:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("path")||".",n=s.searchParams.get("recursive"),a=s.searchParams.get("maxDepth"),i=s.searchParams.get("sessionId"),d=s.searchParams.get("sandboxId"),u=`/coder/files/list?path=${encodeURIComponent(r)}`;n&&(u+=`&recursive=${n}`),a&&(u+=`&maxDepth=${a}`),i&&(u+=`&sessionId=${encodeURIComponent(i)}`),d&&(u+=`&sandboxId=${encodeURIComponent(d)}`);let{data:g,status:m}=await l(u,{},{baseUrl:e});return Response.json(g,{status:m})}},search:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("pattern")||"",n=s.searchParams.get("path"),a=s.searchParams.get("filePattern"),i=s.searchParams.get("sessionId"),d=s.searchParams.get("sandboxId"),u=`/coder/files/search?pattern=${encodeURIComponent(r)}`;n&&(u+=`&path=${encodeURIComponent(n)}`),a&&(u+=`&filePattern=${encodeURIComponent(a)}`),i&&(u+=`&sessionId=${encodeURIComponent(i)}`),d&&(u+=`&sandboxId=${encodeURIComponent(d)}`);let{data:g,status:m}=await l(u,{},{baseUrl:e});return Response.json(g,{status:m})}},diff:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/files/diff",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}}function tt(o={}){let e=o.baseUrl;return {create:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/sandbox",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}},get:{GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/coder/sandbox/${r}`,{},{baseUrl:e});return Response.json(n,{status:a})}},exec:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],n=await t.json(),a=await k(`/coder/sandbox/${r}/exec`,{method:"POST",body:n,stream:n.stream},{baseUrl:e});if((a.headers.get("content-type")||"").includes("text/event-stream")&&a.body)return new Response(a.body,{status:a.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let d=await a.json();return Response.json(d,{status:a.status})}},destroy:{DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/coder/sandbox/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})}}}}function st(o={}){let e=o.baseUrl;return {POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/exec",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})},stream:{POST:async t=>{let s=await t.json(),r=await k("/coder/exec/stream",{method:"POST",body:s,stream:true},{baseUrl:e});if(r.body)return new Response(r.body,{status:r.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let n=await r.json();return Response.json(n,{status:r.status})}}}}function y(o,e){if(!o||typeof o!="string")throw new Error(`Missing required parameter: ${e}`);if(!/^[\w.\-]+$/.test(o))throw new Error(`Invalid ${e}: contains disallowed characters`);return o}function w(o,e){let t={};if(o.extractAuth){let s=o.extractAuth(e);s&&(t.Authorization=`Bearer ${s}`);}else {let s=e.headers.get("Authorization");s&&(t.Authorization=s);}return t}function rt(o={}){let e=o.baseUrl;return {GET:async t=>{let{data:s,status:r}=await l("/api/v2/stacks",{headers:w(o,t)},{baseUrl:e});return Response.json(s,{status:r})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/api/v2/stacks",{method:"POST",body:s,headers:w(o,t)},{baseUrl:e});return Response.json(r,{status:n})}}}function nt(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),{data:n,status:a}=await l(`/api/v2/stacks/${r}`,{headers:w(o,t)},{baseUrl:e});return Response.json(n,{status:a})},POST:async()=>Response.json({error:"Method not allowed"},{status:405}),PUT:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=await t.json(),{data:a,status:i}=await l(`/api/v2/stacks/${r}`,{method:"PATCH",body:n,headers:w(o,t)},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),{data:n,status:a}=await l(`/api/v2/stacks/${r}`,{method:"DELETE",headers:w(o,t)},{baseUrl:e});return Response.json(n,{status:a})}}}function at(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),{data:n,status:a}=await l(`/api/v2/stacks/${r}/keys`,{headers:w(o,t)},{baseUrl:e});return Response.json(n,{status:a})},POST:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=await t.json(),{data:a,status:i}=await l(`/api/v2/stacks/${r}/keys`,{method:"POST",body:n,headers:w(o,t)},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=y(s?.params?.keyId,"keyId"),{data:a,status:i}=await l(`/api/v2/stacks/${r}/keys/${n}`,{method:"DELETE",headers:w(o,t)},{baseUrl:e});return Response.json(a,{status:i})}}}function ot(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=new URL(t.url),a=new URLSearchParams,i=n.searchParams.get("limit"),d=n.searchParams.get("offset"),u=n.searchParams.get("role");i&&a.set("limit",i),d&&a.set("offset",d),u&&a.set("role",u);let g=a.toString()?`?${a}`:"",{data:m,status:f}=await l(`/api/v2/stacks/${r}/members${g}`,{headers:w(o,t)},{baseUrl:e});return Response.json(m,{status:f})},stats:{GET:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),{data:n,status:a}=await l(`/api/v2/stacks/${r}/members/stats`,{headers:w(o,t)},{baseUrl:e});return Response.json(n,{status:a})}},updateRole:{PATCH:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=y(s?.params?.userId,"userId"),a=await t.json(),{data:i,status:d}=await l(`/api/v2/stacks/${r}/members/${encodeURIComponent(n)}/role`,{method:"PATCH",body:a,headers:w(o,t)},{baseUrl:e});return Response.json(i,{status:d})}}}}var Y={text_input:1,image_input:2,file_input:4,audio_input:8,video_input:16,music_input:32,text_output:64,image_output:128,audio_output:256,video_output:512,embeddings_output:1024,music_output:2048,skills:4096,loops:8192,tools:16384,pipelines:32768,training:65536},it=131071;function ct(o){let e=0;for(let[t,s]of Object.entries(Y))o[t]&&(e|=s);return e}function dt(o){let e={};for(let[t,s]of Object.entries(Y))e[t]=(o&s)!==0;return e}export{it as ALL_CAPABILITIES_BITMASK,A as AgentsClient,N as BillingClient,Y as CAPABILITY_BITS,x as CHAT_TASKS_PREFIX,L as CoderClient,W as ComponentStreamAdapter,T as DEFAULT_MAGMA_RPC_URL,h as DEFAULT_TASK_NETWORK_URL,O as FilesClient,p as JSON_HEADERS,I as MCPClient,U as MagmaClient,M as NetworkClient,D as PointsClient,K as SSEWriter,P as SSE_HEADERS,j as SkillsClient,E as SocialClient,q as StackManagementClient,c as StacksSDKError,b as TASK_PREFIX,J as TASK_TTL,H as TaskManager,$ as TaskNetworkClient,v as UserClient,_ as WidgetsClient,Ce as agentsClient,_e as billingClient,dt as bitmaskToCapabilities,ct as capabilitiesToBitmask,Ue as coderClient,He as createAgentDetailRoutes,Ke as createAgentExecuteRoute,Ne as createAgentRoutes,We as createAgentToggleRoutes,ne as createAgentsClient,ge as createBillingClient,le as createCoderClient,st as createCoderExecRoutes,Qe as createCoderExecuteRoute,et as createCoderFilesRoutes,tt as createCoderSandboxRoutes,Xe as createCoderSessionDetailRoutes,Ve as createCoderSessionRoutes,Ze as createCoderToolsRoutes,Fe as createComponentStreamAdapter,ie as createFilesClient,Ye as createImaginationRoutes,ee as createMCPClient,Z as createMagmaClient,me as createNetworkClient,de as createPointsClient,Me as createProxyHandler,je as createSSEResponse,De as createSSEWriter,Je as createSkillDetailRoutes,Be as createSkillRoutes,ce as createSkillsClient,re as createSocialClient,nt as createStackDetailRoutes,at as createStackKeysRoutes,pe as createStackManagementClient,ot as createStackMembersRoutes,rt as createStackRoutes,ve as createTaskManager,X as createTaskNetworkClient,oe as createUserClient,ze as createWidgetDetailRoutes,Ge as createWidgetRoutes,ae as createWidgetsClient,qe as extractToolResults,xe as filesClient,l as forwardJSON,k as forwardRequest,z as generateCID,G as generateUUID,se as getMessageByErrorCode,Le as hasToolCalls,we as magmaClient,Se as mcpClient,Ee as networkClient,ye as parseSSELine,Oe as parseSSEStream,$e as pointsClient,fe as retry,Pe as skillsClient,Q as sleep,ke as socialClient,Ie as stackManagementClient,he as taskNetworkClient,Te as userClient,te as visibilityBySurface,Re as widgetsClient};
|
|
17
|
+
`));}close(){this.controller&&(this.controller.close(),this.controller=null);}error(e){this.controller&&(this.controller.error(e),this.controller=null);}};function De(){return new K}var W=class{constructor(e){this.dataStream=e;}processToolCalls(e){if(!(!e||e.length===0))for(let t of e)try{let s=JSON.parse(t.function.arguments),r=t.function.name;switch(r){case "create_document":this.handleCreateDocument(s,t.id);break;case "update_document":this.handleUpdateDocument(s,t.id);break;default:console.log(`[ComponentStream] Unknown tool: ${r}`);}}catch(s){console.error("[ComponentStream] Error processing tool call:",s);}}processToolResult(e){try{e.type==="artifact"?this.handleArtifactResult(e):e.type==="artifact_update"&&this.handleArtifactUpdate(e);}catch(t){console.error("[ComponentStream] Error processing tool result:",t);}}streamArtifact(e){this.dataStream.write({type:"data-kind",data:e.kind,transient:true}),this.dataStream.write({type:"data-id",data:e.id,transient:true}),this.dataStream.write({type:"data-title",data:e.title,transient:true}),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(e.content),this.dataStream.write({type:"data-finish",data:null,transient:true});}streamTextDelta(e){this.dataStream.write({type:"data-textDelta",data:e,transient:true});}streamContent(e,t=50){let s=this.splitIntoChunks(e,t);for(let r of s)this.dataStream.write({type:"data-textDelta",data:r,transient:true});}finish(){this.dataStream.write({type:"data-finish",data:null,transient:true});}handleCreateDocument(e,t){let{title:s,kind:r,content:n}=e,a=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;console.log(`[ComponentStream] Creating document: ${s} (${r})`),this.streamArtifact({id:a,kind:r,title:s,content:n}),this.dataStream.write({type:"tool-result",data:{toolCallId:t,toolName:"create_document",result:{id:a,title:s,kind:r,message:"Document created successfully"}}});}handleUpdateDocument(e,t){let{id:s,description:r,content:n}=e;console.log(`[ComponentStream] Updating document: ${s}`),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(n),this.dataStream.write({type:"data-finish",data:null,transient:true}),this.dataStream.write({type:"tool-result",data:{toolCallId:t,toolName:"update_document",result:{id:s,message:`Document updated: ${r}`}}});}handleArtifactResult(e){let{id:t,title:s,kind:r,content:n}=e;if(!t||!s||!r||!n){console.error("[ComponentStream] Invalid artifact result:",e);return}this.streamArtifact({id:t,kind:r,title:s,content:n});}handleArtifactUpdate(e){let{content:t}=e;if(!t){console.error("[ComponentStream] Invalid artifact update:",e);return}this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(t),this.dataStream.write({type:"data-finish",data:null,transient:true});}splitIntoChunks(e,t){let s=[],r=e.split(" "),n="";for(let a=0;a<r.length;a++){let i=a===0?r[a]:" "+r[a];n.length+i.length>t&&n.length>0?(s.push(n),n=i.trim()):n+=i;}return n.length>0&&s.push(n),s}};function Le(o){return !!(o?.tool_calls&&Array.isArray(o.tool_calls)&&o.tool_calls.length>0)}function qe(o){try{let e=JSON.parse(o);if(e.type&&(e.type==="artifact"||e.type==="artifact_update"))return [e]}catch{}return []}function Fe(o){return new W(o)}async function k(o,e={},t={}){let s=t.baseUrl||h,{method:r="GET",headers:n={},body:a,searchParams:i,stream:d}=e,u=`${s}${o}`;if(i){let f=new URLSearchParams;Object.entries(i).forEach(([B,C])=>{C!==void 0&&f.set(B,C);});let S=f.toString();S&&(u+=`?${S}`);}let g={method:r,headers:{...t.defaultHeaders,...n}};a&&r!=="GET"&&(g.headers={...g.headers,"Content-Type":"application/json"},g.body=JSON.stringify(a));let m=await fetch(u,g);return d&&m.body,m}async function l(o,e={},t={}){let s=await k(o,e,t);return {data:await s.json(),status:s.status}}function Me(o,e={}){return async t=>{let s=new URL(t.url),r=typeof o=="function"?o(t):o,n={};s.searchParams.forEach((m,f)=>{n[f]=m;});let a;if(t.method!=="GET"&&t.method!=="HEAD")try{a=await t.json();}catch{}let i={};t.headers.forEach((m,f)=>{i[f]=m;});let d=await k(r,{method:t.method,headers:i,body:a,searchParams:n},e);if((d.headers.get("content-type")||"").includes("text/event-stream"))return new Response(d.body,{status:d.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let g=await d.json();return Response.json(g,{status:d.status})}}function Ne(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("userMid"),n=s.searchParams.get("visibility"),a=r?`/agents?creator_mid=${encodeURIComponent(r)}`:n?`/agents?visibility=${n}`:"/agents",{data:i,status:d}=await l(a,{},{baseUrl:e}),u=i;return o.enrichResponse&&(u=await o.enrichResponse(i)),Response.json(u,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/agents",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function He(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/agents/${r}`,{},{baseUrl:e}),i=n;return o.enrichResponse&&(i=await o.enrichResponse(n)),Response.json(i,{status:a})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/agents/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/agents/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/agents/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})}}}function Ke(o={}){let e=o.baseUrl;return {POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],n=await t.json(),a=await k(`/agents/${r}/execute`,{method:"POST",body:n,stream:true},{baseUrl:e});if((a.headers.get("content-type")||"").includes("text/event-stream")&&a.body)return new Response(a.body,{status:a.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let d=await a.json();return Response.json(d,{status:a.status})}}}function We(o={}){let e=o.baseUrl;return {enable:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:a}=await l(`/agents/${r}/enable`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:a})}},disable:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:a}=await l(`/agents/${r}/disable`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:a})}}}}function Be(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("scope"),n=s.searchParams.get("creator_mid"),a="/skills";r?a+=`?scope=${encodeURIComponent(r)}`:n&&(a+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(a,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/skills",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Je(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/skills/${r}`,{},{baseUrl:e});return Response.json(n,{status:a})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/skills/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/skills/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/skills/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})}}}function Ge(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("scope"),n=s.searchParams.get("creator_mid"),a="/widgets";r?a+=`?scope=${encodeURIComponent(r)}`:n&&(a+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(a,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/widgets",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function ze(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/widgets/${r}`,{},{baseUrl:e});return Response.json(n,{status:a})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/widgets/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})},PUT:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/widgets/${r}`,{method:"PUT",body:n},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/widgets/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})}}}function Ye(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("id"),n=s.searchParams.get("creator_mid"),a="/imaginations";r?a=`/imaginations/${r}`:n&&(a+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:d}=await l(a,{},{baseUrl:e});return Response.json(i,{status:d})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/imaginations",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Ve(o={}){let e=o.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("status"),n=s.searchParams.get("limit"),a="/coder/sessions",i=[];r&&i.push(`status=${encodeURIComponent(r)}`),n&&i.push(`limit=${encodeURIComponent(n)}`),i.length&&(a+=`?${i.join("&")}`);let{data:d,status:u}=await l(a,{},{baseUrl:e});return Response.json(d,{status:u})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/sessions",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}function Xe(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/coder/sessions/${r}`,{},{baseUrl:e});return Response.json(n,{status:a})},POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/coder/sessions/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/coder/sessions/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})},abort:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],{data:n,status:a}=await l(`/coder/sessions/${r}/abort`,{method:"POST"},{baseUrl:e});return Response.json(n,{status:a})}}}}function Qe(o={}){let e=o.baseUrl;return {POST:async t=>{let s=await t.json(),r=await k("/coder/execute",{method:"POST",body:s,stream:s.stream},{baseUrl:e});if((r.headers.get("content-type")||"").includes("text/event-stream")&&r.body)return new Response(r.body,{status:r.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let a=await r.json();return Response.json(a,{status:r.status})}}}function Ze(o={}){let e=o.baseUrl;return {GET:async()=>{let{data:t,status:s}=await l("/coder/tools",{},{baseUrl:e});return Response.json(t,{status:s})},call:{POST:async(t,s)=>{let r=s?.params?.tool||new URL(t.url).pathname.split("/").pop(),n=await t.json(),{data:a,status:i}=await l(`/coder/tools/${r}`,{method:"POST",body:n},{baseUrl:e});return Response.json(a,{status:i})}}}}function et(o={}){let e=o.baseUrl;return {read:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("path")||"",n=s.searchParams.get("sessionId"),a=s.searchParams.get("sandboxId"),i=`/coder/files/read?path=${encodeURIComponent(r)}`;n&&(i+=`&sessionId=${encodeURIComponent(n)}`),a&&(i+=`&sandboxId=${encodeURIComponent(a)}`);let{data:d,status:u}=await l(i,{},{baseUrl:e});return Response.json(d,{status:u})}},write:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/files/write",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}},list:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("path")||".",n=s.searchParams.get("recursive"),a=s.searchParams.get("maxDepth"),i=s.searchParams.get("sessionId"),d=s.searchParams.get("sandboxId"),u=`/coder/files/list?path=${encodeURIComponent(r)}`;n&&(u+=`&recursive=${n}`),a&&(u+=`&maxDepth=${a}`),i&&(u+=`&sessionId=${encodeURIComponent(i)}`),d&&(u+=`&sandboxId=${encodeURIComponent(d)}`);let{data:g,status:m}=await l(u,{},{baseUrl:e});return Response.json(g,{status:m})}},search:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("pattern")||"",n=s.searchParams.get("path"),a=s.searchParams.get("filePattern"),i=s.searchParams.get("sessionId"),d=s.searchParams.get("sandboxId"),u=`/coder/files/search?pattern=${encodeURIComponent(r)}`;n&&(u+=`&path=${encodeURIComponent(n)}`),a&&(u+=`&filePattern=${encodeURIComponent(a)}`),i&&(u+=`&sessionId=${encodeURIComponent(i)}`),d&&(u+=`&sandboxId=${encodeURIComponent(d)}`);let{data:g,status:m}=await l(u,{},{baseUrl:e});return Response.json(g,{status:m})}},diff:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/files/diff",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}}}}function tt(o={}){let e=o.baseUrl;return {create:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/sandbox",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})}},get:{GET:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/coder/sandbox/${r}`,{},{baseUrl:e});return Response.json(n,{status:a})}},exec:{POST:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").slice(-2)[0],n=await t.json(),a=await k(`/coder/sandbox/${r}/exec`,{method:"POST",body:n,stream:n.stream},{baseUrl:e});if((a.headers.get("content-type")||"").includes("text/event-stream")&&a.body)return new Response(a.body,{status:a.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let d=await a.json();return Response.json(d,{status:a.status})}},destroy:{DELETE:async(t,s)=>{let r=s?.params?.id||new URL(t.url).pathname.split("/").pop(),{data:n,status:a}=await l(`/coder/sandbox/${r}`,{method:"DELETE"},{baseUrl:e});return Response.json(n,{status:a})}}}}function st(o={}){let e=o.baseUrl;return {POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/coder/exec",{method:"POST",body:s},{baseUrl:e});return Response.json(r,{status:n})},stream:{POST:async t=>{let s=await t.json(),r=await k("/coder/exec/stream",{method:"POST",body:s,stream:true},{baseUrl:e});if(r.body)return new Response(r.body,{status:r.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let n=await r.json();return Response.json(n,{status:r.status})}}}}function y(o,e){if(!o||typeof o!="string")throw new Error(`Missing required parameter: ${e}`);if(!/^[\w.\-]+$/.test(o))throw new Error(`Invalid ${e}: contains disallowed characters`);return o}function w(o,e){let t={};if(o.extractAuth){let s=o.extractAuth(e);s&&(t.Authorization=`Bearer ${s}`);}else {let s=e.headers.get("Authorization");s&&(t.Authorization=s);}return t}function rt(o={}){let e=o.baseUrl;return {GET:async t=>{let{data:s,status:r}=await l("/api/v2/stacks",{headers:w(o,t)},{baseUrl:e});return Response.json(s,{status:r})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await l("/api/v2/stacks",{method:"POST",body:s,headers:w(o,t)},{baseUrl:e});return Response.json(r,{status:n})}}}function nt(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),{data:n,status:a}=await l(`/api/v2/stacks/${r}`,{headers:w(o,t)},{baseUrl:e});return Response.json(n,{status:a})},POST:async()=>Response.json({error:"Method not allowed"},{status:405}),PUT:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=await t.json(),{data:a,status:i}=await l(`/api/v2/stacks/${r}`,{method:"PATCH",body:n,headers:w(o,t)},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),{data:n,status:a}=await l(`/api/v2/stacks/${r}`,{method:"DELETE",headers:w(o,t)},{baseUrl:e});return Response.json(n,{status:a})}}}function at(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),{data:n,status:a}=await l(`/api/v2/stacks/${r}/keys`,{headers:w(o,t)},{baseUrl:e});return Response.json(n,{status:a})},POST:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=await t.json(),{data:a,status:i}=await l(`/api/v2/stacks/${r}/keys`,{method:"POST",body:n,headers:w(o,t)},{baseUrl:e});return Response.json(a,{status:i})},DELETE:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=y(s?.params?.keyId,"keyId"),{data:a,status:i}=await l(`/api/v2/stacks/${r}/keys/${n}`,{method:"DELETE",headers:w(o,t)},{baseUrl:e});return Response.json(a,{status:i})}}}function ot(o={}){let e=o.baseUrl;return {GET:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=new URL(t.url),a=new URLSearchParams,i=n.searchParams.get("limit"),d=n.searchParams.get("offset"),u=n.searchParams.get("role");i&&a.set("limit",i),d&&a.set("offset",d),u&&a.set("role",u);let g=a.toString()?`?${a}`:"",{data:m,status:f}=await l(`/api/v2/stacks/${r}/members${g}`,{headers:w(o,t)},{baseUrl:e});return Response.json(m,{status:f})},stats:{GET:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),{data:n,status:a}=await l(`/api/v2/stacks/${r}/members/stats`,{headers:w(o,t)},{baseUrl:e});return Response.json(n,{status:a})}},updateRole:{PATCH:async(t,s)=>{let r=y(s?.params?.stackId,"stackId"),n=y(s?.params?.userId,"userId"),a=await t.json(),{data:i,status:d}=await l(`/api/v2/stacks/${r}/members/${encodeURIComponent(n)}/role`,{method:"PATCH",body:a,headers:w(o,t)},{baseUrl:e});return Response.json(i,{status:d})}}}}var Y={text_input:1,image_input:2,file_input:4,audio_input:8,video_input:16,music_input:32,text_output:64,image_output:128,audio_output:256,video_output:512,embeddings_output:1024,music_output:2048,skills:4096,loops:8192,tools:16384,pipelines:32768,training:65536},it=131071;function ct(o){let e=0;for(let[t,s]of Object.entries(Y))o[t]&&(e|=s);return e}function dt(o){let e={};for(let[t,s]of Object.entries(Y))e[t]=(o&s)!==0;return e}export{it as ALL_CAPABILITIES_BITMASK,A as AgentsClient,N as BillingClient,Y as CAPABILITY_BITS,P as CHAT_TASKS_PREFIX,L as CoderClient,W as ComponentStreamAdapter,T as DEFAULT_MAGMA_RPC_URL,h as DEFAULT_TASK_NETWORK_URL,O as FilesClient,p as JSON_HEADERS,I as MCPClient,U as MagmaClient,M as NetworkClient,D as PointsClient,K as SSEWriter,x as SSE_HEADERS,j as SkillsClient,E as SocialClient,q as StackManagementClient,c as StacksSDKError,b as TASK_PREFIX,J as TASK_TTL,H as TaskManager,$ as TaskNetworkClient,v as UserClient,_ as WidgetsClient,Ce as agentsClient,_e as billingClient,dt as bitmaskToCapabilities,ct as capabilitiesToBitmask,Ue as coderClient,He as createAgentDetailRoutes,Ke as createAgentExecuteRoute,Ne as createAgentRoutes,We as createAgentToggleRoutes,ne as createAgentsClient,ge as createBillingClient,le as createCoderClient,st as createCoderExecRoutes,Qe as createCoderExecuteRoute,et as createCoderFilesRoutes,tt as createCoderSandboxRoutes,Xe as createCoderSessionDetailRoutes,Ve as createCoderSessionRoutes,Ze as createCoderToolsRoutes,Fe as createComponentStreamAdapter,ie as createFilesClient,Ye as createImaginationRoutes,ee as createMCPClient,Z as createMagmaClient,me as createNetworkClient,de as createPointsClient,Me as createProxyHandler,je as createSSEResponse,De as createSSEWriter,Je as createSkillDetailRoutes,Be as createSkillRoutes,ce as createSkillsClient,re as createSocialClient,nt as createStackDetailRoutes,at as createStackKeysRoutes,pe as createStackManagementClient,ot as createStackMembersRoutes,rt as createStackRoutes,ve as createTaskManager,X as createTaskNetworkClient,oe as createUserClient,ze as createWidgetDetailRoutes,Ge as createWidgetRoutes,ae as createWidgetsClient,qe as extractToolResults,Pe as filesClient,l as forwardJSON,k as forwardRequest,z as generateCID,G as generateUUID,se as getMessageByErrorCode,Le as hasToolCalls,we as magmaClient,Se as mcpClient,Ee as networkClient,ye as parseSSELine,Oe as parseSSEStream,$e as pointsClient,fe as retry,xe as skillsClient,Q as sleep,ke as socialClient,Ie as stackManagementClient,he as taskNetworkClient,Te as userClient,te as visibilityBySurface,Re as widgetsClient};
|
package/dist/types/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as ALL_CAPABILITIES_BITMASK, c as ActionProof, d as AddPointsInput, e as Agent, f as AgentCreateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, j as AgentResponse, k as AgentTrigger, l as AgentUpdateInput, m as AgentWorkflow, n as AgentWorkflowEdge, o as AgentWorkflowNode, p as AgentsClientConfig, q as AgentsListResponse, r as AllowlistConfig, s as AllowlistMode, t as AllowlistUpdateInput, u as AuthMetrics, B as BillingClientConfig, v as BillingPlan, w as BillingPlansResponse, x as BillingPortalResponse, y as BillingState, z as BillingTier, C as CAPABILITY_BITS, D as CapabilityKey, E as ChatCompletionChunk, F as ChatCompletionRequest, G as ChatCompletionResponse, H as CommentResponse, I as CommentsResponse, J as ConfigureOAuthInput, K as ConfigureStripeInput, L as ConfigureWeb3Input, M as ConsensusStateSummary, N as ConsensusStatus, O as ContextDomain, P as ContextResponse, Q as ContextsListResponse, R as CreateCheckoutSessionResponse, S as CreateContextInput, U as CreateDelegationInput, V as CreateDomainInput, W as CreateKeyResponse, X as CreatePostInput, Y as CreatePostResponse, Z as CreateStackRequest, _ as Delegation, $ as DelegationChainLink, a0 as DelegationFilters, a1 as DelegationResponse, a2 as DelegationScope, a3 as DelegationsListResponse, a4 as DomainResponse, a5 as DomainsListResponse, a6 as FeedResponse, a7 as FileUploadResponse, a8 as FilesClientConfig, a9 as HistoryFilters, aa as HistoryResponse, ab as ImaginationCharacter, ac as ImaginationMetadata, ad as ImaginationSource, ae as InitNetworkResponse, af as LeaderStatus, ag as LikeCheckResponse, ah as LikeResponse, ai as MCPContent, aj as MCPMessage, ak as MCPSession, al as MCPSessionConfig, am as MCPToolResult, an as MPCNode, ao as MagmaFile, ap as MediaType, aq as Message, ar as MeteredUsage, as as ModelLayerInfo, at as ModelLayersResponse, au as NetworkClientConfig, av as NetworkStatus, br as Orientation, aw as PaginationMeta, ax as PaymentRequiredResponse, ay as PointBalance, az as PointContext, aA as PointRecord, aB as PointRecordResponse, aC as PointSpend, aD as PointSpendResponse, aE as PointsClientConfig, aF as PostResponse, aG as ProfileResponse, aH as RemixesResponse, aI as Skill, aJ as SkillCreateInput, bp as SkillMapPromptResponse, bo as SkillMapResponse, aK as SkillResponse, bq as SkillSummaryResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aO as SocialAuthor, aP as SocialClientConfig, aQ as SocialComment, aR as SocialPost, aS as SocialRemix, aT as SpendDestination, aU as SpendPointsInput, aV as StackCapabilities, aW as StackConfig, aX as StackKeyInfo, aY as StackKeysListResponse, aZ as StackListResponse, a_ as StackManagementClientConfig, a$ as StackMember, b0 as StackMemberStats, b1 as StackModelAlias, b2 as StackOAuthProvider, b3 as StackResponse, b4 as StackStripeProvider, b5 as StackWeb3Provider, b6 as TaskPayload, b7 as TaskResponse, a as TaskState, b as TaskStatus, T as TaskType, b8 as UsageRecord, b9 as UserClientConfig, ba as UserProfile, bb as UserProfileResponse, bc as UserProfileUpdateInput, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bg as WidgetSystemPromptResponse, bh as WidgetUpdateInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bk as WorkflowData, bl as bitmaskToCapabilities, bm as capabilitiesToBitmask } from '../billing-
|
|
1
|
+
export { A as ALL_CAPABILITIES_BITMASK, c as ActionProof, d as AddPointsInput, e as Agent, f as AgentCreateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, j as AgentResponse, k as AgentTrigger, l as AgentUpdateInput, m as AgentWorkflow, n as AgentWorkflowEdge, o as AgentWorkflowNode, p as AgentsClientConfig, q as AgentsListResponse, r as AllowlistConfig, s as AllowlistMode, t as AllowlistUpdateInput, u as AuthMetrics, B as BillingClientConfig, v as BillingPlan, w as BillingPlansResponse, x as BillingPortalResponse, y as BillingState, z as BillingTier, C as CAPABILITY_BITS, D as CapabilityKey, E as ChatCompletionChunk, F as ChatCompletionRequest, G as ChatCompletionResponse, H as CommentResponse, I as CommentsResponse, J as ConfigureOAuthInput, K as ConfigureStripeInput, L as ConfigureWeb3Input, M as ConsensusStateSummary, N as ConsensusStatus, O as ContextDomain, P as ContextResponse, Q as ContextsListResponse, R as CreateCheckoutSessionResponse, S as CreateContextInput, U as CreateDelegationInput, V as CreateDomainInput, W as CreateKeyResponse, X as CreatePostInput, Y as CreatePostResponse, Z as CreateStackRequest, _ as Delegation, $ as DelegationChainLink, a0 as DelegationFilters, a1 as DelegationResponse, a2 as DelegationScope, a3 as DelegationsListResponse, a4 as DomainResponse, a5 as DomainsListResponse, a6 as FeedResponse, a7 as FileUploadResponse, a8 as FilesClientConfig, a9 as HistoryFilters, aa as HistoryResponse, ab as ImaginationCharacter, ac as ImaginationMetadata, ad as ImaginationSource, ae as InitNetworkResponse, af as LeaderStatus, ag as LikeCheckResponse, ah as LikeResponse, ai as MCPContent, aj as MCPMessage, ak as MCPSession, al as MCPSessionConfig, am as MCPToolResult, an as MPCNode, ao as MagmaFile, ap as MediaType, aq as Message, ar as MeteredUsage, as as ModelLayerInfo, at as ModelLayersResponse, au as NetworkClientConfig, av as NetworkStatus, br as Orientation, aw as PaginationMeta, bs as PaymentMethod, ax as PaymentRequiredResponse, ay as PointBalance, az as PointContext, aA as PointRecord, aB as PointRecordResponse, aC as PointSpend, aD as PointSpendResponse, aE as PointsClientConfig, aF as PostResponse, aG as ProfileResponse, aH as RemixesResponse, aI as Skill, aJ as SkillCreateInput, bp as SkillMapPromptResponse, bo as SkillMapResponse, aK as SkillResponse, bq as SkillSummaryResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aO as SocialAuthor, aP as SocialClientConfig, aQ as SocialComment, aR as SocialPost, aS as SocialRemix, bt as SolPrepaidResult, bu as SolSubscriptionResult, aT as SpendDestination, aU as SpendPointsInput, aV as StackCapabilities, aW as StackConfig, aX as StackKeyInfo, aY as StackKeysListResponse, aZ as StackListResponse, a_ as StackManagementClientConfig, a$ as StackMember, b0 as StackMemberStats, b1 as StackModelAlias, b2 as StackOAuthProvider, b3 as StackResponse, b4 as StackStripeProvider, b5 as StackWeb3Provider, b6 as TaskPayload, b7 as TaskResponse, a as TaskState, b as TaskStatus, T as TaskType, bv as TopupResult, b8 as UsageRecord, b9 as UserClientConfig, ba as UserProfile, bb as UserProfileResponse, bc as UserProfileUpdateInput, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bg as WidgetSystemPromptResponse, bh as WidgetUpdateInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bk as WorkflowData, bl as bitmaskToCapabilities, bm as capabilitiesToBitmask } from '../billing-BqscteyZ.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Coder type definitions
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as ALL_CAPABILITIES_BITMASK, c as ActionProof, d as AddPointsInput, e as Agent, f as AgentCreateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, j as AgentResponse, k as AgentTrigger, l as AgentUpdateInput, m as AgentWorkflow, n as AgentWorkflowEdge, o as AgentWorkflowNode, p as AgentsClientConfig, q as AgentsListResponse, r as AllowlistConfig, s as AllowlistMode, t as AllowlistUpdateInput, u as AuthMetrics, B as BillingClientConfig, v as BillingPlan, w as BillingPlansResponse, x as BillingPortalResponse, y as BillingState, z as BillingTier, C as CAPABILITY_BITS, D as CapabilityKey, E as ChatCompletionChunk, F as ChatCompletionRequest, G as ChatCompletionResponse, H as CommentResponse, I as CommentsResponse, J as ConfigureOAuthInput, K as ConfigureStripeInput, L as ConfigureWeb3Input, M as ConsensusStateSummary, N as ConsensusStatus, O as ContextDomain, P as ContextResponse, Q as ContextsListResponse, R as CreateCheckoutSessionResponse, S as CreateContextInput, U as CreateDelegationInput, V as CreateDomainInput, W as CreateKeyResponse, X as CreatePostInput, Y as CreatePostResponse, Z as CreateStackRequest, _ as Delegation, $ as DelegationChainLink, a0 as DelegationFilters, a1 as DelegationResponse, a2 as DelegationScope, a3 as DelegationsListResponse, a4 as DomainResponse, a5 as DomainsListResponse, a6 as FeedResponse, a7 as FileUploadResponse, a8 as FilesClientConfig, a9 as HistoryFilters, aa as HistoryResponse, ab as ImaginationCharacter, ac as ImaginationMetadata, ad as ImaginationSource, ae as InitNetworkResponse, af as LeaderStatus, ag as LikeCheckResponse, ah as LikeResponse, ai as MCPContent, aj as MCPMessage, ak as MCPSession, al as MCPSessionConfig, am as MCPToolResult, an as MPCNode, ao as MagmaFile, ap as MediaType, aq as Message, ar as MeteredUsage, as as ModelLayerInfo, at as ModelLayersResponse, au as NetworkClientConfig, av as NetworkStatus, br as Orientation, aw as PaginationMeta, ax as PaymentRequiredResponse, ay as PointBalance, az as PointContext, aA as PointRecord, aB as PointRecordResponse, aC as PointSpend, aD as PointSpendResponse, aE as PointsClientConfig, aF as PostResponse, aG as ProfileResponse, aH as RemixesResponse, aI as Skill, aJ as SkillCreateInput, bp as SkillMapPromptResponse, bo as SkillMapResponse, aK as SkillResponse, bq as SkillSummaryResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aO as SocialAuthor, aP as SocialClientConfig, aQ as SocialComment, aR as SocialPost, aS as SocialRemix, aT as SpendDestination, aU as SpendPointsInput, aV as StackCapabilities, aW as StackConfig, aX as StackKeyInfo, aY as StackKeysListResponse, aZ as StackListResponse, a_ as StackManagementClientConfig, a$ as StackMember, b0 as StackMemberStats, b1 as StackModelAlias, b2 as StackOAuthProvider, b3 as StackResponse, b4 as StackStripeProvider, b5 as StackWeb3Provider, b6 as TaskPayload, b7 as TaskResponse, a as TaskState, b as TaskStatus, T as TaskType, b8 as UsageRecord, b9 as UserClientConfig, ba as UserProfile, bb as UserProfileResponse, bc as UserProfileUpdateInput, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bg as WidgetSystemPromptResponse, bh as WidgetUpdateInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bk as WorkflowData, bl as bitmaskToCapabilities, bm as capabilitiesToBitmask } from '../billing-
|
|
1
|
+
export { A as ALL_CAPABILITIES_BITMASK, c as ActionProof, d as AddPointsInput, e as Agent, f as AgentCreateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, j as AgentResponse, k as AgentTrigger, l as AgentUpdateInput, m as AgentWorkflow, n as AgentWorkflowEdge, o as AgentWorkflowNode, p as AgentsClientConfig, q as AgentsListResponse, r as AllowlistConfig, s as AllowlistMode, t as AllowlistUpdateInput, u as AuthMetrics, B as BillingClientConfig, v as BillingPlan, w as BillingPlansResponse, x as BillingPortalResponse, y as BillingState, z as BillingTier, C as CAPABILITY_BITS, D as CapabilityKey, E as ChatCompletionChunk, F as ChatCompletionRequest, G as ChatCompletionResponse, H as CommentResponse, I as CommentsResponse, J as ConfigureOAuthInput, K as ConfigureStripeInput, L as ConfigureWeb3Input, M as ConsensusStateSummary, N as ConsensusStatus, O as ContextDomain, P as ContextResponse, Q as ContextsListResponse, R as CreateCheckoutSessionResponse, S as CreateContextInput, U as CreateDelegationInput, V as CreateDomainInput, W as CreateKeyResponse, X as CreatePostInput, Y as CreatePostResponse, Z as CreateStackRequest, _ as Delegation, $ as DelegationChainLink, a0 as DelegationFilters, a1 as DelegationResponse, a2 as DelegationScope, a3 as DelegationsListResponse, a4 as DomainResponse, a5 as DomainsListResponse, a6 as FeedResponse, a7 as FileUploadResponse, a8 as FilesClientConfig, a9 as HistoryFilters, aa as HistoryResponse, ab as ImaginationCharacter, ac as ImaginationMetadata, ad as ImaginationSource, ae as InitNetworkResponse, af as LeaderStatus, ag as LikeCheckResponse, ah as LikeResponse, ai as MCPContent, aj as MCPMessage, ak as MCPSession, al as MCPSessionConfig, am as MCPToolResult, an as MPCNode, ao as MagmaFile, ap as MediaType, aq as Message, ar as MeteredUsage, as as ModelLayerInfo, at as ModelLayersResponse, au as NetworkClientConfig, av as NetworkStatus, br as Orientation, aw as PaginationMeta, bs as PaymentMethod, ax as PaymentRequiredResponse, ay as PointBalance, az as PointContext, aA as PointRecord, aB as PointRecordResponse, aC as PointSpend, aD as PointSpendResponse, aE as PointsClientConfig, aF as PostResponse, aG as ProfileResponse, aH as RemixesResponse, aI as Skill, aJ as SkillCreateInput, bp as SkillMapPromptResponse, bo as SkillMapResponse, aK as SkillResponse, bq as SkillSummaryResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aO as SocialAuthor, aP as SocialClientConfig, aQ as SocialComment, aR as SocialPost, aS as SocialRemix, bt as SolPrepaidResult, bu as SolSubscriptionResult, aT as SpendDestination, aU as SpendPointsInput, aV as StackCapabilities, aW as StackConfig, aX as StackKeyInfo, aY as StackKeysListResponse, aZ as StackListResponse, a_ as StackManagementClientConfig, a$ as StackMember, b0 as StackMemberStats, b1 as StackModelAlias, b2 as StackOAuthProvider, b3 as StackResponse, b4 as StackStripeProvider, b5 as StackWeb3Provider, b6 as TaskPayload, b7 as TaskResponse, a as TaskState, b as TaskStatus, T as TaskType, bv as TopupResult, b8 as UsageRecord, b9 as UserClientConfig, ba as UserProfile, bb as UserProfileResponse, bc as UserProfileUpdateInput, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bg as WidgetSystemPromptResponse, bh as WidgetUpdateInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bk as WorkflowData, bl as bitmaskToCapabilities, bm as capabilitiesToBitmask } from '../billing-BqscteyZ.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Coder type definitions
|
package/package.json
CHANGED
package/src/clients/billing.ts
CHANGED
|
@@ -142,6 +142,46 @@ export class BillingClient {
|
|
|
142
142
|
async hasPaymentMethod(stackId: string, identityId: string): Promise<{ has_payment_method: boolean; card_last_four?: string; card_brand?: string }> {
|
|
143
143
|
return this.request('GET', `/stacks/${stackId}/identities/${identityId}/billing/payment-method`);
|
|
144
144
|
}
|
|
145
|
+
|
|
146
|
+
// =========================================================================
|
|
147
|
+
// SOL Payment Methods (additive — Stripe methods above remain unchanged)
|
|
148
|
+
// =========================================================================
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Subscribe to a plan using SOL payment.
|
|
152
|
+
* Client must build and sign the SOL transaction first,
|
|
153
|
+
* then pass the on-chain tx signature here for verification.
|
|
154
|
+
*/
|
|
155
|
+
async subscribeSol(
|
|
156
|
+
stackId: string,
|
|
157
|
+
planId: string,
|
|
158
|
+
txSignature: string,
|
|
159
|
+
): Promise<{ subscription: { id: string; planId: string; planName: string; status: string; tokensGranted: number } }> {
|
|
160
|
+
return this.request('POST', `/stacks/${stackId}/subscribe-sol`, { planId, txSignature });
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* One-time prepaid credit via SOL payment.
|
|
165
|
+
*/
|
|
166
|
+
async prepaidSol(
|
|
167
|
+
stackId: string,
|
|
168
|
+
amountCents: number,
|
|
169
|
+
txSignature: string,
|
|
170
|
+
scope?: 'global' | 'stack',
|
|
171
|
+
): Promise<{ alreadyCredited: boolean; tokensCredited?: number; amountCents?: number; paymentRef?: string }> {
|
|
172
|
+
return this.request('POST', `/stacks/${stackId}/prepaid-sol`, { amountCents, txSignature, scope });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Top up account via x402 payment proof (SOL or Stripe).
|
|
177
|
+
*/
|
|
178
|
+
async topup(
|
|
179
|
+
amountCents: number,
|
|
180
|
+
paymentMethod: 'solana' | 'stripe',
|
|
181
|
+
paymentRef: string,
|
|
182
|
+
): Promise<{ success: boolean; tokensCredited: number; tokenBalance: number }> {
|
|
183
|
+
return this.request('POST', '/account/topup', { amount_cents: amountCents, payment_method: paymentMethod, payment_ref: paymentRef });
|
|
184
|
+
}
|
|
145
185
|
}
|
|
146
186
|
|
|
147
187
|
/**
|
package/src/types/billing.ts
CHANGED
|
@@ -85,3 +85,37 @@ export interface BillingClientConfig {
|
|
|
85
85
|
baseUrl?: string;
|
|
86
86
|
authToken?: string;
|
|
87
87
|
}
|
|
88
|
+
|
|
89
|
+
// SOL payment types (additive — Stripe types above remain unchanged)
|
|
90
|
+
|
|
91
|
+
export type PaymentMethod = 'stripe' | 'solana';
|
|
92
|
+
|
|
93
|
+
export interface SolSubscriptionResult {
|
|
94
|
+
subscription: {
|
|
95
|
+
id: string;
|
|
96
|
+
planId: string;
|
|
97
|
+
planName: string;
|
|
98
|
+
status: string;
|
|
99
|
+
tokensGranted: number;
|
|
100
|
+
periodEnd: number;
|
|
101
|
+
paymentMethod: 'solana';
|
|
102
|
+
txSignature: string;
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface SolPrepaidResult {
|
|
107
|
+
alreadyCredited: boolean;
|
|
108
|
+
tokensCredited?: number;
|
|
109
|
+
amountCents?: number;
|
|
110
|
+
paymentRef?: string;
|
|
111
|
+
paymentMethod: 'solana';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface TopupResult {
|
|
115
|
+
success: boolean;
|
|
116
|
+
tokensCredited: number;
|
|
117
|
+
amountCents: number;
|
|
118
|
+
paymentMethod: PaymentMethod;
|
|
119
|
+
paymentRef: string;
|
|
120
|
+
tokenBalance: number;
|
|
121
|
+
}
|