@stacknet/stacks 0.1.2 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +136 -0
  2. package/dist/{billing-BqscteyZ.d.cts → billing-cj0eSVrp.d.cts} +61 -1
  3. package/dist/{billing-BqscteyZ.d.ts → billing-cj0eSVrp.d.ts} +61 -1
  4. package/dist/clients/index.cjs +4 -4
  5. package/dist/clients/index.d.cts +27 -1
  6. package/dist/clients/index.d.ts +27 -1
  7. package/dist/clients/index.js +4 -4
  8. package/dist/{index-DVzKiF_0.d.cts → index-B_dUFmAg.d.cts} +31 -6
  9. package/dist/{index-DVzKiF_0.d.ts → index-B_dUFmAg.d.ts} +31 -6
  10. package/dist/index.cjs +12 -16
  11. package/dist/index.d.cts +4 -4
  12. package/dist/index.d.ts +4 -4
  13. package/dist/index.js +12 -16
  14. package/dist/proxy/index.cjs +2 -2
  15. package/dist/proxy/index.d.cts +1 -1
  16. package/dist/proxy/index.d.ts +1 -1
  17. package/dist/proxy/index.js +2 -2
  18. package/dist/streaming/index.cjs +8 -12
  19. package/dist/streaming/index.js +8 -12
  20. package/dist/types/index.d.cts +1 -1
  21. package/dist/types/index.d.ts +1 -1
  22. package/package.json +15 -13
  23. package/src/clients/agents.ts +0 -233
  24. package/src/clients/billing.ts +0 -197
  25. package/src/clients/coder.ts +0 -655
  26. package/src/clients/files.ts +0 -86
  27. package/src/clients/index.ts +0 -93
  28. package/src/clients/magma.ts +0 -299
  29. package/src/clients/mcp.ts +0 -208
  30. package/src/clients/network.ts +0 -118
  31. package/src/clients/points.ts +0 -403
  32. package/src/clients/skills.ts +0 -236
  33. package/src/clients/social.ts +0 -286
  34. package/src/clients/stack-management.ts +0 -279
  35. package/src/clients/task-network.ts +0 -303
  36. package/src/clients/user.ts +0 -84
  37. package/src/clients/widgets.ts +0 -171
  38. package/src/index.ts +0 -387
  39. package/src/managers/index.ts +0 -10
  40. package/src/managers/task-manager.ts +0 -310
  41. package/src/proxy/forwarder.ts +0 -146
  42. package/src/proxy/index.ts +0 -32
  43. package/src/proxy/route-handlers.ts +0 -950
  44. package/src/streaming/component-stream.ts +0 -319
  45. package/src/streaming/index.ts +0 -21
  46. package/src/streaming/sse.ts +0 -241
  47. package/src/types/agent.ts +0 -106
  48. package/src/types/billing.ts +0 -121
  49. package/src/types/chat.ts +0 -58
  50. package/src/types/coder.ts +0 -345
  51. package/src/types/credential.ts +0 -111
  52. package/src/types/file.ts +0 -15
  53. package/src/types/imagination.ts +0 -50
  54. package/src/types/index.ts +0 -20
  55. package/src/types/mcp.ts +0 -35
  56. package/src/types/network.ts +0 -97
  57. package/src/types/points.ts +0 -250
  58. package/src/types/skill.ts +0 -107
  59. package/src/types/social.ts +0 -109
  60. package/src/types/stack.ts +0 -269
  61. package/src/types/task.ts +0 -41
  62. package/src/types/user.ts +0 -29
  63. package/src/types/widget.ts +0 -57
  64. package/src/utils/constants.ts +0 -26
  65. package/src/utils/errors.ts +0 -169
  66. package/src/utils/helpers.ts +0 -85
  67. package/src/utils/index.ts +0 -7
@@ -1,13 +1,9 @@
1
- 'use strict';var m={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};async function*S(i){if(!i.body)throw new Error("Response body is null");let t=i.body.getReader(),r=new TextDecoder,n="",e={};try{for(;;){let{done:a,value:o}=await t.read();if(a)break;n+=r.decode(o,{stream:!0});let s=n.split(`
2
- `);n=s.pop()||"";for(let c of s){if(c===""){e.data!==void 0&&(yield e),e={};continue}if(c.startsWith(":"))continue;let u=c.indexOf(":");if(u===-1)continue;let f=c.slice(0,u),l=c.slice(u+1).trimStart();switch(f){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(i,t){let r=new TextEncoder,n=new ReadableStream({async start(e){try{for await(let a of i){let o="";a.event&&(o+=`event: ${a.event}
3
- `),a.id&&(o+=`id: ${a.id}
4
- `),a.retry&&(o+=`retry: ${a.retry}
5
- `);let s=typeof a.data=="string"?a.data:JSON.stringify(a.data);o+=`data: ${s}
1
+ 'use strict';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
+ `),a.retry!==void 0&&Number.isFinite(a.retry)&&(t+=`retry: ${Math.floor(a.retry)}
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
+ `;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=S(t);this.controller.enqueue(this.encoder.encode(`: ${n}
6
8
 
7
- `,e.enqueue(r.encode(o));}}catch(a){console.error("SSE stream error:",a);}finally{e.close();}}});return new Response(n,{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){if(!this.controller)return;let r="";t.event&&(r+=`event: ${t.event}
8
- `),t.id&&(r+=`id: ${t.id}
9
- `);let n=typeof t.data=="string"?t.data:JSON.stringify(t.data);r+=`data: ${n}
10
-
11
- `,this.controller.enqueue(this.encoder.encode(r));}writeData(t){this.write({data:t});}writeComment(t){this.controller&&this.controller.enqueue(this.encoder.encode(`: ${t}
12
-
13
- `));}close(){this.controller&&(this.controller.close(),this.controller=null);}error(t){this.controller&&(this.controller.error(t),this.controller=null);}};function g(){return new d}var p=class{constructor(t){this.dataStream=t;}processToolCalls(t){if(!(!t||t.length===0))for(let r of t)try{let n=JSON.parse(r.function.arguments),e=r.function.name;switch(e){case "create_document":this.handleCreateDocument(n,r.id);break;case "update_document":this.handleUpdateDocument(n,r.id);break;default:console.log(`[ComponentStream] Unknown tool: ${e}`);}}catch(n){console.error("[ComponentStream] Error processing tool call:",n);}}processToolResult(t){try{t.type==="artifact"?this.handleArtifactResult(t):t.type==="artifact_update"&&this.handleArtifactUpdate(t);}catch(r){console.error("[ComponentStream] Error processing tool result:",r);}}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,r=50){let n=this.splitIntoChunks(t,r);for(let e of n)this.dataStream.write({type:"data-textDelta",data:e,transient:true});}finish(){this.dataStream.write({type:"data-finish",data:null,transient:true});}handleCreateDocument(t,r){let{title:n,kind:e,content:a}=t,o=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;console.log(`[ComponentStream] Creating document: ${n} (${e})`),this.streamArtifact({id:o,kind:e,title:n,content:a}),this.dataStream.write({type:"tool-result",data:{toolCallId:r,toolName:"create_document",result:{id:o,title:n,kind:e,message:"Document created successfully"}}});}handleUpdateDocument(t,r){let{id:n,description:e,content:a}=t;console.log(`[ComponentStream] Updating document: ${n}`),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(a),this.dataStream.write({type:"data-finish",data:null,transient:true}),this.dataStream.write({type:"tool-result",data:{toolCallId:r,toolName:"update_document",result:{id:n,message:`Document updated: ${e}`}}});}handleArtifactResult(t){let{id:r,title:n,kind:e,content:a}=t;if(!r||!n||!e||!a){console.error("[ComponentStream] Invalid artifact result:",t);return}this.streamArtifact({id:r,kind:e,title:n,content:a});}handleArtifactUpdate(t){let{content:r}=t;if(!r){console.error("[ComponentStream] Invalid artifact update:",t);return}this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(r),this.dataStream.write({type:"data-finish",data:null,transient:true});}splitIntoChunks(t,r){let n=[],e=t.split(" "),a="";for(let o=0;o<e.length;o++){let s=o===0?e[o]:" "+e[o];a.length+s.length>r&&a.length>0?(n.push(a),a=s.trim()):a+=s;}return a.length>0&&n.push(a),n}};function y(i){return !!(i?.tool_calls&&Array.isArray(i.tool_calls)&&i.tool_calls.length>0)}function E(i){try{let t=JSON.parse(i);if(t.type&&(t.type==="artifact"||t.type==="artifact_update"))return [t]}catch{}return []}function v(i){return new p(i)}exports.ComponentStreamAdapter=p;exports.SSEWriter=d;exports.createComponentStreamAdapter=v;exports.createSSEResponse=h;exports.createSSEWriter=g;exports.extractToolResults=E;exports.hasToolCalls=y;exports.parseSSEStream=S;
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)}exports.ComponentStreamAdapter=u;exports.SSEWriter=d;exports.createComponentStreamAdapter=v;exports.createSSEResponse=E;exports.createSSEWriter=w;exports.extractToolResults=A;exports.hasToolCalls=R;exports.parseSSEStream=y;
@@ -1,13 +1,9 @@
1
- var m={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};async function*S(i){if(!i.body)throw new Error("Response body is null");let t=i.body.getReader(),r=new TextDecoder,n="",e={};try{for(;;){let{done:a,value:o}=await t.read();if(a)break;n+=r.decode(o,{stream:!0});let s=n.split(`
2
- `);n=s.pop()||"";for(let c of s){if(c===""){e.data!==void 0&&(yield e),e={};continue}if(c.startsWith(":"))continue;let u=c.indexOf(":");if(u===-1)continue;let f=c.slice(0,u),l=c.slice(u+1).trimStart();switch(f){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(i,t){let r=new TextEncoder,n=new ReadableStream({async start(e){try{for await(let a of i){let o="";a.event&&(o+=`event: ${a.event}
3
- `),a.id&&(o+=`id: ${a.id}
4
- `),a.retry&&(o+=`retry: ${a.retry}
5
- `);let s=typeof a.data=="string"?a.data:JSON.stringify(a.data);o+=`data: ${s}
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
+ `),a.retry!==void 0&&Number.isFinite(a.retry)&&(t+=`retry: ${Math.floor(a.retry)}
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
+ `;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=S(t);this.controller.enqueue(this.encoder.encode(`: ${n}
6
8
 
7
- `,e.enqueue(r.encode(o));}}catch(a){console.error("SSE stream error:",a);}finally{e.close();}}});return new Response(n,{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){if(!this.controller)return;let r="";t.event&&(r+=`event: ${t.event}
8
- `),t.id&&(r+=`id: ${t.id}
9
- `);let n=typeof t.data=="string"?t.data:JSON.stringify(t.data);r+=`data: ${n}
10
-
11
- `,this.controller.enqueue(this.encoder.encode(r));}writeData(t){this.write({data:t});}writeComment(t){this.controller&&this.controller.enqueue(this.encoder.encode(`: ${t}
12
-
13
- `));}close(){this.controller&&(this.controller.close(),this.controller=null);}error(t){this.controller&&(this.controller.error(t),this.controller=null);}};function g(){return new d}var p=class{constructor(t){this.dataStream=t;}processToolCalls(t){if(!(!t||t.length===0))for(let r of t)try{let n=JSON.parse(r.function.arguments),e=r.function.name;switch(e){case "create_document":this.handleCreateDocument(n,r.id);break;case "update_document":this.handleUpdateDocument(n,r.id);break;default:console.log(`[ComponentStream] Unknown tool: ${e}`);}}catch(n){console.error("[ComponentStream] Error processing tool call:",n);}}processToolResult(t){try{t.type==="artifact"?this.handleArtifactResult(t):t.type==="artifact_update"&&this.handleArtifactUpdate(t);}catch(r){console.error("[ComponentStream] Error processing tool result:",r);}}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,r=50){let n=this.splitIntoChunks(t,r);for(let e of n)this.dataStream.write({type:"data-textDelta",data:e,transient:true});}finish(){this.dataStream.write({type:"data-finish",data:null,transient:true});}handleCreateDocument(t,r){let{title:n,kind:e,content:a}=t,o=`doc_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;console.log(`[ComponentStream] Creating document: ${n} (${e})`),this.streamArtifact({id:o,kind:e,title:n,content:a}),this.dataStream.write({type:"tool-result",data:{toolCallId:r,toolName:"create_document",result:{id:o,title:n,kind:e,message:"Document created successfully"}}});}handleUpdateDocument(t,r){let{id:n,description:e,content:a}=t;console.log(`[ComponentStream] Updating document: ${n}`),this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(a),this.dataStream.write({type:"data-finish",data:null,transient:true}),this.dataStream.write({type:"tool-result",data:{toolCallId:r,toolName:"update_document",result:{id:n,message:`Document updated: ${e}`}}});}handleArtifactResult(t){let{id:r,title:n,kind:e,content:a}=t;if(!r||!n||!e||!a){console.error("[ComponentStream] Invalid artifact result:",t);return}this.streamArtifact({id:r,kind:e,title:n,content:a});}handleArtifactUpdate(t){let{content:r}=t;if(!r){console.error("[ComponentStream] Invalid artifact update:",t);return}this.dataStream.write({type:"data-clear",data:null,transient:true}),this.streamContent(r),this.dataStream.write({type:"data-finish",data:null,transient:true});}splitIntoChunks(t,r){let n=[],e=t.split(" "),a="";for(let o=0;o<e.length;o++){let s=o===0?e[o]:" "+e[o];a.length+s.length>r&&a.length>0?(n.push(a),a=s.trim()):a+=s;}return a.length>0&&n.push(a),n}};function y(i){return !!(i?.tool_calls&&Array.isArray(i.tool_calls)&&i.tool_calls.length>0)}function E(i){try{let t=JSON.parse(i);if(t.type&&(t.type==="artifact"||t.type==="artifact_update"))return [t]}catch{}return []}function v(i){return new p(i)}export{p as ComponentStreamAdapter,d as SSEWriter,v as createComponentStreamAdapter,h as createSSEResponse,g as createSSEWriter,E as extractToolResults,y as hasToolCalls,S 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};
@@ -1,4 +1,4 @@
1
- export { A as ALL_CAPABILITIES_BITMASK, c as ActionProof, d as AddPointsInput, e as Agent, f as AgentCreateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, j as AgentResponse, k as AgentTrigger, l as AgentUpdateInput, m as AgentWorkflow, n as AgentWorkflowEdge, o as AgentWorkflowNode, p as AgentsClientConfig, q as AgentsListResponse, r as AllowlistConfig, s as AllowlistMode, t as AllowlistUpdateInput, u as AuthMetrics, B as BillingClientConfig, v as BillingPlan, w as BillingPlansResponse, x as BillingPortalResponse, y as BillingState, z as BillingTier, C as CAPABILITY_BITS, D as CapabilityKey, E as ChatCompletionChunk, F as ChatCompletionRequest, G as ChatCompletionResponse, H as CommentResponse, I as CommentsResponse, J as ConfigureOAuthInput, K as ConfigureStripeInput, L as ConfigureWeb3Input, M as ConsensusStateSummary, N as ConsensusStatus, O as ContextDomain, P as ContextResponse, Q as ContextsListResponse, R as CreateCheckoutSessionResponse, S as CreateContextInput, U as CreateDelegationInput, V as CreateDomainInput, W as CreateKeyResponse, X as CreatePostInput, Y as CreatePostResponse, Z as CreateStackRequest, _ as Delegation, $ as DelegationChainLink, a0 as DelegationFilters, a1 as DelegationResponse, a2 as DelegationScope, a3 as DelegationsListResponse, a4 as DomainResponse, a5 as DomainsListResponse, a6 as FeedResponse, a7 as FileUploadResponse, a8 as FilesClientConfig, a9 as HistoryFilters, aa as HistoryResponse, ab as ImaginationCharacter, ac as ImaginationMetadata, ad as ImaginationSource, ae as InitNetworkResponse, af as LeaderStatus, ag as LikeCheckResponse, ah as LikeResponse, ai as MCPContent, aj as MCPMessage, ak as MCPSession, al as MCPSessionConfig, am as MCPToolResult, an as MPCNode, ao as MagmaFile, ap as MediaType, aq as Message, ar as MeteredUsage, as as ModelLayerInfo, at as ModelLayersResponse, au as NetworkClientConfig, av as NetworkStatus, br as Orientation, aw as PaginationMeta, bs as PaymentMethod, ax as PaymentRequiredResponse, ay as PointBalance, az as PointContext, aA as PointRecord, aB as PointRecordResponse, aC as PointSpend, aD as PointSpendResponse, aE as PointsClientConfig, aF as PostResponse, aG as ProfileResponse, aH as RemixesResponse, aI as Skill, aJ as SkillCreateInput, bp as SkillMapPromptResponse, bo as SkillMapResponse, aK as SkillResponse, bq as SkillSummaryResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aO as SocialAuthor, aP as SocialClientConfig, aQ as SocialComment, aR as SocialPost, aS as SocialRemix, bt as SolPrepaidResult, bu as SolSubscriptionResult, aT as SpendDestination, aU as SpendPointsInput, aV as StackCapabilities, aW as StackConfig, aX as StackKeyInfo, aY as StackKeysListResponse, aZ as StackListResponse, a_ as StackManagementClientConfig, a$ as StackMember, b0 as StackMemberStats, b1 as StackModelAlias, b2 as StackOAuthProvider, b3 as StackResponse, b4 as StackStripeProvider, b5 as StackWeb3Provider, b6 as TaskPayload, b7 as TaskResponse, a as TaskState, b as TaskStatus, T as TaskType, bv as TopupResult, b8 as UsageRecord, b9 as UserClientConfig, ba as UserProfile, bb as UserProfileResponse, bc as UserProfileUpdateInput, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bg as WidgetSystemPromptResponse, bh as WidgetUpdateInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bk as WorkflowData, bl as bitmaskToCapabilities, bm as capabilitiesToBitmask } from '../billing-BqscteyZ.cjs';
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
@@ -1,4 +1,4 @@
1
- export { A as ALL_CAPABILITIES_BITMASK, c as ActionProof, d as AddPointsInput, e as Agent, f as AgentCreateInput, g as AgentExecuteRequest, h as AgentExecuteResponse, i as AgentFromPromptInput, j as AgentResponse, k as AgentTrigger, l as AgentUpdateInput, m as AgentWorkflow, n as AgentWorkflowEdge, o as AgentWorkflowNode, p as AgentsClientConfig, q as AgentsListResponse, r as AllowlistConfig, s as AllowlistMode, t as AllowlistUpdateInput, u as AuthMetrics, B as BillingClientConfig, v as BillingPlan, w as BillingPlansResponse, x as BillingPortalResponse, y as BillingState, z as BillingTier, C as CAPABILITY_BITS, D as CapabilityKey, E as ChatCompletionChunk, F as ChatCompletionRequest, G as ChatCompletionResponse, H as CommentResponse, I as CommentsResponse, J as ConfigureOAuthInput, K as ConfigureStripeInput, L as ConfigureWeb3Input, M as ConsensusStateSummary, N as ConsensusStatus, O as ContextDomain, P as ContextResponse, Q as ContextsListResponse, R as CreateCheckoutSessionResponse, S as CreateContextInput, U as CreateDelegationInput, V as CreateDomainInput, W as CreateKeyResponse, X as CreatePostInput, Y as CreatePostResponse, Z as CreateStackRequest, _ as Delegation, $ as DelegationChainLink, a0 as DelegationFilters, a1 as DelegationResponse, a2 as DelegationScope, a3 as DelegationsListResponse, a4 as DomainResponse, a5 as DomainsListResponse, a6 as FeedResponse, a7 as FileUploadResponse, a8 as FilesClientConfig, a9 as HistoryFilters, aa as HistoryResponse, ab as ImaginationCharacter, ac as ImaginationMetadata, ad as ImaginationSource, ae as InitNetworkResponse, af as LeaderStatus, ag as LikeCheckResponse, ah as LikeResponse, ai as MCPContent, aj as MCPMessage, ak as MCPSession, al as MCPSessionConfig, am as MCPToolResult, an as MPCNode, ao as MagmaFile, ap as MediaType, aq as Message, ar as MeteredUsage, as as ModelLayerInfo, at as ModelLayersResponse, au as NetworkClientConfig, av as NetworkStatus, br as Orientation, aw as PaginationMeta, bs as PaymentMethod, ax as PaymentRequiredResponse, ay as PointBalance, az as PointContext, aA as PointRecord, aB as PointRecordResponse, aC as PointSpend, aD as PointSpendResponse, aE as PointsClientConfig, aF as PostResponse, aG as ProfileResponse, aH as RemixesResponse, aI as Skill, aJ as SkillCreateInput, bp as SkillMapPromptResponse, bo as SkillMapResponse, aK as SkillResponse, bq as SkillSummaryResponse, aL as SkillUpdateInput, bn as SkillVerifyResponse, aM as SkillsClientConfig, aN as SkillsListResponse, aO as SocialAuthor, aP as SocialClientConfig, aQ as SocialComment, aR as SocialPost, aS as SocialRemix, bt as SolPrepaidResult, bu as SolSubscriptionResult, aT as SpendDestination, aU as SpendPointsInput, aV as StackCapabilities, aW as StackConfig, aX as StackKeyInfo, aY as StackKeysListResponse, aZ as StackListResponse, a_ as StackManagementClientConfig, a$ as StackMember, b0 as StackMemberStats, b1 as StackModelAlias, b2 as StackOAuthProvider, b3 as StackResponse, b4 as StackStripeProvider, b5 as StackWeb3Provider, b6 as TaskPayload, b7 as TaskResponse, a as TaskState, b as TaskStatus, T as TaskType, bv as TopupResult, b8 as UsageRecord, b9 as UserClientConfig, ba as UserProfile, bb as UserProfileResponse, bc as UserProfileUpdateInput, bd as Widget, be as WidgetCreateInput, bf as WidgetResponse, bg as WidgetSystemPromptResponse, bh as WidgetUpdateInput, bi as WidgetsClientConfig, bj as WidgetsListResponse, bk as WorkflowData, bl as bitmaskToCapabilities, bm as capabilitiesToBitmask } from '../billing-BqscteyZ.js';
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.1.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
- "src"
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
+ }
@@ -1,233 +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
-
26
- constructor(config: AgentsClientConfig = {}) {
27
- this.baseUrl = config.baseUrl || DEFAULT_TASK_NETWORK_URL;
28
- // Use coprocessor API by default (can be disabled for backwards compatibility)
29
- this.useCpxApi = config.useCpxApi !== false;
30
- }
31
-
32
- private get agentsUrl(): string {
33
- // Route through Agent Coprocessor at /cpx/agent/agents
34
- return this.useCpxApi
35
- ? `${this.baseUrl}/cpx/agent/agents`
36
- : `${this.baseUrl}/agents`;
37
- }
38
-
39
- /**
40
- * List all agents
41
- */
42
- async list(options: { userMid?: string } = {}): Promise<AgentsListResponse> {
43
- const params = new URLSearchParams();
44
- if (options.userMid) {
45
- params.set('userMid', options.userMid);
46
- }
47
-
48
- const queryString = params.toString();
49
- const url = `${this.agentsUrl}${queryString ? `?${queryString}` : ''}`;
50
-
51
- const response = await fetch(url);
52
-
53
- if (!response.ok) {
54
- throw new StacksSDKError(
55
- 'bad_request:api',
56
- `Failed to list agents: ${response.statusText}`
57
- );
58
- }
59
-
60
- return response.json();
61
- }
62
-
63
- /**
64
- * Get an agent by ID
65
- */
66
- async get(id: string): Promise<Agent> {
67
- const response = await fetch(`${this.agentsUrl}/${id}`);
68
-
69
- if (!response.ok) {
70
- throw new StacksSDKError(
71
- response.status === 404 ? 'not_found:api' : 'bad_request:api',
72
- `Failed to get agent: ${response.statusText}`
73
- );
74
- }
75
-
76
- return response.json();
77
- }
78
-
79
- /**
80
- * Create a new agent
81
- */
82
- async create(input: AgentCreateInput): Promise<AgentResponse> {
83
- const response = await fetch(this.agentsUrl, {
84
- method: 'POST',
85
- headers: JSON_HEADERS,
86
- body: JSON.stringify(input),
87
- });
88
-
89
- if (!response.ok) {
90
- const data = await response.json().catch(() => ({}));
91
- throw new StacksSDKError(
92
- 'bad_request:api',
93
- data.error || `Failed to create agent: ${response.statusText}`
94
- );
95
- }
96
-
97
- return response.json();
98
- }
99
-
100
- /**
101
- * Update an agent
102
- */
103
- async update(id: string, input: AgentUpdateInput): Promise<AgentResponse> {
104
- const response = await fetch(`${this.agentsUrl}/${id}`, {
105
- method: 'PUT',
106
- headers: JSON_HEADERS,
107
- body: JSON.stringify(input),
108
- });
109
-
110
- if (!response.ok) {
111
- const data = await response.json().catch(() => ({}));
112
- throw new StacksSDKError(
113
- 'bad_request:api',
114
- data.error || `Failed to update agent: ${response.statusText}`
115
- );
116
- }
117
-
118
- return response.json();
119
- }
120
-
121
- /**
122
- * Delete an agent
123
- */
124
- async delete(id: string): Promise<{ success: boolean }> {
125
- const response = await fetch(`${this.agentsUrl}/${id}`, {
126
- method: 'DELETE',
127
- });
128
-
129
- if (!response.ok) {
130
- throw new StacksSDKError(
131
- 'bad_request:api',
132
- `Failed to delete agent: ${response.statusText}`
133
- );
134
- }
135
-
136
- return response.json();
137
- }
138
-
139
- /**
140
- * Enable an agent
141
- */
142
- async enable(id: string): Promise<AgentResponse> {
143
- const response = await fetch(`${this.agentsUrl}/${id}/enable`, {
144
- method: 'POST',
145
- });
146
-
147
- if (!response.ok) {
148
- throw new StacksSDKError(
149
- 'bad_request:api',
150
- `Failed to enable agent: ${response.statusText}`
151
- );
152
- }
153
-
154
- return response.json();
155
- }
156
-
157
- /**
158
- * Disable an agent
159
- */
160
- async disable(id: string): Promise<AgentResponse> {
161
- const response = await fetch(`${this.agentsUrl}/${id}/disable`, {
162
- method: 'POST',
163
- });
164
-
165
- if (!response.ok) {
166
- throw new StacksSDKError(
167
- 'bad_request:api',
168
- `Failed to disable agent: ${response.statusText}`
169
- );
170
- }
171
-
172
- return response.json();
173
- }
174
-
175
- /**
176
- * Execute an agent
177
- */
178
- async execute(id: string, request: AgentExecuteRequest = {}): Promise<AgentExecuteResponse> {
179
- const response = await fetch(`${this.agentsUrl}/${id}/execute`, {
180
- method: 'POST',
181
- headers: JSON_HEADERS,
182
- body: JSON.stringify(request),
183
- });
184
-
185
- if (!response.ok) {
186
- throw new StacksSDKError(
187
- 'bad_request:api',
188
- `Failed to execute agent: ${response.statusText}`
189
- );
190
- }
191
-
192
- return response.json();
193
- }
194
-
195
- /**
196
- * Create agent from prompt (AI-generated)
197
- */
198
- async createFromPrompt(input: AgentFromPromptInput): Promise<AgentResponse> {
199
- // First, generate agent config from prompt
200
- const generateResponse = await fetch(`${this.agentsUrl}/from-prompt`, {
201
- method: 'POST',
202
- headers: JSON_HEADERS,
203
- body: JSON.stringify(input),
204
- });
205
-
206
- if (!generateResponse.ok) {
207
- throw new StacksSDKError(
208
- 'bad_request:api',
209
- `Failed to generate agent from prompt: ${generateResponse.statusText}`
210
- );
211
- }
212
-
213
- const agentConfig = await generateResponse.json();
214
-
215
- // Then create the agent
216
- return this.create({
217
- ...agentConfig,
218
- created_by: input.created_by,
219
- });
220
- }
221
- }
222
-
223
- /**
224
- * Create an AgentsClient instance
225
- */
226
- export function createAgentsClient(config: AgentsClientConfig = {}): AgentsClient {
227
- return new AgentsClient(config);
228
- }
229
-
230
- /**
231
- * Default agents client instance
232
- */
233
- export const agentsClient = createAgentsClient();
@@ -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();