@stacknet/stacks
v0.2.3
Published
SDK for connecting to StackNet
Maintainers
Readme
@stacknet/stacks
Browser- and Node-friendly TypeScript SDK for StackNet — the decentralized AI inference network. Provides typed clients for chat completions, multimodal media generation, file storage on Magma, agents, skills, widgets, social, billing, and stack management. Includes Web Request/Response proxy handlers for stacks that need to forward authenticated traffic without exposing API keys to the browser.
Install
npm install @stacknet/stacks
# or
pnpm add @stacknet/stacksQuickstart — TaskNetworkClient
OpenAI-compatible streaming chat completions against the network.
import { createTaskNetworkClient } from '@stacknet/stacks';
const client = createTaskNetworkClient({
baseUrl: 'https://stacknet.magma-rpc.com',
apiKey: 'gk_YOUR_KEY',
});
for await (const chunk of client.chatCompletions({
model: 'magma',
messages: [{ role: 'user', content: 'Summarize the Treaty of Westphalia.' }],
stream: true,
})) {
process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
}apiKey is a gateway key (gk_*). The SDK adds it as Authorization: Bearer <key> on every request. If you're issuing per-user keys via the Stack proxy, use sk_* keys instead — same shape, scoped to the issuing stack.
Lower-level task submission
const taskId = await client.submitTask({
type: 'ai-prompt',
model: 'preview',
prompt: 'Hello',
stream: true,
});
for await (const chunk of client.streamTaskResults(taskId, 'preview')) {
// ...
}submitTask returns the task id. streamTaskResults opens an SSE connection to /tasks/:id/stream and yields OpenAI-shaped chat.completion.chunk payloads. getTask(taskId) polls for terminal status when streaming isn't available.
Quickstart — MagmaClient
File storage and imagination metadata against the Magma side of the network.
import { createMagmaClient } from '@stacknet/stacks';
const magma = createMagmaClient({
baseUrl: 'https://stacknet.magma-rpc.com',
persistLocalFiles: false,
});
const file = await magma.uploadFile(myFile);
console.log(file.cid, file.url);
await magma.storeImagination({
id: 'imag_abc',
title: 'Untitled run',
// ...
});Per-client APIs
The default export bundle includes a typed client for each network surface. All accept a config object and expose the underlying baseUrl for advanced cases.
| Import | Purpose |
|---|---|
| TaskNetworkClient | Chat completions, task submission, SSE streaming |
| MagmaClient | File upload/CID, imagination metadata |
| MCPClient | MCP server discovery + tool execution |
| SocialClient | Posts, likes, comments, remixes |
| AgentsClient | List/create/run agents, agent detail |
| WidgetsClient | List/create/run widgets |
| UserClient | Profile read/write |
| FilesClient | File listings, deletes |
| SkillsClient | Skill catalog + execution |
| NetworkClient | Network-wide reads (treasury, nodes, KPIs) |
| BillingClient | Subscription, balance, ledger, usage |
| PointsClient | Points balance + history |
| CoderClient | Code-execution sandbox tasks |
| StackManagementClient | Create/list/update stacks, keys, members |
Each is also exported from @stacknet/stacks/clients. Singletons (taskNetworkClient, magmaClient, etc.) ship pre-instantiated against the SDK defaults for low-config usage.
Streaming
@stacknet/stacks/streaming exports SSE helpers used by the clients above. Most consumers won't import it directly — call chatCompletions() or streamTaskResults() instead, which handle reconnect logic, partial-chunk buffering, and OpenAI-compatible chunk shape. If you're parsing your own SSE stream, the helpers are public.
Server-side proxy routes
For stacks that proxy traffic on behalf of their users, @stacknet/stacks/proxy bundles drop-in route handlers for the Next.js App Router:
// app/api/stacks/[stackId]/agents/route.ts
import { createAgentRoutes } from '@stacknet/stacks/proxy';
export const { GET, POST } = createAgentRoutes({
baseUrl: 'https://stacknet.magma-rpc.com',
requireAuth: true,
extractAuth(request) {
// Verify your application session and return its scoped bearer.
return verifyApplicationSession(request)?.stacknetToken ?? null;
},
});The handlers are framework-independent but fit the Next.js App Router signature. Helpers cover agents, skills, widgets, imaginations, and stack management. requireAuth rejects missing or malformed credentials locally. extractAuth should verify the host application's session and return only the scoped upstream bearer. For server-to-server routes, a trusted defaultHeaders.Authorization can be configured; never construct it from an unverified inbound header.
Generic forwardRequest and createProxyHandler are available for routes the named helpers do not cover. They constrain the upstream origin/base path, strip cookies and forwarding headers, cap JSON bodies and responses, apply timeouts, and let trusted configuration override caller headers.
Errors
Network calls throw on non-2xx responses. Errors preserve typed status categories where available, but do not reflect upstream response bodies or internal causes into serialized responses. Handle them like any other fetch failure:
try {
for await (const chunk of client.chatCompletions({ ... })) { ... }
} catch (e) {
// Inspect the typed error/status, not an upstream response body.
}Security
- Remote service roots must use HTTPS; loopback HTTP is allowed for development. URL credentials, query strings, and fragments are rejected.
- Bearers are length/control-character validated before entering headers. Opaque path identifiers are validated and percent-encoded.
- Requests have finite timeouts, browser credentials remain same-origin, and JSON responses are strict-UTF-8 and byte-capped.
MagmaClientcaps file sizes and does not persist raw file contents inlocalStorageunlesspersistLocalFiles: trueis explicitly configured.- Keep
StackManagementClient, billing mutations, coder execution, and static service credentials behind authorized server routes. Client validation is defense in depth, not an authorization boundary.
Versioning
Pre-1.0 — minor versions may break. Once 1.0.0 lands, the SDK follows semver: breaking changes only on a major version bump. Track the changelog at the repo root.
License
MIT
