@stacknet/stacks 0.2.0 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +136 -0
- package/dist/{billing-eQZIWeNW.d.cts → billing-cj0eSVrp.d.cts} +59 -1
- package/dist/{billing-eQZIWeNW.d.ts → billing-cj0eSVrp.d.ts} +59 -1
- package/dist/clients/index.cjs +4 -4
- package/dist/clients/index.d.cts +24 -1
- package/dist/clients/index.d.ts +24 -1
- package/dist/clients/index.js +4 -4
- package/dist/index.cjs +7 -7
- package/dist/index.d.cts +3 -3
- package/dist/index.d.ts +3 -3
- package/dist/index.js +7 -7
- package/dist/proxy/index.cjs +2 -2
- package/dist/proxy/index.js +2 -2
- package/dist/streaming/index.cjs +5 -5
- package/dist/streaming/index.js +5 -5
- package/dist/types/index.d.cts +1 -1
- package/dist/types/index.d.ts +1 -1
- package/package.json +15 -13
- package/src/clients/agents.ts +0 -250
- package/src/clients/billing.ts +0 -197
- package/src/clients/coder.ts +0 -655
- package/src/clients/files.ts +0 -86
- package/src/clients/index.ts +0 -93
- package/src/clients/magma.ts +0 -299
- package/src/clients/mcp.ts +0 -208
- package/src/clients/network.ts +0 -118
- package/src/clients/points.ts +0 -403
- package/src/clients/skills.ts +0 -236
- package/src/clients/social.ts +0 -286
- package/src/clients/stack-management.ts +0 -279
- package/src/clients/task-network.ts +0 -303
- package/src/clients/user.ts +0 -84
- package/src/clients/widgets.ts +0 -171
- package/src/index.ts +0 -387
- package/src/managers/index.ts +0 -10
- package/src/managers/task-manager.ts +0 -332
- package/src/proxy/forwarder.ts +0 -235
- package/src/proxy/index.ts +0 -32
- package/src/proxy/route-handlers.ts +0 -1107
- package/src/streaming/component-stream.ts +0 -319
- package/src/streaming/index.ts +0 -21
- package/src/streaming/sse.ts +0 -266
- package/src/types/agent.ts +0 -108
- package/src/types/billing.ts +0 -121
- package/src/types/chat.ts +0 -58
- package/src/types/coder.ts +0 -345
- package/src/types/credential.ts +0 -111
- package/src/types/file.ts +0 -15
- package/src/types/imagination.ts +0 -50
- package/src/types/index.ts +0 -20
- package/src/types/mcp.ts +0 -35
- package/src/types/network.ts +0 -97
- package/src/types/points.ts +0 -250
- package/src/types/skill.ts +0 -107
- package/src/types/social.ts +0 -109
- package/src/types/stack.ts +0 -269
- package/src/types/task.ts +0 -41
- package/src/types/user.ts +0 -29
- package/src/types/widget.ts +0 -57
- package/src/utils/constants.ts +0 -26
- package/src/utils/errors.ts +0 -169
- package/src/utils/helpers.ts +0 -85
- package/src/utils/index.ts +0 -7
package/dist/streaming/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var m={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};var
|
|
2
|
-
`);r=s.pop()||"";for(let c of s){if(c===""){e.data!==void 0&&(yield e),e={};continue}if(c.startsWith(":"))continue;let p=c.indexOf(":");if(p===-1)continue;let g=c.slice(0,p),l=c.slice(p+1).trimStart();switch(g){case "event":e.event=l;break;case "data":try{e.data=JSON.parse(l);}catch{e.data=l;}break;case "id":e.id=l;break;case "retry":e.retry=parseInt(l,10);break}}}e.data!==void 0&&(yield e);}finally{t.releaseLock();}}function h(a){let t="";a.event&&(t+=`event: ${
|
|
3
|
-
`),a.id&&(t+=`id: ${
|
|
1
|
+
var m={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};var f=1024*1024;function S(a){return a.replace(/[\r\n\u2028\u2029]/g," ")}async function*y(a){if(!a.body)throw new Error("Response body is null");let t=a.body.getReader(),n=new TextDecoder,r="",e={};try{for(;;){let{done:o,value:i}=await t.read();if(o)break;if(r+=n.decode(i,{stream:!0}),r.length>f)throw new Error(`SSE buffer exceeded ${f} bytes without an event delimiter`);let s=r.split(`
|
|
2
|
+
`);r=s.pop()||"";for(let c of s){if(c===""){e.data!==void 0&&(yield e),e={};continue}if(c.startsWith(":"))continue;let p=c.indexOf(":");if(p===-1)continue;let g=c.slice(0,p),l=c.slice(p+1).trimStart();switch(g){case "event":e.event=l;break;case "data":try{e.data=JSON.parse(l);}catch{e.data=l;}break;case "id":e.id=l;break;case "retry":e.retry=parseInt(l,10);break}}}e.data!==void 0&&(yield e);}finally{t.releaseLock();}}function h(a){let t="";a.event&&(t+=`event: ${S(a.event)}
|
|
3
|
+
`),a.id&&(t+=`id: ${S(a.id)}
|
|
4
4
|
`),a.retry!==void 0&&Number.isFinite(a.retry)&&(t+=`retry: ${Math.floor(a.retry)}
|
|
5
5
|
`);let n=typeof a.data=="string"?a.data:JSON.stringify(a.data);for(let r of n.split(/\r?\n/))t+=`data: ${r}
|
|
6
6
|
`;return t+=`
|
|
7
|
-
`,t}function E(a,t){let n=new TextEncoder,r=new ReadableStream({async start(e){try{for await(let o of a)e.enqueue(n.encode(h(o)));}catch(o){console.error("SSE stream error:",o);}finally{e.close();}}});return new Response(r,{headers:{...m,...t}})}var d=class{encoder=new TextEncoder;controller=null;stream;constructor(){this.stream=new ReadableStream({start:t=>{this.controller=t;}});}getStream(){return this.stream}getResponse(t){return new Response(this.stream,{headers:{...m,...t}})}write(t){this.controller&&this.controller.enqueue(this.encoder.encode(h(t)));}writeData(t){this.write({data:t});}writeComment(t){if(!this.controller)return;let n=
|
|
7
|
+
`,t}function E(a,t){let n=new TextEncoder,r=new ReadableStream({async start(e){try{for await(let o of a)e.enqueue(n.encode(h(o)));}catch(o){console.error("SSE stream error:",o);}finally{e.close();}}});return new Response(r,{headers:{...m,...t}})}var d=class{encoder=new TextEncoder;controller=null;stream;constructor(){this.stream=new ReadableStream({start:t=>{this.controller=t;}});}getStream(){return this.stream}getResponse(t){return new Response(this.stream,{headers:{...m,...t}})}write(t){this.controller&&this.controller.enqueue(this.encoder.encode(h(t)));}writeData(t){this.write({data:t});}writeComment(t){if(!this.controller)return;let n=S(t);this.controller.enqueue(this.encoder.encode(`: ${n}
|
|
8
8
|
|
|
9
|
-
`));}close(){this.controller&&(this.controller.close(),this.controller=null);}error(t){this.controller&&(this.controller.error(t),this.controller=null);}};function w(){return new d}var u=class{constructor(t){this.dataStream=t;}processToolCalls(t){if(!(!t||t.length===0))for(let n of t)try{let r=JSON.parse(n.function.arguments),e=n.function.name;switch(e){case "create_document":this.handleCreateDocument(r,n.id);break;case "update_document":this.handleUpdateDocument(r,n.id);break;default:console.log(`[ComponentStream] Unknown tool: ${e}`);}}catch(r){console.error("[ComponentStream] Error processing tool call:",r);}}processToolResult(t){try{t.type==="artifact"?this.handleArtifactResult(t):t.type==="artifact_update"&&this.handleArtifactUpdate(t);}catch(n){console.error("[ComponentStream] Error processing tool result:",n);}}streamArtifact(t){this.dataStream.write({type:"data-kind",data:t.kind,transient:true}),this.dataStream.write({type:"data-id",data:t.id,transient:true}),this.dataStream.write({type:"data-title",data:t.title,transient:true}),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(t.content),this.dataStream.write({type:"data-finish",data:null,transient:true});}streamTextDelta(t){this.dataStream.write({type:"data-textDelta",data:t,transient:true});}streamContent(t,n=50){let r=this.splitIntoChunks(t,n);for(let e of r)this.dataStream.write({type:"data-textDelta",data:e,transient:true});}finish(){this.dataStream.write({type:"data-finish",data:null,transient:true});}handleCreateDocument(t,n){let{title:r,kind:e,content:o}=t,i=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;console.log(`[ComponentStream] Creating document: ${r} (${e})`),this.streamArtifact({id:i,kind:e,title:r,content:o}),this.dataStream.write({type:"tool-result",data:{toolCallId:n,toolName:"create_document",result:{id:i,title:r,kind:e,message:"Document created successfully"}}});}handleUpdateDocument(t,n){let{id:r,description:e,content:o}=t;console.log(`[ComponentStream] Updating document: ${r}`),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(o),this.dataStream.write({type:"data-finish",data:null,transient:true}),this.dataStream.write({type:"tool-result",data:{toolCallId:n,toolName:"update_document",result:{id:r,message:`Document updated: ${e}`}}});}handleArtifactResult(t){let{id:n,title:r,kind:e,content:o}=t;if(!n||!r||!e||!o){console.error("[ComponentStream] Invalid artifact result:",t);return}this.streamArtifact({id:n,kind:e,title:r,content:o});}handleArtifactUpdate(t){let{content:n}=t;if(!n){console.error("[ComponentStream] Invalid artifact update:",t);return}this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(n),this.dataStream.write({type:"data-finish",data:null,transient:true});}splitIntoChunks(t,n){let r=[],e=t.split(" "),o="";for(let i=0;i<e.length;i++){let s=i===0?e[i]:" "+e[i];o.length+s.length>n&&o.length>0?(r.push(o),o=s.trim()):o+=s;}return o.length>0&&r.push(o),r}};function R(a){return !!(a?.tool_calls&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0)}function A(a){try{let t=JSON.parse(a);if(t.type&&(t.type==="artifact"||t.type==="artifact_update"))return [t]}catch{}return []}function v(a){return new u(a)}export{u as ComponentStreamAdapter,d as SSEWriter,v as createComponentStreamAdapter,E as createSSEResponse,w as createSSEWriter,A as extractToolResults,R as hasToolCalls,y as parseSSEStream};
|
|
9
|
+
`));}close(){this.controller&&(this.controller.close(),this.controller=null);}error(t){this.controller&&(this.controller.error(t),this.controller=null);}};function w(){return new d}var u=class{constructor(t){this.dataStream=t;}dataStream;processToolCalls(t){if(!(!t||t.length===0))for(let n of t)try{let r=JSON.parse(n.function.arguments),e=n.function.name;switch(e){case "create_document":this.handleCreateDocument(r,n.id);break;case "update_document":this.handleUpdateDocument(r,n.id);break;default:console.log(`[ComponentStream] Unknown tool: ${e}`);}}catch(r){console.error("[ComponentStream] Error processing tool call:",r);}}processToolResult(t){try{t.type==="artifact"?this.handleArtifactResult(t):t.type==="artifact_update"&&this.handleArtifactUpdate(t);}catch(n){console.error("[ComponentStream] Error processing tool result:",n);}}streamArtifact(t){this.dataStream.write({type:"data-kind",data:t.kind,transient:true}),this.dataStream.write({type:"data-id",data:t.id,transient:true}),this.dataStream.write({type:"data-title",data:t.title,transient:true}),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(t.content),this.dataStream.write({type:"data-finish",data:null,transient:true});}streamTextDelta(t){this.dataStream.write({type:"data-textDelta",data:t,transient:true});}streamContent(t,n=50){let r=this.splitIntoChunks(t,n);for(let e of r)this.dataStream.write({type:"data-textDelta",data:e,transient:true});}finish(){this.dataStream.write({type:"data-finish",data:null,transient:true});}handleCreateDocument(t,n){let{title:r,kind:e,content:o}=t,i=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;console.log(`[ComponentStream] Creating document: ${r} (${e})`),this.streamArtifact({id:i,kind:e,title:r,content:o}),this.dataStream.write({type:"tool-result",data:{toolCallId:n,toolName:"create_document",result:{id:i,title:r,kind:e,message:"Document created successfully"}}});}handleUpdateDocument(t,n){let{id:r,description:e,content:o}=t;console.log(`[ComponentStream] Updating document: ${r}`),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(o),this.dataStream.write({type:"data-finish",data:null,transient:true}),this.dataStream.write({type:"tool-result",data:{toolCallId:n,toolName:"update_document",result:{id:r,message:`Document updated: ${e}`}}});}handleArtifactResult(t){let{id:n,title:r,kind:e,content:o}=t;if(!n||!r||!e||!o){console.error("[ComponentStream] Invalid artifact result:",t);return}this.streamArtifact({id:n,kind:e,title:r,content:o});}handleArtifactUpdate(t){let{content:n}=t;if(!n){console.error("[ComponentStream] Invalid artifact update:",t);return}this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(n),this.dataStream.write({type:"data-finish",data:null,transient:true});}splitIntoChunks(t,n){let r=[],e=t.split(" "),o="";for(let i=0;i<e.length;i++){let s=i===0?e[i]:" "+e[i];o.length+s.length>n&&o.length>0?(r.push(o),o=s.trim()):o+=s;}return o.length>0&&r.push(o),r}};function R(a){return !!(a?.tool_calls&&Array.isArray(a.tool_calls)&&a.tool_calls.length>0)}function A(a){try{let t=JSON.parse(a);if(t.type&&(t.type==="artifact"||t.type==="artifact_update"))return [t]}catch{}return []}function v(a){return new u(a)}export{u as ComponentStreamAdapter,d as SSEWriter,v as createComponentStreamAdapter,E as createSSEResponse,w as createSSEWriter,A as extractToolResults,R as hasToolCalls,y as parseSSEStream};
|
package/dist/types/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as ALL_CAPABILITIES_BITMASK,
|
|
1
|
+
export { A as ALL_CAPABILITIES_BITMASK, a as ActionProof, b as AddPointsInput, c as Agent, d as AgentCreateInput, e as AgentExecuteRequest, f as AgentExecuteResponse, g as AgentFromPromptInput, h as AgentResponse, i as AgentTrigger, j as AgentUpdateInput, k as AgentWorkflow, l as AgentWorkflowEdge, m as AgentWorkflowNode, n as AgentsClientConfig, o as AgentsListResponse, p as AllowlistConfig, q as AllowlistMode, r as AllowlistUpdateInput, s as AuthMetrics, B as BillingClientConfig, t as BillingPlan, u as BillingPlansResponse, v as BillingPortalResponse, w as BillingState, x as BillingTier, C as CAPABILITY_BITS, y as CapabilityKey, z as ChatCompletionChunk, D as ChatCompletionRequest, E as ChatCompletionResponse, F as CommentResponse, G as CommentsResponse, H as ConfigureOAuthInput, I as ConfigureStripeInput, J as ConfigureWeb3Input, K as ConsensusStateSummary, L as ConsensusStatus, M as ContextDomain, N as ContextResponse, O as ContextsListResponse, P as CreateCheckoutSessionResponse, Q as CreateContextInput, R as CreateDelegationInput, S as CreateDomainInput, T as CreateKeyResponse, U as CreatePostInput, V as CreatePostResponse, W as CreateStackRequest, X as Delegation, Y as DelegationChainLink, Z as DelegationFilters, _ as DelegationResponse, $ as DelegationScope, a0 as DelegationsListResponse, a1 as DomainResponse, a2 as DomainsListResponse, a3 as FeedResponse, a4 as FileUploadResponse, a5 as FilesClientConfig, a6 as HistoryFilters, a7 as HistoryResponse, a8 as ImaginationCharacter, a9 as ImaginationMetadata, aa as ImaginationSource, ab as InitNetworkResponse, ac as LeaderStatus, ad as LikeCheckResponse, ae as LikeResponse, af as MCPContent, ag as MCPMessage, ah as MCPSession, ai as MCPSessionConfig, aj as MCPToolResult, ak as MPCNode, al as MagmaFile, am as MarkViewedInput, an as MediaType, ao as Message, ap as MeteredUsage, aq as ModelLayerInfo, ar as ModelLayersResponse, as as NetworkClientConfig, at as NetworkStatus, au as NotificationAction, av as NotificationActor, aw as NotificationCounts, ax as NotificationListResponse, ay as NotificationPostRef, az as NotificationRow, aA as Orientation, aB as PaginationMeta, aC as PaymentMethod, aD as PaymentRequiredResponse, aE as PointBalance, aF as PointContext, aG as PointRecord, aH as PointRecordResponse, aI as PointSpend, aJ as PointSpendResponse, aK as PointsClientConfig, aL as PostResponse, aM as ProfileResponse, aN as RemixesResponse, aO as Skill, aP as SkillCreateInput, aQ as SkillMapPromptResponse, aR as SkillMapResponse, aS as SkillResponse, aT as SkillSummaryResponse, aU as SkillUpdateInput, aV as SkillVerifyResponse, aW as SkillsClientConfig, aX as SkillsListResponse, aY as SocialAuthor, aZ as SocialClientConfig, a_ as SocialComment, a$ as SocialPost, b0 as SocialRemix, b1 as SolPrepaidResult, b2 as SolSubscriptionResult, b3 as SpendDestination, b4 as SpendPointsInput, b5 as StackCapabilities, b6 as StackConfig, b7 as StackKeyInfo, b8 as StackKeysListResponse, b9 as StackListResponse, ba as StackManagementClientConfig, bb as StackMember, bc as StackMemberStats, bd as StackModelAlias, be as StackOAuthProvider, bf as StackResponse, bg as StackStripeProvider, bh as StackWeb3Provider, bi as TaskPayload, bj as TaskResponse, bk as TaskState, bl as TaskStatus, bm as TaskType, bn as TopupResult, bo as UsageRecord, bp as UserClientConfig, bq as UserProfile, br as UserProfileResponse, bs as UserProfileUpdateInput, bt as Widget, bu as WidgetCreateInput, bv as WidgetResponse, bw as WidgetSystemPromptResponse, bx as WidgetUpdateInput, by as WidgetsClientConfig, bz as WidgetsListResponse, bA as WorkflowData, bB as bitmaskToCapabilities, bC as capabilitiesToBitmask } from '../billing-cj0eSVrp.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Coder type definitions
|
package/dist/types/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { A as ALL_CAPABILITIES_BITMASK,
|
|
1
|
+
export { A as ALL_CAPABILITIES_BITMASK, a as ActionProof, b as AddPointsInput, c as Agent, d as AgentCreateInput, e as AgentExecuteRequest, f as AgentExecuteResponse, g as AgentFromPromptInput, h as AgentResponse, i as AgentTrigger, j as AgentUpdateInput, k as AgentWorkflow, l as AgentWorkflowEdge, m as AgentWorkflowNode, n as AgentsClientConfig, o as AgentsListResponse, p as AllowlistConfig, q as AllowlistMode, r as AllowlistUpdateInput, s as AuthMetrics, B as BillingClientConfig, t as BillingPlan, u as BillingPlansResponse, v as BillingPortalResponse, w as BillingState, x as BillingTier, C as CAPABILITY_BITS, y as CapabilityKey, z as ChatCompletionChunk, D as ChatCompletionRequest, E as ChatCompletionResponse, F as CommentResponse, G as CommentsResponse, H as ConfigureOAuthInput, I as ConfigureStripeInput, J as ConfigureWeb3Input, K as ConsensusStateSummary, L as ConsensusStatus, M as ContextDomain, N as ContextResponse, O as ContextsListResponse, P as CreateCheckoutSessionResponse, Q as CreateContextInput, R as CreateDelegationInput, S as CreateDomainInput, T as CreateKeyResponse, U as CreatePostInput, V as CreatePostResponse, W as CreateStackRequest, X as Delegation, Y as DelegationChainLink, Z as DelegationFilters, _ as DelegationResponse, $ as DelegationScope, a0 as DelegationsListResponse, a1 as DomainResponse, a2 as DomainsListResponse, a3 as FeedResponse, a4 as FileUploadResponse, a5 as FilesClientConfig, a6 as HistoryFilters, a7 as HistoryResponse, a8 as ImaginationCharacter, a9 as ImaginationMetadata, aa as ImaginationSource, ab as InitNetworkResponse, ac as LeaderStatus, ad as LikeCheckResponse, ae as LikeResponse, af as MCPContent, ag as MCPMessage, ah as MCPSession, ai as MCPSessionConfig, aj as MCPToolResult, ak as MPCNode, al as MagmaFile, am as MarkViewedInput, an as MediaType, ao as Message, ap as MeteredUsage, aq as ModelLayerInfo, ar as ModelLayersResponse, as as NetworkClientConfig, at as NetworkStatus, au as NotificationAction, av as NotificationActor, aw as NotificationCounts, ax as NotificationListResponse, ay as NotificationPostRef, az as NotificationRow, aA as Orientation, aB as PaginationMeta, aC as PaymentMethod, aD as PaymentRequiredResponse, aE as PointBalance, aF as PointContext, aG as PointRecord, aH as PointRecordResponse, aI as PointSpend, aJ as PointSpendResponse, aK as PointsClientConfig, aL as PostResponse, aM as ProfileResponse, aN as RemixesResponse, aO as Skill, aP as SkillCreateInput, aQ as SkillMapPromptResponse, aR as SkillMapResponse, aS as SkillResponse, aT as SkillSummaryResponse, aU as SkillUpdateInput, aV as SkillVerifyResponse, aW as SkillsClientConfig, aX as SkillsListResponse, aY as SocialAuthor, aZ as SocialClientConfig, a_ as SocialComment, a$ as SocialPost, b0 as SocialRemix, b1 as SolPrepaidResult, b2 as SolSubscriptionResult, b3 as SpendDestination, b4 as SpendPointsInput, b5 as StackCapabilities, b6 as StackConfig, b7 as StackKeyInfo, b8 as StackKeysListResponse, b9 as StackListResponse, ba as StackManagementClientConfig, bb as StackMember, bc as StackMemberStats, bd as StackModelAlias, be as StackOAuthProvider, bf as StackResponse, bg as StackStripeProvider, bh as StackWeb3Provider, bi as TaskPayload, bj as TaskResponse, bk as TaskState, bl as TaskStatus, bm as TaskType, bn as TopupResult, bo as UsageRecord, bp as UserClientConfig, bq as UserProfile, br as UserProfileResponse, bs as UserProfileUpdateInput, bt as Widget, bu as WidgetCreateInput, bv as WidgetResponse, bw as WidgetSystemPromptResponse, bx as WidgetUpdateInput, by as WidgetsClientConfig, bz as WidgetsListResponse, bA as WorkflowData, bB as bitmaskToCapabilities, bC as capabilitiesToBitmask } from '../billing-cj0eSVrp.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Coder type definitions
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@stacknet/stacks",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.2",
|
|
4
4
|
"description": "SDK for connecting to StackNet",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|
|
@@ -35,22 +35,14 @@
|
|
|
35
35
|
},
|
|
36
36
|
"files": [
|
|
37
37
|
"dist",
|
|
38
|
-
"
|
|
38
|
+
"README.md"
|
|
39
39
|
],
|
|
40
|
-
"scripts": {
|
|
41
|
-
"build": "tsup",
|
|
42
|
-
"build:publish": "tsup --no-sourcemap --minify",
|
|
43
|
-
"dev": "tsup --watch",
|
|
44
|
-
"clean": "rm -rf dist",
|
|
45
|
-
"typecheck": "tsc --noEmit",
|
|
46
|
-
"prepublishOnly": "pnpm run clean && pnpm run typecheck && pnpm run build:publish",
|
|
47
|
-
"release": "pnpm run prepublishOnly && npm publish --access public"
|
|
48
|
-
},
|
|
49
40
|
"dependencies": {
|
|
50
41
|
"@xenova/transformers": "^2.17.2",
|
|
51
42
|
"redis": "^4.7.0"
|
|
52
43
|
},
|
|
53
44
|
"devDependencies": {
|
|
45
|
+
"@types/bun": "latest",
|
|
54
46
|
"@types/node": "^20.0.0",
|
|
55
47
|
"tsup": "^8.0.0",
|
|
56
48
|
"typescript": "^5.0.0"
|
|
@@ -71,5 +63,15 @@
|
|
|
71
63
|
"ai",
|
|
72
64
|
"sdk"
|
|
73
65
|
],
|
|
74
|
-
"license": "MIT"
|
|
75
|
-
|
|
66
|
+
"license": "MIT",
|
|
67
|
+
"scripts": {
|
|
68
|
+
"build": "tsup",
|
|
69
|
+
"build:publish": "tsup --no-sourcemap --minify",
|
|
70
|
+
"dev": "tsup --watch",
|
|
71
|
+
"clean": "rm -rf dist",
|
|
72
|
+
"typecheck": "tsc --noEmit",
|
|
73
|
+
"release": "pnpm run prepublishOnly && npm publish --access public",
|
|
74
|
+
"test": "bun test",
|
|
75
|
+
"coverage": "bun test --coverage"
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/clients/agents.ts
DELETED
|
@@ -1,250 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Agents Client
|
|
3
|
-
* Client for interacting with the agents API
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { DEFAULT_TASK_NETWORK_URL, JSON_HEADERS } from '../utils/constants';
|
|
7
|
-
import { StacksSDKError } from '../utils/errors';
|
|
8
|
-
import type {
|
|
9
|
-
Agent,
|
|
10
|
-
AgentsListResponse,
|
|
11
|
-
AgentResponse,
|
|
12
|
-
AgentCreateInput,
|
|
13
|
-
AgentUpdateInput,
|
|
14
|
-
AgentFromPromptInput,
|
|
15
|
-
AgentExecuteRequest,
|
|
16
|
-
AgentExecuteResponse,
|
|
17
|
-
AgentsClientConfig,
|
|
18
|
-
} from '../types/agent';
|
|
19
|
-
|
|
20
|
-
export type { AgentsClientConfig } from '../types/agent';
|
|
21
|
-
|
|
22
|
-
export class AgentsClient {
|
|
23
|
-
private baseUrl: string;
|
|
24
|
-
private useCpxApi: boolean;
|
|
25
|
-
private authToken: string | null;
|
|
26
|
-
|
|
27
|
-
constructor(config: AgentsClientConfig = {}) {
|
|
28
|
-
this.baseUrl = config.baseUrl || DEFAULT_TASK_NETWORK_URL;
|
|
29
|
-
// Use coprocessor API by default (can be disabled for backwards compatibility)
|
|
30
|
-
this.useCpxApi = config.useCpxApi !== false;
|
|
31
|
-
this.authToken = config.authToken || null;
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
setAuthToken(token: string | null) {
|
|
35
|
-
this.authToken = token;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
private get headers(): Record<string, string> {
|
|
39
|
-
const h: Record<string, string> = { ...JSON_HEADERS };
|
|
40
|
-
if (this.authToken) {
|
|
41
|
-
h['Authorization'] = `Bearer ${this.authToken}`;
|
|
42
|
-
}
|
|
43
|
-
return h;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
private get agentsUrl(): string {
|
|
47
|
-
// Route through Agent Coprocessor at /cpx/agent/agents
|
|
48
|
-
return this.useCpxApi
|
|
49
|
-
? `${this.baseUrl}/cpx/agent/agents`
|
|
50
|
-
: `${this.baseUrl}/agents`;
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* List all agents
|
|
55
|
-
*/
|
|
56
|
-
async list(options: { userMid?: string } = {}): Promise<AgentsListResponse> {
|
|
57
|
-
const params = new URLSearchParams();
|
|
58
|
-
if (options.userMid) {
|
|
59
|
-
params.set('userMid', options.userMid);
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
const queryString = params.toString();
|
|
63
|
-
const url = `${this.agentsUrl}${queryString ? `?${queryString}` : ''}`;
|
|
64
|
-
|
|
65
|
-
const response = await fetch(url, { headers: this.headers });
|
|
66
|
-
|
|
67
|
-
if (!response.ok) {
|
|
68
|
-
throw new StacksSDKError(
|
|
69
|
-
'bad_request:api',
|
|
70
|
-
`Failed to list agents: ${response.statusText}`
|
|
71
|
-
);
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
return response.json();
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Get an agent by ID
|
|
79
|
-
*/
|
|
80
|
-
async get(id: string): Promise<Agent> {
|
|
81
|
-
const response = await fetch(`${this.agentsUrl}/${id}`, { headers: this.headers });
|
|
82
|
-
|
|
83
|
-
if (!response.ok) {
|
|
84
|
-
throw new StacksSDKError(
|
|
85
|
-
response.status === 404 ? 'not_found:api' : 'bad_request:api',
|
|
86
|
-
`Failed to get agent: ${response.statusText}`
|
|
87
|
-
);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
return response.json();
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/**
|
|
94
|
-
* Create a new agent
|
|
95
|
-
*/
|
|
96
|
-
async create(input: AgentCreateInput): Promise<AgentResponse> {
|
|
97
|
-
const response = await fetch(this.agentsUrl, {
|
|
98
|
-
method: 'POST',
|
|
99
|
-
headers: this.headers,
|
|
100
|
-
body: JSON.stringify(input),
|
|
101
|
-
});
|
|
102
|
-
|
|
103
|
-
if (!response.ok) {
|
|
104
|
-
const data = await response.json().catch(() => ({}));
|
|
105
|
-
throw new StacksSDKError(
|
|
106
|
-
'bad_request:api',
|
|
107
|
-
data.error || `Failed to create agent: ${response.statusText}`
|
|
108
|
-
);
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
return response.json();
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/**
|
|
115
|
-
* Update an agent
|
|
116
|
-
*/
|
|
117
|
-
async update(id: string, input: AgentUpdateInput): Promise<AgentResponse> {
|
|
118
|
-
const response = await fetch(`${this.agentsUrl}/${id}`, {
|
|
119
|
-
method: 'PUT',
|
|
120
|
-
headers: this.headers,
|
|
121
|
-
body: JSON.stringify(input),
|
|
122
|
-
});
|
|
123
|
-
|
|
124
|
-
if (!response.ok) {
|
|
125
|
-
const data = await response.json().catch(() => ({}));
|
|
126
|
-
throw new StacksSDKError(
|
|
127
|
-
'bad_request:api',
|
|
128
|
-
data.error || `Failed to update agent: ${response.statusText}`
|
|
129
|
-
);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
return response.json();
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
/**
|
|
136
|
-
* Delete an agent
|
|
137
|
-
*/
|
|
138
|
-
async delete(id: string): Promise<{ success: boolean }> {
|
|
139
|
-
const response = await fetch(`${this.agentsUrl}/${id}`, {
|
|
140
|
-
method: 'DELETE',
|
|
141
|
-
headers: this.headers,
|
|
142
|
-
});
|
|
143
|
-
|
|
144
|
-
if (!response.ok) {
|
|
145
|
-
throw new StacksSDKError(
|
|
146
|
-
'bad_request:api',
|
|
147
|
-
`Failed to delete agent: ${response.statusText}`
|
|
148
|
-
);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
return response.json();
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/**
|
|
155
|
-
* Enable an agent
|
|
156
|
-
*/
|
|
157
|
-
async enable(id: string): Promise<AgentResponse> {
|
|
158
|
-
const response = await fetch(`${this.agentsUrl}/${id}/enable`, {
|
|
159
|
-
method: 'POST',
|
|
160
|
-
headers: this.headers,
|
|
161
|
-
});
|
|
162
|
-
|
|
163
|
-
if (!response.ok) {
|
|
164
|
-
throw new StacksSDKError(
|
|
165
|
-
'bad_request:api',
|
|
166
|
-
`Failed to enable agent: ${response.statusText}`
|
|
167
|
-
);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
return response.json();
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Disable an agent
|
|
175
|
-
*/
|
|
176
|
-
async disable(id: string): Promise<AgentResponse> {
|
|
177
|
-
const response = await fetch(`${this.agentsUrl}/${id}/disable`, {
|
|
178
|
-
method: 'POST',
|
|
179
|
-
headers: this.headers,
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
if (!response.ok) {
|
|
183
|
-
throw new StacksSDKError(
|
|
184
|
-
'bad_request:api',
|
|
185
|
-
`Failed to disable agent: ${response.statusText}`
|
|
186
|
-
);
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
return response.json();
|
|
190
|
-
}
|
|
191
|
-
|
|
192
|
-
/**
|
|
193
|
-
* Execute an agent
|
|
194
|
-
*/
|
|
195
|
-
async execute(id: string, request: AgentExecuteRequest = {}): Promise<AgentExecuteResponse> {
|
|
196
|
-
const response = await fetch(`${this.agentsUrl}/${id}/execute`, {
|
|
197
|
-
method: 'POST',
|
|
198
|
-
headers: this.headers,
|
|
199
|
-
body: JSON.stringify(request),
|
|
200
|
-
});
|
|
201
|
-
|
|
202
|
-
if (!response.ok) {
|
|
203
|
-
throw new StacksSDKError(
|
|
204
|
-
'bad_request:api',
|
|
205
|
-
`Failed to execute agent: ${response.statusText}`
|
|
206
|
-
);
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
return response.json();
|
|
210
|
-
}
|
|
211
|
-
|
|
212
|
-
/**
|
|
213
|
-
* Create agent from prompt (AI-generated)
|
|
214
|
-
*/
|
|
215
|
-
async createFromPrompt(input: AgentFromPromptInput): Promise<AgentResponse> {
|
|
216
|
-
// First, generate agent config from prompt
|
|
217
|
-
const generateResponse = await fetch(`${this.agentsUrl}/from-prompt`, {
|
|
218
|
-
method: 'POST',
|
|
219
|
-
headers: this.headers,
|
|
220
|
-
body: JSON.stringify(input),
|
|
221
|
-
});
|
|
222
|
-
|
|
223
|
-
if (!generateResponse.ok) {
|
|
224
|
-
throw new StacksSDKError(
|
|
225
|
-
'bad_request:api',
|
|
226
|
-
`Failed to generate agent from prompt: ${generateResponse.statusText}`
|
|
227
|
-
);
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
const agentConfig = await generateResponse.json();
|
|
231
|
-
|
|
232
|
-
// Then create the agent
|
|
233
|
-
return this.create({
|
|
234
|
-
...agentConfig,
|
|
235
|
-
created_by: input.created_by,
|
|
236
|
-
});
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/**
|
|
241
|
-
* Create an AgentsClient instance
|
|
242
|
-
*/
|
|
243
|
-
export function createAgentsClient(config: AgentsClientConfig = {}): AgentsClient {
|
|
244
|
-
return new AgentsClient(config);
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
/**
|
|
248
|
-
* Default agents client instance
|
|
249
|
-
*/
|
|
250
|
-
export const agentsClient = createAgentsClient();
|
package/src/clients/billing.ts
DELETED
|
@@ -1,197 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Billing Client
|
|
3
|
-
* Plans, checkout, usage, and payment management scoped to a stack
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
import { DEFAULT_GLAYER_NETWORK_URL, JSON_HEADERS } from '../utils/constants';
|
|
7
|
-
import { StacksSDKError } from '../utils/errors';
|
|
8
|
-
import type {
|
|
9
|
-
BillingState,
|
|
10
|
-
BillingPlansResponse,
|
|
11
|
-
CreateCheckoutSessionResponse,
|
|
12
|
-
BillingPortalResponse,
|
|
13
|
-
BillingClientConfig,
|
|
14
|
-
} from '../types/billing';
|
|
15
|
-
|
|
16
|
-
export type { BillingClientConfig } from '../types/billing';
|
|
17
|
-
|
|
18
|
-
const API_PATH = '/api/v2';
|
|
19
|
-
|
|
20
|
-
export class BillingClient {
|
|
21
|
-
private baseUrl: string;
|
|
22
|
-
private authToken: string | null;
|
|
23
|
-
|
|
24
|
-
constructor(config: BillingClientConfig = {}) {
|
|
25
|
-
this.baseUrl = config.baseUrl || DEFAULT_GLAYER_NETWORK_URL;
|
|
26
|
-
this.authToken = config.authToken || null;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
setAuthToken(token: string | null) {
|
|
30
|
-
this.authToken = token;
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
private get headers(): Record<string, string> {
|
|
34
|
-
const h: Record<string, string> = { ...JSON_HEADERS };
|
|
35
|
-
if (this.authToken) {
|
|
36
|
-
h['Authorization'] = `Bearer ${this.authToken}`;
|
|
37
|
-
}
|
|
38
|
-
return h;
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
private url(path: string): string {
|
|
42
|
-
return `${this.baseUrl}${API_PATH}${path}`;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
private async request<T>(method: string, path: string, body?: unknown): Promise<T> {
|
|
46
|
-
const opts: RequestInit = { method, headers: this.headers };
|
|
47
|
-
if (body && method !== 'GET') {
|
|
48
|
-
opts.body = JSON.stringify(body);
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const response = await fetch(this.url(path), opts);
|
|
52
|
-
|
|
53
|
-
if (!response.ok) {
|
|
54
|
-
const data = await response.json().catch(() => ({}));
|
|
55
|
-
throw new StacksSDKError(
|
|
56
|
-
response.status === 402 ? 'payment_required:api' : 'bad_request:api',
|
|
57
|
-
data.error?.message || `Request failed: ${response.statusText}`
|
|
58
|
-
);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
const data = await response.json();
|
|
62
|
-
return (data && typeof data === 'object' && 'data' in data) ? data.data : data;
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
// =========================================================================
|
|
66
|
-
// Plans
|
|
67
|
-
// =========================================================================
|
|
68
|
-
|
|
69
|
-
async getPlans(stackId: string): Promise<BillingPlansResponse> {
|
|
70
|
-
return this.request<BillingPlansResponse>('GET', `/stacks/${stackId}/billing/plans`);
|
|
71
|
-
}
|
|
72
|
-
|
|
73
|
-
// =========================================================================
|
|
74
|
-
// Billing State
|
|
75
|
-
// =========================================================================
|
|
76
|
-
|
|
77
|
-
async getBillingState(stackId: string, identityId: string): Promise<BillingState> {
|
|
78
|
-
return this.request<BillingState>('GET', `/stacks/${stackId}/identities/${identityId}/billing`);
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
// =========================================================================
|
|
82
|
-
// Checkout & Portal
|
|
83
|
-
// =========================================================================
|
|
84
|
-
|
|
85
|
-
async createCheckoutSession(
|
|
86
|
-
stackId: string,
|
|
87
|
-
identityId: string,
|
|
88
|
-
planId: string,
|
|
89
|
-
successUrl: string,
|
|
90
|
-
cancelUrl: string
|
|
91
|
-
): Promise<CreateCheckoutSessionResponse> {
|
|
92
|
-
return this.request<CreateCheckoutSessionResponse>('POST', `/stacks/${stackId}/billing/checkout`, {
|
|
93
|
-
identity_id: identityId,
|
|
94
|
-
plan_id: planId,
|
|
95
|
-
success_url: successUrl,
|
|
96
|
-
cancel_url: cancelUrl,
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
async createBillingPortal(stackId: string, identityId: string, returnUrl: string): Promise<BillingPortalResponse> {
|
|
101
|
-
return this.request<BillingPortalResponse>('POST', `/stacks/${stackId}/billing/portal`, {
|
|
102
|
-
identity_id: identityId,
|
|
103
|
-
return_url: returnUrl,
|
|
104
|
-
});
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
// =========================================================================
|
|
108
|
-
// Usage
|
|
109
|
-
// =========================================================================
|
|
110
|
-
|
|
111
|
-
async recordUsage(
|
|
112
|
-
stackId: string,
|
|
113
|
-
identityId: string,
|
|
114
|
-
usageType: string,
|
|
115
|
-
quantity: number,
|
|
116
|
-
idempotencyKey?: string
|
|
117
|
-
): Promise<{ recorded: boolean; total_usage: number }> {
|
|
118
|
-
return this.request('POST', `/stacks/${stackId}/billing/usage`, {
|
|
119
|
-
identity_id: identityId,
|
|
120
|
-
usage_type: usageType,
|
|
121
|
-
quantity,
|
|
122
|
-
idempotency_key: idempotencyKey,
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
async getCurrentUsage(stackId: string, identityId: string): Promise<{ usage: { type: string; quantity: number; amount: number }[]; total_amount: number }> {
|
|
127
|
-
return this.request('GET', `/stacks/${stackId}/identities/${identityId}/billing/usage`);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
// =========================================================================
|
|
131
|
-
// Payment Method
|
|
132
|
-
// =========================================================================
|
|
133
|
-
|
|
134
|
-
async linkStripeCustomer(stackId: string, identityId: string, stripeCustomerId: string, sessionId: string): Promise<{ linked: boolean }> {
|
|
135
|
-
return this.request('POST', `/stacks/${stackId}/billing/link`, {
|
|
136
|
-
identity_id: identityId,
|
|
137
|
-
stripe_customer_id: stripeCustomerId,
|
|
138
|
-
checkout_session_id: sessionId,
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
|
|
142
|
-
async hasPaymentMethod(stackId: string, identityId: string): Promise<{ has_payment_method: boolean; card_last_four?: string; card_brand?: string }> {
|
|
143
|
-
return this.request('GET', `/stacks/${stackId}/identities/${identityId}/billing/payment-method`);
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
// =========================================================================
|
|
147
|
-
// SOL Payment Methods (additive — Stripe methods above remain unchanged)
|
|
148
|
-
// =========================================================================
|
|
149
|
-
|
|
150
|
-
/**
|
|
151
|
-
* Subscribe to a plan using SOL payment.
|
|
152
|
-
* Client must build and sign the SOL transaction first,
|
|
153
|
-
* then pass the on-chain tx signature here for verification.
|
|
154
|
-
*/
|
|
155
|
-
async subscribeSol(
|
|
156
|
-
stackId: string,
|
|
157
|
-
planId: string,
|
|
158
|
-
txSignature: string,
|
|
159
|
-
): Promise<{ subscription: { id: string; planId: string; planName: string; status: string; tokensGranted: number } }> {
|
|
160
|
-
return this.request('POST', `/stacks/${stackId}/subscribe-sol`, { planId, txSignature });
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* One-time prepaid credit via SOL payment.
|
|
165
|
-
*/
|
|
166
|
-
async prepaidSol(
|
|
167
|
-
stackId: string,
|
|
168
|
-
amountCents: number,
|
|
169
|
-
txSignature: string,
|
|
170
|
-
scope?: 'global' | 'stack',
|
|
171
|
-
): Promise<{ alreadyCredited: boolean; tokensCredited?: number; amountCents?: number; paymentRef?: string }> {
|
|
172
|
-
return this.request('POST', `/stacks/${stackId}/prepaid-sol`, { amountCents, txSignature, scope });
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
/**
|
|
176
|
-
* Top up account via x402 payment proof (SOL or Stripe).
|
|
177
|
-
*/
|
|
178
|
-
async topup(
|
|
179
|
-
amountCents: number,
|
|
180
|
-
paymentMethod: 'solana' | 'stripe',
|
|
181
|
-
paymentRef: string,
|
|
182
|
-
): Promise<{ success: boolean; tokensCredited: number; tokenBalance: number }> {
|
|
183
|
-
return this.request('POST', '/account/topup', { amount_cents: amountCents, payment_method: paymentMethod, payment_ref: paymentRef });
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
|
|
187
|
-
/**
|
|
188
|
-
* Create a BillingClient instance
|
|
189
|
-
*/
|
|
190
|
-
export function createBillingClient(config: BillingClientConfig = {}): BillingClient {
|
|
191
|
-
return new BillingClient(config);
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
/**
|
|
195
|
-
* Default billing client instance
|
|
196
|
-
*/
|
|
197
|
-
export const billingClient = createBillingClient();
|