@stacknet/stacks 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{billing-BqscteyZ.d.cts → billing-eQZIWeNW.d.cts} +2 -0
- package/dist/{billing-BqscteyZ.d.ts → billing-eQZIWeNW.d.ts} +2 -0
- package/dist/clients/index.cjs +4 -4
- package/dist/clients/index.d.cts +4 -1
- package/dist/clients/index.d.ts +4 -1
- package/dist/clients/index.js +4 -4
- package/dist/{index-DVzKiF_0.d.cts → index-B_dUFmAg.d.cts} +31 -6
- package/dist/{index-DVzKiF_0.d.ts → index-B_dUFmAg.d.ts} +31 -6
- package/dist/index.cjs +12 -16
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +12 -16
- package/dist/proxy/index.cjs +2 -2
- package/dist/proxy/index.d.cts +1 -1
- package/dist/proxy/index.d.ts +1 -1
- package/dist/proxy/index.js +2 -2
- package/dist/streaming/index.cjs +8 -12
- package/dist/streaming/index.js +8 -12
- package/dist/types/index.d.cts +1 -1
- package/dist/types/index.d.ts +1 -1
- package/package.json +1 -1
- package/src/clients/agents.ts +23 -6
- package/src/managers/task-manager.ts +25 -3
- package/src/proxy/forwarder.ts +105 -16
- package/src/proxy/route-handlers.ts +273 -116
- package/src/streaming/sse.ts +65 -40
- package/src/types/agent.ts +2 -0
|
@@ -4,7 +4,13 @@
|
|
|
4
4
|
interface ForwarderConfig {
|
|
5
5
|
baseUrl?: string;
|
|
6
6
|
defaultHeaders?: Record<string, string>;
|
|
7
|
+
/** Request timeout in milliseconds. Applied via AbortSignal to every
|
|
8
|
+
* outbound fetch. Default: 30_000 (30s). Previously declared but not
|
|
9
|
+
* wired — an upstream hang would leak file descriptors indefinitely. */
|
|
7
10
|
timeout?: number;
|
|
11
|
+
/** Hard cap on inbound JSON body size (bytes) read by `createProxyHandler`.
|
|
12
|
+
* Requests larger than this are rejected with 413. Default: 1 MiB. */
|
|
13
|
+
maxBodyBytes?: number;
|
|
8
14
|
}
|
|
9
15
|
interface RequestOptions {
|
|
10
16
|
method?: string;
|
|
@@ -25,19 +31,39 @@ declare function forwardJSON<T = unknown>(path: string, options?: RequestOptions
|
|
|
25
31
|
status: number;
|
|
26
32
|
}>;
|
|
27
33
|
/**
|
|
28
|
-
* Create a proxy handler that forwards requests
|
|
34
|
+
* Create a proxy handler that forwards requests.
|
|
35
|
+
*
|
|
36
|
+
* SECURITY: only a small whitelist of inbound headers is forwarded (see
|
|
37
|
+
* FORWARDABLE_REQUEST_HEADERS). Everything else — including `cookie`,
|
|
38
|
+
* `x-forwarded-for`, `host` — is stripped so a caller cannot poison the
|
|
39
|
+
* upstream's view of the request or smuggle the consumer app's cookies to
|
|
40
|
+
* a third-party StackNet endpoint.
|
|
29
41
|
*/
|
|
30
42
|
declare function createProxyHandler(path: string | ((req: Request) => string), config?: ForwarderConfig): (request: Request) => Promise<Response>;
|
|
31
43
|
|
|
32
44
|
/**
|
|
33
45
|
* Next.js API Route Handler Factories
|
|
34
46
|
*
|
|
35
|
-
* Create pre-configured route handlers for common patterns
|
|
47
|
+
* Create pre-configured route handlers for common patterns.
|
|
48
|
+
*
|
|
49
|
+
* SECURITY NOTES
|
|
50
|
+
* - Every path-position parameter is run through `validateId` before being
|
|
51
|
+
* interpolated into the upstream path. Without this, characters like `?`,
|
|
52
|
+
* `&`, `#`, or `/` in an id would smuggle extra query params or escape
|
|
53
|
+
* the intended namespace.
|
|
54
|
+
* - Every factory supports `extractAuth`; the forwarder receives an
|
|
55
|
+
* `Authorization` header so the upstream can attribute the request to
|
|
56
|
+
* the real caller instead of treating it as anonymous.
|
|
36
57
|
*/
|
|
37
58
|
|
|
38
59
|
interface RouteHandlerConfig extends ForwarderConfig {
|
|
39
60
|
requireAuth?: boolean;
|
|
40
61
|
enrichResponse?: (data: unknown) => Promise<unknown>;
|
|
62
|
+
/** Extract the caller's bearer token from the incoming Request and
|
|
63
|
+
* forward it upstream as `Authorization: Bearer <token>`. If unset,
|
|
64
|
+
* the handler passes through any inbound `Authorization` header
|
|
65
|
+
* verbatim. Without one of these the upstream sees no auth at all. */
|
|
66
|
+
extractAuth?: (request: Request) => string | null;
|
|
41
67
|
}
|
|
42
68
|
type RouteHandler = (request: Request, context?: {
|
|
43
69
|
params?: Record<string, string>;
|
|
@@ -48,6 +74,9 @@ interface CRUDRouteHandlers {
|
|
|
48
74
|
PUT?: RouteHandler;
|
|
49
75
|
DELETE?: RouteHandler;
|
|
50
76
|
}
|
|
77
|
+
/** Back-compat: `StackRouteHandlerConfig` used to be distinct; now every
|
|
78
|
+
* factory accepts `extractAuth`, so the two configs are identical. */
|
|
79
|
+
type StackRouteHandlerConfig = RouteHandlerConfig;
|
|
51
80
|
/**
|
|
52
81
|
* Create agent route handlers
|
|
53
82
|
*/
|
|
@@ -166,10 +195,6 @@ declare function createCoderExecRoutes(config?: RouteHandlerConfig): {
|
|
|
166
195
|
POST: RouteHandler;
|
|
167
196
|
};
|
|
168
197
|
};
|
|
169
|
-
interface StackRouteHandlerConfig extends RouteHandlerConfig {
|
|
170
|
-
/** Extract JWT from incoming request and forward as Authorization header */
|
|
171
|
-
extractAuth?: (request: Request) => string | null;
|
|
172
|
-
}
|
|
173
198
|
/**
|
|
174
199
|
* Create stack CRUD route handlers (list + create)
|
|
175
200
|
*/
|
package/dist/index.cjs
CHANGED
|
@@ -1,17 +1,13 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
`);
|
|
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
|
-
`);
|
|
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
|
-
`);s=i.pop()||"";for(let
|
|
7
|
-
`),
|
|
8
|
-
`),
|
|
9
|
-
`);let
|
|
1
|
+
'use strict';var T="https://stacknet.magma-rpc.com",w=T;var x="http://geoff.magma-rpc.com",C="task:",P="chat:tasks:",G=86400*7,U={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"},g={"Content-Type":"application/json"};var E=class{baseUrl;apiKey;timeout;constructor(e={}){this.baseUrl=(e.baseUrl||w).replace(/\/$/,""),this.apiKey=e.apiKey,this.timeout=e.timeout||6e4;}async*chatCompletions(e){let t=e.messages.filter(n=>n.role==="user"),s=t[t.length-1]?.content||"",r=await this.submitTask({type:"ai-prompt",model:e.model,prompt:s,sessionId:e.sessionId,temperature:e.temperature,maxTokens:e.max_tokens,stream:true});yield*this.streamTaskResults(r,e.model);}async submitTask(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Task submission failed: ${n}`)}let s=await t.json(),r=s.taskId||s.id;if(!r)throw new Error("Task submission did not return a taskId");return r}async submitTaskFull(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let r=await t.text();throw new Error(`Task submission failed: ${r}`)}let s=await t.json();return {taskId:s.taskId||s.id,output:s.output,status:s.status}}async getTask(e){let t=await fetch(`${this.baseUrl}/tasks/${e}`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Failed to get task: ${t.statusText}`);return t.json()}async*streamTaskResults(e,t){let s=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!s.ok)throw new Error(`Stream failed: ${s.statusText}`);if(!s.body)throw new Error("Response body is null");let r=s.body.getReader(),n=new TextDecoder,o="",i="",c=Math.floor(Date.now()/1e3);try{for(;;){let{done:l,value:f}=await r.read();if(l){yield {id:e,object:"chat.completion.chunk",created:c,model:t,choices:[{index:0,delta:{},finish_reason:"stop"}]};break}o+=n.decode(f,{stream:!0});let m=o.split(`
|
|
2
|
+
`);o=m.pop()||"";for(let S of m)if(S.startsWith("data: "))try{let b=JSON.parse(S.slice(6));if(Array.isArray(b)&&b.length>0){let $=b[0].result||"";if($&&$!==i){let Q=$.substring(i.length);i=$,Q&&(yield {id:e,object:"chat.completion.chunk",created:c,model:t,choices:[{index:0,delta:{role:"assistant",content:Q},finish_reason:null}]});}}}catch{}}}finally{r.releaseLock();}}async*streamTaskRaw(e){let t=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Stream failed: ${t.statusText}`);if(!t.body)throw new Error("Response body is null");let s=t.body.getReader(),r=new TextDecoder,n="";try{for(;;){let{done:o,value:i}=await s.read();if(o)break;n+=r.decode(i,{stream:!0});let c=n.split(`
|
|
3
|
+
`);n=c.pop()||"";for(let l of c)if(l.startsWith("data: "))try{yield JSON.parse(l.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 Z(a){return new E(a)}var be=Z();function z(){return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{let e=Math.random()*16|0;return (a==="x"?e:e&3|8).toString(16)})}async function Y(a){let e=await crypto.subtle.digest("SHA-256",a);return `baf${Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,52)}`}function ee(a){return new Promise(e=>setTimeout(e,a))}async function ke(a,e={}){let{maxAttempts:t=3,initialDelay:s=1e3,maxDelay:r=3e4,backoffFactor:n=2}=e,o,i=s;for(let c=1;c<=t;c++)try{return await a()}catch(l){if(o=l,c===t)break;await ee(i),i=Math.min(i*n,r);}throw o}function Ce(a){return !a||a.startsWith(":")?null:a.startsWith("event:")?{event:a.slice(6).trim()}:a.startsWith("data:")?{data:a.slice(5).trim()}:null}var I=class{baseUrl;localServerUrl;constructor(e={}){this.baseUrl=e.baseUrl||x,this.localServerUrl=e.localServerUrl||w;}async uploadFile(e){let t=await e.arrayBuffer(),s=await Y(t),r=this.arrayBufferToBase64(t);return typeof localStorage<"u"&&localStorage.setItem(`file:${s}`,JSON.stringify({cid:s,name:e.name,type:e.type,size:e.size,data:r})),{cid:s,name:e.name,size:e.size,type:e.type,url:`data:${e.type};base64,${r}`}}async uploadText(e,t){let s=new Blob([e],{type:"text/plain"}),r=new File([s],t,{type:"text/plain"});return this.uploadFile(r)}async storeImagination(e){let t=e.createdBy||"anonymous",r=(await fetch(`${this.localServerUrl}/imaginations/${e.id}`)).ok,n={id:e.id,title:e.title,sources:e.sources,summary:e.summary,character:e.character,workflow:e.workflow,is_public:e.is_public||false,creator_mid:t};if(r){let o=await fetch(`${this.localServerUrl}/imaginations/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to update imagination: ${o.statusText}`);return typeof localStorage<"u"&&localStorage.setItem(`imagination:${e.id}`,e.id),e.id}else {let o=await fetch(`${this.localServerUrl}/imaginations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to store imagination: ${o.statusText}`);let c=(await o.json()).imagination?.id||e.id;return typeof localStorage<"u"&&localStorage.setItem(`imagination:${c}`,c),c}}async getImagination(e){try{let t=await fetch(`${this.localServerUrl}/imaginations/${e}`);if(!t.ok)return null;let s=await t.json();return s.imagination?{id:s.imagination.id,title:s.imagination.title,createdAt:new Date(s.imagination.created_at).toISOString(),createdBy:s.imagination.creator_mid,sources:s.imagination.sources,summary:s.imagination.summary,character:s.imagination.character,workflow:s.imagination.workflow,is_public:s.imagination.is_public}:null}catch(t){return console.error("Failed to retrieve imagination:",t),null}}async getImaginationByCID(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);if(!t.ok)return null;let s=await t.json();return typeof localStorage<"u"&&localStorage.setItem(`imagination:${s.id}`,e),s}catch(t){return console.error("Failed to retrieve imagination by CID:",t),null}}async listImaginations(e){try{let t=e||"anonymous",s=await fetch(`${this.localServerUrl}/imaginations?creator_mid=${encodeURIComponent(t)}`);if(!s.ok)return console.warn("Failed to fetch imaginations from P2P, falling back to localStorage"),this.listImaginationsFromLocalStorage();let n=(await s.json()).imaginations.map(o=>({id:o.id,title:o.title,createdAt:new Date(o.created_at).toISOString(),createdBy:o.creator_mid,sources:o.sources,summary:o.summary,character:o.character,workflow:o.workflow,is_public:o.is_public}));return typeof localStorage<"u"&&n.forEach(o=>{localStorage.setItem(`imagination:${o.id}`,o.id);}),n}catch(t){return console.error("Failed to list imaginations:",t),this.listImaginationsFromLocalStorage()}}async listImaginationsFromLocalStorage(){if(typeof localStorage>"u")return [];let e=[];for(let t=0;t<localStorage.length;t++){let s=localStorage.key(t);if(s&&s.startsWith("imagination:")){let r=s.replace("imagination:",""),n=await this.getImagination(r);n&&e.push(n);}}return e}async getFile(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);return t.ok?await t.blob():null}catch(t){return console.error("Failed to retrieve file:",t),null}}arrayBufferToBase64(e){let t=new Uint8Array(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}};function te(a){return new I(a)}var Re=te();var A=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 se(a){return new A(a)}var Te=se();var re={database:"log",chat:"response",auth:"response",stream:"response",api:"response",history:"response",vote:"response",document:"response",suggestions:"response",task:"response",agent:"response",imagination:"response"},d=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=ne(e),this.statusCode=xe(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=re[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 ne(a){if(a.includes("database"))return "An error occurred while executing a database query.";switch(a){case "bad_request:api":return "The request couldn't be processed. Please check your input and try again.";case "unauthorized:auth":return "You need to sign in before continuing.";case "unauthorized:api":return "Your session has expired. Please sign in again.";case "forbidden:auth":return "Your account does not have access to this feature.";case "rate_limit:chat":return "You have exceeded your maximum number of messages for the day. Please try again later.";case "not_found:chat":return "The requested chat was not found.";case "forbidden:chat":return "This chat belongs to another user.";case "unauthorized:chat":return "You need to sign in to view this chat.";case "offline:chat":return "We're having trouble sending your message. Please check your internet connection.";case "not_found:task":return "The requested task was not found.";case "forbidden:task":return "You do not have access to this task.";case "not_found:agent":return "The requested agent was not found.";case "forbidden:agent":return "You do not have access to this agent.";case "not_found:imagination":return "The requested imagination was not found.";case "forbidden:imagination":return "You do not have access to this imagination.";case "not_found:document":return "The requested document was not found.";case "forbidden:document":return "This document belongs to another user.";case "unauthorized:document":return "You need to sign in to view this document.";case "bad_request:document":return "The request to create or update the document was invalid.";default:return "Something went wrong. Please try again later."}}function xe(a){switch(a){case "bad_request":return 400;case "unauthorized":return 401;case "payment_required":return 402;case "forbidden":return 403;case "not_found":return 404;case "rate_limit":return 429;case "offline":return 503;case "internal":return 500;default:return 500}}var _=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||w;}get socialUrl(){return `${this.baseUrl}/social`}async getFeed(e={}){let{page:t=1,limit:s=10,mediaType:r}=e,n=new URLSearchParams({page:String(t),limit:String(s)});r&&n.set("media_type",r);let o=await fetch(`${this.socialUrl}/feed?${n}`);if(!o.ok)throw new d("bad_request:api",`Failed to fetch feed: ${o.statusText}`);return o.json()}async getPost(e){let t=await fetch(`${this.socialUrl}/posts/${e}`);if(!t.ok)throw new d(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 d("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 d("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 d("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:g,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new d("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:g,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new d("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:g,body:JSON.stringify({postId:e,userMid:t,content:s})});if(!r.ok)throw new d("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:g,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 d("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:g,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:g,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 d("bad_request:api",`Failed to fetch profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof d)throw t;return null}}};function ae(a={}){return new _(a)}var Pe=ae();var v=class{baseUrl;useCpxApi;authToken;constructor(e={}){this.baseUrl=e.baseUrl||w,this.useCpxApi=e.useCpxApi!==false,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...g};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}get agentsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/agents`:`${this.baseUrl}/agents`}async list(e={}){let t=new URLSearchParams;e.userMid&&t.set("userMid",e.userMid);let s=t.toString(),r=`${this.agentsUrl}${s?`?${s}`:""}`,n=await fetch(r,{headers:this.headers});if(!n.ok)throw new d("bad_request:api",`Failed to list agents: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.agentsUrl}/${e}`,{headers:this.headers});if(!t.ok)throw new d(t.status===404?"not_found:api":"bad_request:api",`Failed to get agent: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.agentsUrl,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new d("bad_request:api",s.error||`Failed to create agent: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.agentsUrl}/${e}`,{method:"PUT",headers:this.headers,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new d("bad_request:api",r.error||`Failed to update agent: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.agentsUrl}/${e}`,{method:"DELETE",headers:this.headers});if(!t.ok)throw new d("bad_request:api",`Failed to delete agent: ${t.statusText}`);return t.json()}async enable(e){let t=await fetch(`${this.agentsUrl}/${e}/enable`,{method:"POST",headers:this.headers});if(!t.ok)throw new d("bad_request:api",`Failed to enable agent: ${t.statusText}`);return t.json()}async disable(e){let t=await fetch(`${this.agentsUrl}/${e}/disable`,{method:"POST",headers:this.headers});if(!t.ok)throw new d("bad_request:api",`Failed to disable agent: ${t.statusText}`);return t.json()}async execute(e,t={}){let s=await fetch(`${this.agentsUrl}/${e}/execute`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!s.ok)throw new d("bad_request:api",`Failed to execute agent: ${s.statusText}`);return s.json()}async createFromPrompt(e){let t=await fetch(`${this.agentsUrl}/from-prompt`,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok)throw new d("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 oe(a={}){return new v(a)}var $e=oe();var O=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||w;}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 d("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 d(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:g,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new d("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:g,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new d("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 d("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 d("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 ie(a={}){return new O(a)}var Ue=ie();var j=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||w;}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 d("bad_request:api",`Failed to get user profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof d)throw t;return null}}async updateProfile(e,t){let s=await fetch(`${this.userUrl}/profile/${e}`,{method:"PUT",headers:g,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new d("bad_request:api",r.error||`Failed to update user profile: ${s.statusText}`)}return s.json()}};function ce(a={}){return new j(a)}var Ee=ce();var D=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||w;}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 d("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 d("bad_request:api",`Failed to upload file from URL: ${t.statusText}`);return t.json()}getFileUrl(e){return `${this.filesUrl}/${e}`}};function de(a={}){return new D(a)}var Ie=de();var L=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||x,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 le(a){return new L(a)}var Ae=le();var F=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||x;}get pointsUrl(){return `${this.baseUrl}/cpx/points`}async initNetworkDomain(){let e=await fetch(`${this.pointsUrl}/init`,{method:"POST",headers:g});if(!e.ok){let t=await e.json().catch(()=>({}));throw new d("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 d("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 d("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:g,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new d("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new d("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 d("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 d("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:g,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new d("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new d("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 d("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:g,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new d("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 d("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:g,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new d("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:g,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new d("bad_request:api",s.error||`Failed to spend points: ${t.statusText}`)}return t.json()}async getBalance(e,t={}){let s=new URLSearchParams;t.domainId&&s.set("domainId",t.domainId),t.contextId&&s.set("contextId",t.contextId);let r=s.toString(),n=`${this.pointsUrl}/balance/${e}${r?`?${r}`:""}`,o=await fetch(n);if(!o.ok)throw new d("bad_request:api",`Failed to get balance: ${o.statusText}`);return o.json()}async getHistory(e={}){let t=new URLSearchParams;e.mid&&t.set("mid",e.mid),e.domainId&&t.set("domainId",e.domainId),e.contextId&&t.set("contextId",e.contextId),e.periodStart&&t.set("periodStart",e.periodStart.toString()),e.periodEnd&&t.set("periodEnd",e.periodEnd.toString()),e.taskId&&t.set("taskId",e.taskId),e.limit&&t.set("limit",e.limit.toString()),e.offset&&t.set("offset",e.offset.toString());let s=t.toString(),r=`${this.pointsUrl}/history${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new d("bad_request:api",`Failed to get history: ${n.statusText}`);return n.json()}};function ue(a={}){return new F(a)}var _e=ue();var M=class{baseUrl;apiKey;timeout;defaultModel;defaultMaxIterations;constructor(e={}){this.baseUrl=e.baseUrl||w,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={...g};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 d("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 d(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 d("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 d("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 d("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 l=await n.json().catch(()=>({}));throw new d("bad_request:api",l.error||`Failed to execute coder stream: ${n.statusText}`)}let o=n.body?.getReader();if(!o)throw new d("bad_request:stream","No response body");let i=new TextDecoder,c="";try{for(;;){let{done:l,value:f}=await o.read();if(l)break;c+=i.decode(f,{stream:!0});let m=c.split(`
|
|
4
|
+
`);c=m.pop()||"";for(let S of m)if(S.startsWith("data: ")){let b=S.slice(6);if(b==="[DONE]")return;try{yield JSON.parse(b);}catch{}}}}finally{clearTimeout(r),o.releaseLock();}}async getTools(){let e=await fetch(`${this.coderUrl}/tools`,{headers:this.headers});if(!e.ok)throw new d("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 d("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 d(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 d("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 d("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 d("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 d("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 d("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 d("bad_request:api",i.error||`Failed to execute command stream: ${s.statusText}`)}let r=s.body?.getReader();if(!r)throw new d("bad_request:stream","No response body");let n=new TextDecoder,o="";try{for(;;){let{done:i,value:c}=await r.read();if(i)break;o+=n.decode(c,{stream:!0});let l=o.split(`
|
|
5
|
+
`);o=l.pop()||"";for(let f of l)if(f.startsWith("data: ")){let m=f.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 d("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 d(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 d("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 d("bad_request:api",`Failed to destroy sandbox: ${t.statusText}`);return t.json()}};function pe(a={}){return new M(a)}var ve=pe();var he="/api/v2",q=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||T,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...g};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${he}${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(()=>({})),c=n.status===404?"not_found":n.status===401?"unauthorized":"bad_request";throw new d(`${c}:api`,i.error?.message||i.error||`Request failed: ${n.statusText}`)}let o=await n.json();return o&&typeof o=="object"&&"data"in o?o.data:o}async createStack(e){return this.request("POST","/stacks",e)}async listStacks(){return this.request("GET","/stacks")}async getStack(e){return this.request("GET",`/stacks/${e}`)}async updateStack(e,t){return this.request("PATCH",`/stacks/${e}`,t)}async deleteStack(e){return this.request("DELETE",`/stacks/${e}`)}async configureOAuthProvider(e,t,s){return this.request("POST",`/stacks/${e}/oauth/${t}`,s)}async removeOAuthProvider(e,t){return this.request("DELETE",`/stacks/${e}/oauth/${t}`)}async configureWeb3Provider(e,t,s){return this.request("POST",`/stacks/${e}/web3/${t}`,s)}async removeWeb3Provider(e,t){return this.request("DELETE",`/stacks/${e}/web3/${t}`)}async configureStripeProvider(e,t){return this.request("POST",`/stacks/${e}/stripe`,t)}async getStripeProvider(e){return this.request("GET",`/stacks/${e}/stripe`)}async removeStripeProvider(e){return this.request("DELETE",`/stacks/${e}/stripe`)}async createPaymentIntent(e,t,s){return this.request("POST",`/stacks/${e}/stripe/payment-intent`,{amountCents:t,metadata:s})}async createKey(e,t,s){return this.request("POST",`/stacks/${e}/keys`,{name:t,permission:s})}async listKeys(e){return this.request("GET",`/stacks/${e}/keys`)}async revokeKey(e,t){return this.request("DELETE",`/stacks/${e}/keys/${t}`)}async getAllowlist(e){return this.request("GET",`/stacks/${e}/auth/allowlist`)}async updateAllowlist(e,t){return this.request("PUT",`/stacks/${e}/auth/allowlist`,t)}async updateCapabilities(e,t){return this.request("PATCH",`/stacks/${e}`,{capabilityBitmask:t})}async getModelLayers(e){return this.request("GET",`/stacks/${e}/model-layers`)}async updateModelAlias(e,t,s,r){return this.request("PATCH",`/stacks/${e}/model-layers`,{layer:t,capability:s,alias:r})}async resetModelAlias(e,t,s){return this.request("DELETE",`/stacks/${e}/model-layers/${t}/${s}`)}async uploadLogo(e,t){let s=`${this.baseUrl}${he}/stacks/${e}/logo`,r=new FormData;r.append("logo",t);let n={};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);let o=await fetch(s,{method:"POST",headers:n,body:r});if(!o.ok){let c=await o.json().catch(()=>({}));throw new d("bad_request:api",c.error?.message||`Failed to upload logo: ${o.statusText}`)}let i=await o.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 ge(a={}){return new q(a)}var Oe=ge();var N="/api/v2",H=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||T,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...g};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 d("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}${N}/network/status`)}async getMPCNodes(){return this.request("GET",`${this.baseUrl}${N}/network/nodes`)}async getNodeHealth(e){return this.request("GET",`${this.baseUrl}${N}/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}${N}${t}`)}};function me(a={}){return new H(a)}var je=me();var De="/api/v2",K=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||T,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...g};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${De}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let i=await n.json().catch(()=>({}));throw new d(n.status===402?"payment_required:api":"bad_request:api",i.error?.message||`Request failed: ${n.statusText}`)}let o=await n.json();return o&&typeof o=="object"&&"data"in o?o.data:o}async getPlans(e){return this.request("GET",`/stacks/${e}/billing/plans`)}async getBillingState(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing`)}async createCheckoutSession(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/checkout`,{identity_id:t,plan_id:s,success_url:r,cancel_url:n})}async createBillingPortal(e,t,s){return this.request("POST",`/stacks/${e}/billing/portal`,{identity_id:t,return_url:s})}async recordUsage(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/usage`,{identity_id:t,usage_type:s,quantity:r,idempotency_key:n})}async getCurrentUsage(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/usage`)}async linkStripeCustomer(e,t,s,r){return this.request("POST",`/stacks/${e}/billing/link`,{identity_id:t,stripe_customer_id:s,checkout_session_id:r})}async hasPaymentMethod(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/payment-method`)}async subscribeSol(e,t,s){return this.request("POST",`/stacks/${e}/subscribe-sol`,{planId:t,txSignature:s})}async prepaidSol(e,t,s,r){return this.request("POST",`/stacks/${e}/prepaid-sol`,{amountCents:t,txSignature:s,scope:r})}async topup(e,t,s){return this.request("POST","/account/topup",{amount_cents:e,payment_method:t,payment_ref:s})}};function fe(a={}){return new K(a)}var Le=fe();var W=class{redis;getRedisClient;taskTTL;constructor(e={}){this.redis=e.redis,this.getRedisClient=e.getRedisClient,this.taskTTL=e.taskTTL||G;}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(),o=z(),i=Date.now(),c={id:o,chatId:e,messageId:t,type:s,status:"pending",progress:0,message:r,createdAt:i,updatedAt:i};return await n.hSet(`${C}${o}`,this.taskToRedis(c)),await n.expire(`${C}${o}`,this.taskTTL),await n.sAdd(`${P}${e}`,o),await n.expire(`${P}${e}`,this.taskTTL),console.log(`[TaskManager] Created task ${o} for chat ${e} (${s})`),o}async updateProgress(e,t,s){let r=await this.getClient();await r.hSet(`${C}${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(`${C}${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(`${C}${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(`${C}${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 o=await this.getTask(n);o&&r.push(o);}return r.sort((n,o)=>o.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(`${C}${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=>{let o;try{o=JSON.parse(n);}catch{return}if(!o||typeof o!="object"||Array.isArray(o))return;let i=o;typeof i.taskId!="string"||i.taskId!==e||typeof i.status=="string"&&(i.progress!==void 0&&typeof i.progress!="number"||i.message!==void 0&&typeof i.message!="string"||i.error!==void 0&&typeof i.error!="string"||t({taskId:i.taskId,status:i.status,progress:i.progress,message:i.message,result:i.result,error:i.error}));}),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 Fe(a){return new W(a)}var ye=1024*1024;function X(a){return a.replace(/[\r\n\u2028\u2029]/g," ")}async function*Me(a){if(!a.body)throw new Error("Response body is null");let e=a.body.getReader(),t=new TextDecoder,s="",r={};try{for(;;){let{done:n,value:o}=await e.read();if(n)break;if(s+=t.decode(o,{stream:!0}),s.length>ye)throw new Error(`SSE buffer exceeded ${ye} bytes without an event delimiter`);let i=s.split(`
|
|
6
|
+
`);s=i.pop()||"";for(let c of i){if(c===""){r.data!==void 0&&(yield r),r={};continue}if(c.startsWith(":"))continue;let l=c.indexOf(":");if(l===-1)continue;let f=c.slice(0,l),m=c.slice(l+1).trimStart();switch(f){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 we(a){let e="";a.event&&(e+=`event: ${X(a.event)}
|
|
7
|
+
`),a.id&&(e+=`id: ${X(a.id)}
|
|
8
|
+
`),a.retry!==void 0&&Number.isFinite(a.retry)&&(e+=`retry: ${Math.floor(a.retry)}
|
|
9
|
+
`);let t=typeof a.data=="string"?a.data:JSON.stringify(a.data);for(let s of t.split(/\r?\n/))e+=`data: ${s}
|
|
10
|
+
`;return e+=`
|
|
11
|
+
`,e}function qe(a,e){let t=new TextEncoder,s=new ReadableStream({async start(r){try{for await(let n of a)r.enqueue(t.encode(we(n)));}catch(n){console.error("SSE stream error:",n);}finally{r.close();}}});return new Response(s,{headers:{...U,...e}})}var B=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:{...U,...e}})}write(e){this.controller&&this.controller.enqueue(this.encoder.encode(we(e)));}writeData(e){this.write({data:e});}writeComment(e){if(!this.controller)return;let t=X(e);this.controller.enqueue(this.encoder.encode(`: ${t}
|
|
10
12
|
|
|
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
|
-
`),e.id&&(t+=`id: ${e.id}
|
|
13
|
-
`);let s=typeof e.data=="string"?e.data:JSON.stringify(e.data);t+=`data: ${s}
|
|
14
|
-
|
|
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
|
-
|
|
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}exports.ALL_CAPABILITIES_BITMASK=it;exports.AgentsClient=A;exports.BillingClient=N;exports.CAPABILITY_BITS=Y;exports.CHAT_TASKS_PREFIX=P;exports.CoderClient=L;exports.ComponentStreamAdapter=W;exports.DEFAULT_MAGMA_RPC_URL=T;exports.DEFAULT_TASK_NETWORK_URL=h;exports.FilesClient=O;exports.JSON_HEADERS=p;exports.MCPClient=I;exports.MagmaClient=U;exports.NetworkClient=M;exports.PointsClient=D;exports.SSEWriter=K;exports.SSE_HEADERS=x;exports.SkillsClient=j;exports.SocialClient=E;exports.StackManagementClient=q;exports.StacksSDKError=c;exports.TASK_PREFIX=b;exports.TASK_TTL=J;exports.TaskManager=H;exports.TaskNetworkClient=$;exports.UserClient=v;exports.WidgetsClient=_;exports.agentsClient=Ce;exports.billingClient=_e;exports.bitmaskToCapabilities=dt;exports.capabilitiesToBitmask=ct;exports.coderClient=Ue;exports.createAgentDetailRoutes=He;exports.createAgentExecuteRoute=Ke;exports.createAgentRoutes=Ne;exports.createAgentToggleRoutes=We;exports.createAgentsClient=ne;exports.createBillingClient=ge;exports.createCoderClient=le;exports.createCoderExecRoutes=st;exports.createCoderExecuteRoute=Qe;exports.createCoderFilesRoutes=et;exports.createCoderSandboxRoutes=tt;exports.createCoderSessionDetailRoutes=Xe;exports.createCoderSessionRoutes=Ve;exports.createCoderToolsRoutes=Ze;exports.createComponentStreamAdapter=Fe;exports.createFilesClient=ie;exports.createImaginationRoutes=Ye;exports.createMCPClient=ee;exports.createMagmaClient=Z;exports.createNetworkClient=me;exports.createPointsClient=de;exports.createProxyHandler=Me;exports.createSSEResponse=je;exports.createSSEWriter=De;exports.createSkillDetailRoutes=Je;exports.createSkillRoutes=Be;exports.createSkillsClient=ce;exports.createSocialClient=re;exports.createStackDetailRoutes=nt;exports.createStackKeysRoutes=at;exports.createStackManagementClient=pe;exports.createStackMembersRoutes=ot;exports.createStackRoutes=rt;exports.createTaskManager=ve;exports.createTaskNetworkClient=X;exports.createUserClient=oe;exports.createWidgetDetailRoutes=ze;exports.createWidgetRoutes=Ge;exports.createWidgetsClient=ae;exports.extractToolResults=qe;exports.filesClient=Pe;exports.forwardJSON=l;exports.forwardRequest=k;exports.generateCID=z;exports.generateUUID=G;exports.getMessageByErrorCode=se;exports.hasToolCalls=Le;exports.magmaClient=we;exports.mcpClient=Se;exports.networkClient=Ee;exports.parseSSELine=ye;exports.parseSSEStream=Oe;exports.pointsClient=$e;exports.retry=fe;exports.skillsClient=xe;exports.sleep=Q;exports.socialClient=ke;exports.stackManagementClient=Ie;exports.taskNetworkClient=he;exports.userClient=Te;exports.visibilityBySurface=te;exports.widgetsClient=Re;
|
|
13
|
+
`));}close(){this.controller&&(this.controller.close(),this.controller=null);}error(e){this.controller&&(this.controller.error(e),this.controller=null);}};function Ne(){return new B}var J=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,o=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;console.log(`[ComponentStream] Creating document: ${s} (${r})`),this.streamArtifact({id:o,kind:r,title:s,content:n}),this.dataStream.write({type:"tool-result",data:{toolCallId:t,toolName:"create_document",result:{id:o,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 o=0;o<r.length;o++){let i=o===0?r[o]:" "+r[o];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 He(a){return !!(a?.tool_calls&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0)}function Ke(a){try{let e=JSON.parse(a);if(e.type&&(e.type==="artifact"||e.type==="artifact_update"))return [e]}catch{}return []}function We(a){return new J(a)}var Be=3e4,Je=1024*1024,Ge=new Set(["authorization","content-type","accept","accept-language","x-request-id","x-correlation-id","idempotency-key"]);function ze(a,e){let t=a.endsWith("/")?a:`${a}/`,s=e.startsWith("/")?e.slice(1):e,r=new URL(s,t),n=new URL(t);if(r.origin!==n.origin)throw new Error(`forwarder: resolved URL ${r.origin} escapes baseUrl origin ${n.origin}`);return r.toString()}async function R(a,e={},t={}){let s=t.baseUrl||w,{method:r="GET",headers:n={},body:o,searchParams:i,stream:c}=e,l=new URL(ze(s,a));i&&Object.entries(i).forEach(([S,b])=>{b!==void 0&&l.searchParams.set(S,b);});let f={method:r,headers:{...t.defaultHeaders,...n},signal:AbortSignal.timeout(t.timeout??Be)};o&&r!=="GET"&&(f.headers={...f.headers,"Content-Type":"application/json"},f.body=JSON.stringify(o));let m=await fetch(l.toString(),f);return c&&m.body,m}async function p(a,e={},t={}){let s=await R(a,e,t);return {data:await s.json(),status:s.status}}async function Ye(a,e){let t=a.headers.get("content-length");if(t){let l=parseInt(t,10);if(Number.isFinite(l)&&l>e)return {_tooLarge:true}}if(!a.body)return;let s=a.body.getReader(),r=0,n=[];for(;;){let{done:l,value:f}=await s.read();if(l)break;if(r+=f.byteLength,r>e){try{await s.cancel();}catch{}return {_tooLarge:true}}n.push(f);}if(r===0)return;let o=new Uint8Array(r),i=0;for(let l of n)o.set(l,i),i+=l.byteLength;let c=new TextDecoder().decode(o);if(c.trim()!=="")try{return JSON.parse(c)}catch{return}}function Xe(a,e={}){let t=e.maxBodyBytes??Je;return async s=>{let r=new URL(s.url),n=typeof a=="function"?a(s):a,o={};r.searchParams.forEach((S,b)=>{o[b]=S;});let i;if(s.method!=="GET"&&s.method!=="HEAD"){let S=await Ye(s,t);if(S&&typeof S=="object"&&S._tooLarge)return Response.json({error:`Request body exceeds ${t} bytes`},{status:413});i=S;}let c={};s.headers.forEach((S,b)=>{Ge.has(b.toLowerCase())&&(c[b]=S);});let l=await R(n,{method:s.method,headers:c,body:i,searchParams:o},e);if((l.headers.get("content-type")||"").includes("text/event-stream"))return new Response(l.body,{status:l.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let m=await l.json();return Response.json(m,{status:l.status})}}function k(a,e){if(!a||typeof a!="string")throw new Error(`Missing required parameter: ${e}`);if(!/^[\w.\-]+$/.test(a))throw new Error(`Invalid ${e}: contains disallowed characters`);return a}function h(a){let e=a instanceof Error?a.message:"Bad request";return Response.json({error:e},{status:400})}function u(a,e){let t={};if(a.extractAuth){let s=a.extractAuth(e);s&&(t.Authorization=`Bearer ${s}`);}else {let s=e.headers.get("Authorization");s&&(t.Authorization=s);}return t}function y(a,e,t,s=1){let r=e?.params?.[t];if(r)return k(r,t);let n=new URL(a.url).pathname.split("/").filter(Boolean),o=n[n.length-s];return k(o,t)}function Ve(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("userMid"),n=s.searchParams.get("visibility"),o=r?`/agents?creator_mid=${encodeURIComponent(r)}`:n?`/agents?visibility=${encodeURIComponent(n)}`:"/agents",{data:i,status:c}=await p(o,{headers:u(a,t)},{baseUrl:e}),l=i;return a.enrichResponse&&(l=await a.enrichResponse(i)),Response.json(l,{status:c})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/agents",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})}}}function Qe(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(c){return h(c)}let{data:n,status:o}=await p(`/agents/${r}`,{headers:u(a,t)},{baseUrl:e}),i=n;return a.enrichResponse&&(i=await a.enrichResponse(n)),Response.json(i,{status:o})},POST:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/agents/${r}`,{method:"POST",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},PUT:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/agents/${r}`,{method:"PUT",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/agents/${r}`,{method:"DELETE",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}}}function Ze(a={}){let e=a.baseUrl;return {POST:async(t,s)=>{let r;try{r=y(t,s,"id",2);}catch(l){return h(l)}let n=await t.json(),o=await R(`/agents/${r}/execute`,{method:"POST",body:n,stream:true,headers:u(a,t)},{baseUrl:e});if((o.headers.get("content-type")||"").includes("text/event-stream")&&o.body)return new Response(o.body,{status:o.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let c=await o.json();return Response.json(c,{status:o.status})}}}function et(a={}){let e=a.baseUrl;return {enable:{POST:async(t,s)=>{let r;try{r=y(t,s,"id",2);}catch(i){return h(i)}let{data:n,status:o}=await p(`/agents/${r}/enable`,{method:"POST",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}},disable:{POST:async(t,s)=>{let r;try{r=y(t,s,"id",2);}catch(i){return h(i)}let{data:n,status:o}=await p(`/agents/${r}/disable`,{method:"POST",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}}}}function tt(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("scope"),n=s.searchParams.get("creator_mid"),o="/skills";r?o+=`?scope=${encodeURIComponent(r)}`:n&&(o+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:c}=await p(o,{headers:u(a,t)},{baseUrl:e});return Response.json(i,{status:c})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/skills",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})}}}function st(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/skills/${r}`,{headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})},POST:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/skills/${r}`,{method:"POST",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},PUT:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/skills/${r}`,{method:"PUT",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/skills/${r}`,{method:"DELETE",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}}}function rt(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("scope"),n=s.searchParams.get("creator_mid"),o="/widgets";r?o+=`?scope=${encodeURIComponent(r)}`:n&&(o+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:c}=await p(o,{headers:u(a,t)},{baseUrl:e});return Response.json(i,{status:c})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/widgets",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})}}}function nt(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/widgets/${r}`,{headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})},POST:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/widgets/${r}`,{method:"POST",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},PUT:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/widgets/${r}`,{method:"PUT",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/widgets/${r}`,{method:"DELETE",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}}}function at(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("id"),n=s.searchParams.get("creator_mid"),o="/imaginations";if(r)try{o=`/imaginations/${k(r,"id")}`;}catch(l){return h(l)}else n&&(o+=`?creator_mid=${encodeURIComponent(n)}`);let{data:i,status:c}=await p(o,{headers:u(a,t)},{baseUrl:e});return Response.json(i,{status:c})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/imaginations",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})}}}function ot(a={}){let e=a.baseUrl;return {GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("status"),n=s.searchParams.get("limit"),o="/coder/sessions",i=[];r&&i.push(`status=${encodeURIComponent(r)}`),n&&i.push(`limit=${encodeURIComponent(n)}`),i.length&&(o+=`?${i.join("&")}`);let{data:c,status:l}=await p(o,{headers:u(a,t)},{baseUrl:e});return Response.json(c,{status:l})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/coder/sessions",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})}}}function it(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/coder/sessions/${r}`,{headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})},POST:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/coder/sessions/${r}`,{method:"POST",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/coder/sessions/${r}`,{method:"DELETE",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})},abort:{POST:async(t,s)=>{let r;try{r=y(t,s,"id",2);}catch(i){return h(i)}let{data:n,status:o}=await p(`/coder/sessions/${r}/abort`,{method:"POST",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}}}}function ct(a={}){let e=a.baseUrl;return {POST:async t=>{let s=await t.json(),r=await R("/coder/execute",{method:"POST",body:s,stream:s.stream,headers:u(a,t)},{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 o=await r.json();return Response.json(o,{status:r.status})}}}function dt(a={}){let e=a.baseUrl;return {GET:async t=>{let{data:s,status:r}=await p("/coder/tools",{headers:u(a,t)},{baseUrl:e});return Response.json(s,{status:r})},call:{POST:async(t,s)=>{let r;try{r=y(t,s,"tool");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/coder/tools/${r}`,{method:"POST",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})}}}}function lt(a={}){let e=a.baseUrl;return {read:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("path")||"",n=s.searchParams.get("sessionId"),o=s.searchParams.get("sandboxId"),i=`/coder/files/read?path=${encodeURIComponent(r)}`;n&&(i+=`&sessionId=${encodeURIComponent(n)}`),o&&(i+=`&sandboxId=${encodeURIComponent(o)}`);let{data:c,status:l}=await p(i,{headers:u(a,t)},{baseUrl:e});return Response.json(c,{status:l})}},write:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/coder/files/write",{method:"POST",body:s,headers:u(a,t)},{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"),o=s.searchParams.get("maxDepth"),i=s.searchParams.get("sessionId"),c=s.searchParams.get("sandboxId"),l=`/coder/files/list?path=${encodeURIComponent(r)}`;n&&(l+=`&recursive=${encodeURIComponent(n)}`),o&&(l+=`&maxDepth=${encodeURIComponent(o)}`),i&&(l+=`&sessionId=${encodeURIComponent(i)}`),c&&(l+=`&sandboxId=${encodeURIComponent(c)}`);let{data:f,status:m}=await p(l,{headers:u(a,t)},{baseUrl:e});return Response.json(f,{status:m})}},search:{GET:async t=>{let s=new URL(t.url),r=s.searchParams.get("pattern")||"",n=s.searchParams.get("path"),o=s.searchParams.get("filePattern"),i=s.searchParams.get("sessionId"),c=s.searchParams.get("sandboxId"),l=`/coder/files/search?pattern=${encodeURIComponent(r)}`;n&&(l+=`&path=${encodeURIComponent(n)}`),o&&(l+=`&filePattern=${encodeURIComponent(o)}`),i&&(l+=`&sessionId=${encodeURIComponent(i)}`),c&&(l+=`&sandboxId=${encodeURIComponent(c)}`);let{data:f,status:m}=await p(l,{headers:u(a,t)},{baseUrl:e});return Response.json(f,{status:m})}},diff:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/coder/files/diff",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})}}}}function ut(a={}){let e=a.baseUrl;return {create:{POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/coder/sandbox",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})}},get:{GET:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/coder/sandbox/${r}`,{headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}},exec:{POST:async(t,s)=>{let r;try{r=y(t,s,"id",2);}catch(l){return h(l)}let n=await t.json(),o=await R(`/coder/sandbox/${r}/exec`,{method:"POST",body:n,stream:n.stream,headers:u(a,t)},{baseUrl:e});if((o.headers.get("content-type")||"").includes("text/event-stream")&&o.body)return new Response(o.body,{status:o.status,headers:{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}});let c=await o.json();return Response.json(c,{status:o.status})}},destroy:{DELETE:async(t,s)=>{let r;try{r=y(t,s,"id");}catch(i){return h(i)}let{data:n,status:o}=await p(`/coder/sandbox/${r}`,{method:"DELETE",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}}}}function pt(a={}){let e=a.baseUrl;return {POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/coder/exec",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})},stream:{POST:async t=>{let s=await t.json(),r=await R("/coder/exec/stream",{method:"POST",body:s,stream:true,headers:u(a,t)},{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 ht(a={}){let e=a.baseUrl;return {GET:async t=>{let{data:s,status:r}=await p("/api/v2/stacks",{headers:u(a,t)},{baseUrl:e});return Response.json(s,{status:r})},POST:async t=>{let s=await t.json(),{data:r,status:n}=await p("/api/v2/stacks",{method:"POST",body:s,headers:u(a,t)},{baseUrl:e});return Response.json(r,{status:n})}}}function gt(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r;try{r=k(s?.params?.stackId,"stackId");}catch(i){return h(i)}let{data:n,status:o}=await p(`/api/v2/stacks/${r}`,{headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})},POST:async()=>Response.json({error:"Method not allowed"},{status:405}),PUT:async(t,s)=>{let r;try{r=k(s?.params?.stackId,"stackId");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/api/v2/stacks/${r}`,{method:"PATCH",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r;try{r=k(s?.params?.stackId,"stackId");}catch(i){return h(i)}let{data:n,status:o}=await p(`/api/v2/stacks/${r}`,{method:"DELETE",headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}}}function mt(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r;try{r=k(s?.params?.stackId,"stackId");}catch(i){return h(i)}let{data:n,status:o}=await p(`/api/v2/stacks/${r}/keys`,{headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})},POST:async(t,s)=>{let r;try{r=k(s?.params?.stackId,"stackId");}catch(c){return h(c)}let n=await t.json(),{data:o,status:i}=await p(`/api/v2/stacks/${r}/keys`,{method:"POST",body:n,headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})},DELETE:async(t,s)=>{let r,n;try{r=k(s?.params?.stackId,"stackId"),n=k(s?.params?.keyId,"keyId");}catch(c){return h(c)}let{data:o,status:i}=await p(`/api/v2/stacks/${r}/keys/${n}`,{method:"DELETE",headers:u(a,t)},{baseUrl:e});return Response.json(o,{status:i})}}}function ft(a={}){let e=a.baseUrl;return {GET:async(t,s)=>{let r;try{r=k(s?.params?.stackId,"stackId");}catch(b){return h(b)}let n=new URL(t.url),o=new URLSearchParams,i=n.searchParams.get("limit"),c=n.searchParams.get("offset"),l=n.searchParams.get("role");i&&o.set("limit",i),c&&o.set("offset",c),l&&o.set("role",l);let f=o.toString()?`?${o}`:"",{data:m,status:S}=await p(`/api/v2/stacks/${r}/members${f}`,{headers:u(a,t)},{baseUrl:e});return Response.json(m,{status:S})},stats:{GET:async(t,s)=>{let r;try{r=k(s?.params?.stackId,"stackId");}catch(i){return h(i)}let{data:n,status:o}=await p(`/api/v2/stacks/${r}/members/stats`,{headers:u(a,t)},{baseUrl:e});return Response.json(n,{status:o})}},updateRole:{PATCH:async(t,s)=>{let r,n;try{r=k(s?.params?.stackId,"stackId"),n=k(s?.params?.userId,"userId");}catch(l){return h(l)}let o=await t.json(),{data:i,status:c}=await p(`/api/v2/stacks/${r}/members/${n}/role`,{method:"PATCH",body:o,headers:u(a,t)},{baseUrl:e});return Response.json(i,{status:c})}}}}var V={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},yt=131071;function wt(a){let e=0;for(let[t,s]of Object.entries(V))a[t]&&(e|=s);return e}function St(a){let e={};for(let[t,s]of Object.entries(V))e[t]=(a&s)!==0;return e}exports.ALL_CAPABILITIES_BITMASK=yt;exports.AgentsClient=v;exports.BillingClient=K;exports.CAPABILITY_BITS=V;exports.CHAT_TASKS_PREFIX=P;exports.CoderClient=M;exports.ComponentStreamAdapter=J;exports.DEFAULT_MAGMA_RPC_URL=x;exports.DEFAULT_TASK_NETWORK_URL=w;exports.FilesClient=D;exports.JSON_HEADERS=g;exports.MCPClient=A;exports.MagmaClient=I;exports.NetworkClient=H;exports.PointsClient=F;exports.SSEWriter=B;exports.SSE_HEADERS=U;exports.SkillsClient=L;exports.SocialClient=_;exports.StackManagementClient=q;exports.StacksSDKError=d;exports.TASK_PREFIX=C;exports.TASK_TTL=G;exports.TaskManager=W;exports.TaskNetworkClient=E;exports.UserClient=j;exports.WidgetsClient=O;exports.agentsClient=$e;exports.billingClient=Le;exports.bitmaskToCapabilities=St;exports.capabilitiesToBitmask=wt;exports.coderClient=ve;exports.createAgentDetailRoutes=Qe;exports.createAgentExecuteRoute=Ze;exports.createAgentRoutes=Ve;exports.createAgentToggleRoutes=et;exports.createAgentsClient=oe;exports.createBillingClient=fe;exports.createCoderClient=pe;exports.createCoderExecRoutes=pt;exports.createCoderExecuteRoute=ct;exports.createCoderFilesRoutes=lt;exports.createCoderSandboxRoutes=ut;exports.createCoderSessionDetailRoutes=it;exports.createCoderSessionRoutes=ot;exports.createCoderToolsRoutes=dt;exports.createComponentStreamAdapter=We;exports.createFilesClient=de;exports.createImaginationRoutes=at;exports.createMCPClient=se;exports.createMagmaClient=te;exports.createNetworkClient=me;exports.createPointsClient=ue;exports.createProxyHandler=Xe;exports.createSSEResponse=qe;exports.createSSEWriter=Ne;exports.createSkillDetailRoutes=st;exports.createSkillRoutes=tt;exports.createSkillsClient=le;exports.createSocialClient=ae;exports.createStackDetailRoutes=gt;exports.createStackKeysRoutes=mt;exports.createStackManagementClient=ge;exports.createStackMembersRoutes=ft;exports.createStackRoutes=ht;exports.createTaskManager=Fe;exports.createTaskNetworkClient=Z;exports.createUserClient=ce;exports.createWidgetDetailRoutes=nt;exports.createWidgetRoutes=rt;exports.createWidgetsClient=ie;exports.extractToolResults=Ke;exports.filesClient=Ie;exports.forwardJSON=p;exports.forwardRequest=R;exports.generateCID=Y;exports.generateUUID=z;exports.getMessageByErrorCode=ne;exports.hasToolCalls=He;exports.magmaClient=Re;exports.mcpClient=Te;exports.networkClient=je;exports.parseSSELine=Ce;exports.parseSSEStream=Me;exports.pointsClient=_e;exports.retry=ke;exports.skillsClient=Ae;exports.sleep=ee;exports.socialClient=Pe;exports.stackManagementClient=Oe;exports.taskNetworkClient=be;exports.userClient=Ee;exports.visibilityBySurface=re;exports.widgetsClient=Ue;
|
package/dist/index.d.cts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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.cjs';
|
|
2
2
|
import { CoderClientConfig, CoderSandboxCreateInput, CoderSession, CoderExecuteRequest, CoderExecuteResponse, CoderStreamEvent, CoderTool, CoderToolResult, CoderFileContent, CoderFileWriteInput, CoderFileInfo, CoderSearchResult, CoderDiffInput, CoderCommandInput, CoderCommandResult, CoderSandbox, CoderSandboxExecInput, CoderSandboxExecResult } from './types/index.cjs';
|
|
3
3
|
export { AuthMethod, BillingCredentialData, CoderMetrics, CoderSandboxConfig, CoderSessionStatus, CoderStreamEventType, CredentialLinkProof, CredentialType, EmailCredentialData, GlobalIdentity, OAuthCredentialData, Session, StackCredential, StackIdentity, StripeConnectCredentialData, Web3Chain, Web3CredentialData } from './types/index.cjs';
|
|
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-eQZIWeNW.cjs';
|
|
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-eQZIWeNW.cjs';
|
|
6
6
|
export { ArtifactToolCall, ArtifactToolResult, ComponentStreamAdapter, DataStreamWriter, SSEEvent, SSEWriter, createComponentStreamAdapter, createSSEResponse, createSSEWriter, extractToolResults, hasToolCalls, parseSSEStream } from './streaming/index.cjs';
|
|
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-
|
|
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-B_dUFmAg.cjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Coder Client
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
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-eQZIWeNW.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-eQZIWeNW.js';
|
|
6
6
|
export { ArtifactToolCall, ArtifactToolResult, ComponentStreamAdapter, DataStreamWriter, SSEEvent, SSEWriter, createComponentStreamAdapter, createSSEResponse, createSSEWriter, extractToolResults, hasToolCalls, parseSSEStream } from './streaming/index.js';
|
|
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-
|
|
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-B_dUFmAg.js';
|
|
8
8
|
|
|
9
9
|
/**
|
|
10
10
|
* Coder Client
|