@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/README.md
CHANGED
|
@@ -1 +1,137 @@
|
|
|
1
1
|
# @stacknet/stacks
|
|
2
|
+
|
|
3
|
+
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 a Next.js proxy module for stacks that need to forward authenticated traffic to the network without exposing API keys to the browser.
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @stacknet/stacks
|
|
9
|
+
# or
|
|
10
|
+
pnpm add @stacknet/stacks
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Peer dependency: `next >= 14` (optional — only required if you import from `@stacknet/stacks/proxy`).
|
|
14
|
+
|
|
15
|
+
## Quickstart — `TaskNetworkClient`
|
|
16
|
+
|
|
17
|
+
OpenAI-compatible streaming chat completions against the network.
|
|
18
|
+
|
|
19
|
+
```ts
|
|
20
|
+
import { createTaskNetworkClient } from '@stacknet/stacks';
|
|
21
|
+
|
|
22
|
+
const client = createTaskNetworkClient({
|
|
23
|
+
baseUrl: 'https://stacknet.magma-rpc.com',
|
|
24
|
+
apiKey: 'gk_YOUR_KEY',
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
for await (const chunk of client.chatCompletions({
|
|
28
|
+
model: 'magma',
|
|
29
|
+
messages: [{ role: 'user', content: 'Summarize the Treaty of Westphalia.' }],
|
|
30
|
+
stream: true,
|
|
31
|
+
})) {
|
|
32
|
+
process.stdout.write(chunk.choices[0]?.delta?.content ?? '');
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`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.
|
|
37
|
+
|
|
38
|
+
### Lower-level task submission
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
const taskId = await client.submitTask({
|
|
42
|
+
type: 'ai-prompt',
|
|
43
|
+
model: 'preview',
|
|
44
|
+
prompt: 'Hello',
|
|
45
|
+
stream: true,
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
for await (const chunk of client.streamTaskResults(taskId, 'preview')) {
|
|
49
|
+
// ...
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
`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.
|
|
54
|
+
|
|
55
|
+
## Quickstart — `MagmaClient`
|
|
56
|
+
|
|
57
|
+
File storage and imagination metadata against the Magma side of the network.
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { createMagmaClient } from '@stacknet/stacks';
|
|
61
|
+
|
|
62
|
+
const magma = createMagmaClient({
|
|
63
|
+
baseUrl: 'https://stacknet.magma-rpc.com',
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const file = await magma.uploadFile(myFile);
|
|
67
|
+
console.log(file.cid, file.url);
|
|
68
|
+
|
|
69
|
+
await magma.storeImagination({
|
|
70
|
+
id: 'imag_abc',
|
|
71
|
+
title: 'Untitled run',
|
|
72
|
+
// ...
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## Per-client APIs
|
|
77
|
+
|
|
78
|
+
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.
|
|
79
|
+
|
|
80
|
+
| Import | Purpose |
|
|
81
|
+
|---|---|
|
|
82
|
+
| `TaskNetworkClient` | Chat completions, task submission, SSE streaming |
|
|
83
|
+
| `MagmaClient` | File upload/CID, imagination metadata |
|
|
84
|
+
| `MCPClient` | MCP server discovery + tool execution |
|
|
85
|
+
| `SocialClient` | Posts, likes, comments, remixes |
|
|
86
|
+
| `AgentsClient` | List/create/run agents, agent detail |
|
|
87
|
+
| `WidgetsClient` | List/create/run widgets |
|
|
88
|
+
| `UserClient` | Profile read/write |
|
|
89
|
+
| `FilesClient` | File listings, deletes |
|
|
90
|
+
| `SkillsClient` | Skill catalog + execution |
|
|
91
|
+
| `NetworkClient` | Network-wide reads (treasury, nodes, KPIs) |
|
|
92
|
+
| `BillingClient` | Subscription, balance, ledger, usage |
|
|
93
|
+
| `PointsClient` | Points balance + history |
|
|
94
|
+
| `CoderClient` | Code-execution sandbox tasks |
|
|
95
|
+
| `StackManagementClient` | Create/list/update stacks, keys, members |
|
|
96
|
+
|
|
97
|
+
Each is also exported from `@stacknet/stacks/clients`. Singletons (`taskNetworkClient`, `magmaClient`, etc.) ship pre-instantiated against the SDK defaults for low-config usage.
|
|
98
|
+
|
|
99
|
+
## Streaming
|
|
100
|
+
|
|
101
|
+
`@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.
|
|
102
|
+
|
|
103
|
+
## Server-side proxy routes (Next.js)
|
|
104
|
+
|
|
105
|
+
For stacks that proxy traffic on behalf of their users, `@stacknet/stacks/proxy` bundles drop-in route handlers for the Next.js App Router:
|
|
106
|
+
|
|
107
|
+
```ts
|
|
108
|
+
// app/api/stacks/[stackId]/agents/route.ts
|
|
109
|
+
import { createAgentRoutes } from '@stacknet/stacks/proxy';
|
|
110
|
+
|
|
111
|
+
export const { GET, POST } = createAgentRoutes({
|
|
112
|
+
upstreamUrl: 'https://stacknet.magma-rpc.com',
|
|
113
|
+
apiKey: process.env.STACKNET_GK_KEY!,
|
|
114
|
+
});
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Helpers cover agents, skills, widgets, imaginations, and stack management (stacks, keys, members). All forward to the upstream network with the configured API key — keys live on the server, never in the browser. Generic `forwardRequest` and `createProxyHandler` are available for routes the named helpers don't cover.
|
|
118
|
+
|
|
119
|
+
## Errors
|
|
120
|
+
|
|
121
|
+
Network calls throw on non-2xx responses. The SDK surfaces the upstream response body in `error.message` so you can route 4xx (bad request, payment required, rate limit) differently from 5xx. Handle them like any other `fetch` failure:
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
try {
|
|
125
|
+
for await (const chunk of client.chatCompletions({ ... })) { ... }
|
|
126
|
+
} catch (e) {
|
|
127
|
+
// e.message includes the upstream body for 4xx
|
|
128
|
+
}
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
## Versioning
|
|
132
|
+
|
|
133
|
+
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.
|
|
134
|
+
|
|
135
|
+
## License
|
|
136
|
+
|
|
137
|
+
MIT
|
|
@@ -280,6 +280,9 @@ type Orientation = 'portrait' | 'landscape';
|
|
|
280
280
|
interface SocialPost {
|
|
281
281
|
id: string;
|
|
282
282
|
creator_mid: string;
|
|
283
|
+
/** Optional human-readable title. The `content` field holds the
|
|
284
|
+
* long-form description / original prompt. */
|
|
285
|
+
title?: string;
|
|
283
286
|
content: string;
|
|
284
287
|
media_url: string;
|
|
285
288
|
media_type: MediaType;
|
|
@@ -337,6 +340,9 @@ interface CommentResponse {
|
|
|
337
340
|
}
|
|
338
341
|
interface CreatePostInput {
|
|
339
342
|
creatorMid: string;
|
|
343
|
+
/** Short display title for the post. Optional — when omitted the
|
|
344
|
+
* feed falls back to rendering `content`. */
|
|
345
|
+
title?: string;
|
|
340
346
|
content: string;
|
|
341
347
|
mediaUrl: string;
|
|
342
348
|
mediaType: MediaType;
|
|
@@ -358,6 +364,58 @@ interface ProfileResponse {
|
|
|
358
364
|
interface SocialClientConfig {
|
|
359
365
|
baseUrl?: string;
|
|
360
366
|
}
|
|
367
|
+
type NotificationAction = 'like' | 'comment' | 'remix' | 'follow';
|
|
368
|
+
interface NotificationActor {
|
|
369
|
+
mid: string;
|
|
370
|
+
username: string | null;
|
|
371
|
+
avatar_url: string | null;
|
|
372
|
+
}
|
|
373
|
+
interface NotificationPostRef {
|
|
374
|
+
id: string;
|
|
375
|
+
media_type: MediaType | string | null;
|
|
376
|
+
media_cid: string | null;
|
|
377
|
+
title?: string | null;
|
|
378
|
+
}
|
|
379
|
+
interface NotificationRow {
|
|
380
|
+
id: number;
|
|
381
|
+
action: NotificationAction;
|
|
382
|
+
actor: NotificationActor;
|
|
383
|
+
post: NotificationPostRef | null;
|
|
384
|
+
comment: {
|
|
385
|
+
id: string;
|
|
386
|
+
snippet: string | null;
|
|
387
|
+
} | null;
|
|
388
|
+
remix_post: {
|
|
389
|
+
id: string;
|
|
390
|
+
media_type: MediaType | string | null;
|
|
391
|
+
} | null;
|
|
392
|
+
created_at: number;
|
|
393
|
+
viewed_at: number | null;
|
|
394
|
+
}
|
|
395
|
+
interface NotificationCounts {
|
|
396
|
+
total: number;
|
|
397
|
+
by_action: {
|
|
398
|
+
like: number;
|
|
399
|
+
comment: number;
|
|
400
|
+
remix: number;
|
|
401
|
+
follow: number;
|
|
402
|
+
};
|
|
403
|
+
by_media_type: {
|
|
404
|
+
image: number;
|
|
405
|
+
video: number;
|
|
406
|
+
music: number;
|
|
407
|
+
code: number;
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
interface NotificationListResponse {
|
|
411
|
+
notifications: NotificationRow[];
|
|
412
|
+
recipient_mid: string;
|
|
413
|
+
}
|
|
414
|
+
interface MarkViewedInput {
|
|
415
|
+
upToId?: number;
|
|
416
|
+
ids?: number[];
|
|
417
|
+
action?: NotificationAction;
|
|
418
|
+
}
|
|
361
419
|
|
|
362
420
|
/**
|
|
363
421
|
* Widget type definitions
|
|
@@ -1181,4 +1239,4 @@ interface TopupResult {
|
|
|
1181
1239
|
tokenBalance: number;
|
|
1182
1240
|
}
|
|
1183
1241
|
|
|
1184
|
-
export { type
|
|
1242
|
+
export { type DelegationScope as $, ALL_CAPABILITIES_BITMASK as A, type BillingClientConfig as B, CAPABILITY_BITS as C, type ChatCompletionRequest as D, type ChatCompletionResponse as E, type CommentResponse as F, type CommentsResponse as G, type ConfigureOAuthInput as H, type ConfigureStripeInput as I, type ConfigureWeb3Input as J, type ConsensusStateSummary as K, type ConsensusStatus as L, type ContextDomain as M, type ContextResponse as N, type ContextsListResponse as O, type CreateCheckoutSessionResponse as P, type CreateContextInput as Q, type CreateDelegationInput as R, type CreateDomainInput as S, type CreateKeyResponse as T, type CreatePostInput as U, type CreatePostResponse as V, type CreateStackRequest as W, type Delegation as X, type DelegationChainLink as Y, type DelegationFilters as Z, type DelegationResponse as _, type ActionProof as a, type SocialPost as a$, type DelegationsListResponse as a0, type DomainResponse as a1, type DomainsListResponse as a2, type FeedResponse as a3, type FileUploadResponse as a4, type FilesClientConfig as a5, type HistoryFilters as a6, type HistoryResponse as a7, type ImaginationCharacter as a8, type ImaginationMetadata as a9, type Orientation as aA, type PaginationMeta as aB, type PaymentMethod as aC, type PaymentRequiredResponse as aD, type PointBalance as aE, type PointContext as aF, type PointRecord as aG, type PointRecordResponse as aH, type PointSpend as aI, type PointSpendResponse as aJ, type PointsClientConfig as aK, type PostResponse as aL, type ProfileResponse as aM, type RemixesResponse as aN, type Skill as aO, type SkillCreateInput as aP, type SkillMapPromptResponse as aQ, type SkillMapResponse as aR, type SkillResponse as aS, type SkillSummaryResponse as aT, type SkillUpdateInput as aU, type SkillVerifyResponse as aV, type SkillsClientConfig as aW, type SkillsListResponse as aX, type SocialAuthor as aY, type SocialClientConfig as aZ, type SocialComment as a_, type ImaginationSource as aa, type InitNetworkResponse as ab, type LeaderStatus as ac, type LikeCheckResponse as ad, type LikeResponse as ae, type MCPContent as af, type MCPMessage as ag, type MCPSession as ah, type MCPSessionConfig as ai, type MCPToolResult as aj, type MPCNode as ak, type MagmaFile as al, type MarkViewedInput as am, type MediaType as an, type Message as ao, type MeteredUsage as ap, type ModelLayerInfo as aq, type ModelLayersResponse as ar, type NetworkClientConfig as as, type NetworkStatus as at, type NotificationAction as au, type NotificationActor as av, type NotificationCounts as aw, type NotificationListResponse as ax, type NotificationPostRef as ay, type NotificationRow as az, type AddPointsInput as b, type SocialRemix as b0, type SolPrepaidResult as b1, type SolSubscriptionResult as b2, type SpendDestination as b3, type SpendPointsInput as b4, type StackCapabilities as b5, type StackConfig as b6, type StackKeyInfo as b7, type StackKeysListResponse as b8, type StackListResponse as b9, type WorkflowData as bA, bitmaskToCapabilities as bB, capabilitiesToBitmask as bC, type StackManagementClientConfig as ba, type StackMember as bb, type StackMemberStats as bc, type StackModelAlias as bd, type StackOAuthProvider as be, type StackResponse as bf, type StackStripeProvider as bg, type StackWeb3Provider as bh, type TaskPayload as bi, type TaskResponse as bj, type TaskState as bk, type TaskStatus as bl, type TaskType as bm, type TopupResult as bn, type UsageRecord as bo, type UserClientConfig as bp, type UserProfile as bq, type UserProfileResponse as br, type UserProfileUpdateInput as bs, type Widget as bt, type WidgetCreateInput as bu, type WidgetResponse as bv, type WidgetSystemPromptResponse as bw, type WidgetUpdateInput as bx, type WidgetsClientConfig as by, type WidgetsListResponse as bz, type Agent as c, type AgentCreateInput as d, type AgentExecuteRequest as e, type AgentExecuteResponse as f, type AgentFromPromptInput as g, type AgentResponse as h, type AgentTrigger as i, type AgentUpdateInput as j, type AgentWorkflow as k, type AgentWorkflowEdge as l, type AgentWorkflowNode as m, type AgentsClientConfig as n, type AgentsListResponse as o, type AllowlistConfig as p, type AllowlistMode as q, type AllowlistUpdateInput as r, type AuthMetrics as s, type BillingPlan as t, type BillingPlansResponse as u, type BillingPortalResponse as v, type BillingState as w, type BillingTier as x, type CapabilityKey as y, type ChatCompletionChunk as z };
|
|
@@ -280,6 +280,9 @@ type Orientation = 'portrait' | 'landscape';
|
|
|
280
280
|
interface SocialPost {
|
|
281
281
|
id: string;
|
|
282
282
|
creator_mid: string;
|
|
283
|
+
/** Optional human-readable title. The `content` field holds the
|
|
284
|
+
* long-form description / original prompt. */
|
|
285
|
+
title?: string;
|
|
283
286
|
content: string;
|
|
284
287
|
media_url: string;
|
|
285
288
|
media_type: MediaType;
|
|
@@ -337,6 +340,9 @@ interface CommentResponse {
|
|
|
337
340
|
}
|
|
338
341
|
interface CreatePostInput {
|
|
339
342
|
creatorMid: string;
|
|
343
|
+
/** Short display title for the post. Optional — when omitted the
|
|
344
|
+
* feed falls back to rendering `content`. */
|
|
345
|
+
title?: string;
|
|
340
346
|
content: string;
|
|
341
347
|
mediaUrl: string;
|
|
342
348
|
mediaType: MediaType;
|
|
@@ -358,6 +364,58 @@ interface ProfileResponse {
|
|
|
358
364
|
interface SocialClientConfig {
|
|
359
365
|
baseUrl?: string;
|
|
360
366
|
}
|
|
367
|
+
type NotificationAction = 'like' | 'comment' | 'remix' | 'follow';
|
|
368
|
+
interface NotificationActor {
|
|
369
|
+
mid: string;
|
|
370
|
+
username: string | null;
|
|
371
|
+
avatar_url: string | null;
|
|
372
|
+
}
|
|
373
|
+
interface NotificationPostRef {
|
|
374
|
+
id: string;
|
|
375
|
+
media_type: MediaType | string | null;
|
|
376
|
+
media_cid: string | null;
|
|
377
|
+
title?: string | null;
|
|
378
|
+
}
|
|
379
|
+
interface NotificationRow {
|
|
380
|
+
id: number;
|
|
381
|
+
action: NotificationAction;
|
|
382
|
+
actor: NotificationActor;
|
|
383
|
+
post: NotificationPostRef | null;
|
|
384
|
+
comment: {
|
|
385
|
+
id: string;
|
|
386
|
+
snippet: string | null;
|
|
387
|
+
} | null;
|
|
388
|
+
remix_post: {
|
|
389
|
+
id: string;
|
|
390
|
+
media_type: MediaType | string | null;
|
|
391
|
+
} | null;
|
|
392
|
+
created_at: number;
|
|
393
|
+
viewed_at: number | null;
|
|
394
|
+
}
|
|
395
|
+
interface NotificationCounts {
|
|
396
|
+
total: number;
|
|
397
|
+
by_action: {
|
|
398
|
+
like: number;
|
|
399
|
+
comment: number;
|
|
400
|
+
remix: number;
|
|
401
|
+
follow: number;
|
|
402
|
+
};
|
|
403
|
+
by_media_type: {
|
|
404
|
+
image: number;
|
|
405
|
+
video: number;
|
|
406
|
+
music: number;
|
|
407
|
+
code: number;
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
interface NotificationListResponse {
|
|
411
|
+
notifications: NotificationRow[];
|
|
412
|
+
recipient_mid: string;
|
|
413
|
+
}
|
|
414
|
+
interface MarkViewedInput {
|
|
415
|
+
upToId?: number;
|
|
416
|
+
ids?: number[];
|
|
417
|
+
action?: NotificationAction;
|
|
418
|
+
}
|
|
361
419
|
|
|
362
420
|
/**
|
|
363
421
|
* Widget type definitions
|
|
@@ -1181,4 +1239,4 @@ interface TopupResult {
|
|
|
1181
1239
|
tokenBalance: number;
|
|
1182
1240
|
}
|
|
1183
1241
|
|
|
1184
|
-
export { type
|
|
1242
|
+
export { type DelegationScope as $, ALL_CAPABILITIES_BITMASK as A, type BillingClientConfig as B, CAPABILITY_BITS as C, type ChatCompletionRequest as D, type ChatCompletionResponse as E, type CommentResponse as F, type CommentsResponse as G, type ConfigureOAuthInput as H, type ConfigureStripeInput as I, type ConfigureWeb3Input as J, type ConsensusStateSummary as K, type ConsensusStatus as L, type ContextDomain as M, type ContextResponse as N, type ContextsListResponse as O, type CreateCheckoutSessionResponse as P, type CreateContextInput as Q, type CreateDelegationInput as R, type CreateDomainInput as S, type CreateKeyResponse as T, type CreatePostInput as U, type CreatePostResponse as V, type CreateStackRequest as W, type Delegation as X, type DelegationChainLink as Y, type DelegationFilters as Z, type DelegationResponse as _, type ActionProof as a, type SocialPost as a$, type DelegationsListResponse as a0, type DomainResponse as a1, type DomainsListResponse as a2, type FeedResponse as a3, type FileUploadResponse as a4, type FilesClientConfig as a5, type HistoryFilters as a6, type HistoryResponse as a7, type ImaginationCharacter as a8, type ImaginationMetadata as a9, type Orientation as aA, type PaginationMeta as aB, type PaymentMethod as aC, type PaymentRequiredResponse as aD, type PointBalance as aE, type PointContext as aF, type PointRecord as aG, type PointRecordResponse as aH, type PointSpend as aI, type PointSpendResponse as aJ, type PointsClientConfig as aK, type PostResponse as aL, type ProfileResponse as aM, type RemixesResponse as aN, type Skill as aO, type SkillCreateInput as aP, type SkillMapPromptResponse as aQ, type SkillMapResponse as aR, type SkillResponse as aS, type SkillSummaryResponse as aT, type SkillUpdateInput as aU, type SkillVerifyResponse as aV, type SkillsClientConfig as aW, type SkillsListResponse as aX, type SocialAuthor as aY, type SocialClientConfig as aZ, type SocialComment as a_, type ImaginationSource as aa, type InitNetworkResponse as ab, type LeaderStatus as ac, type LikeCheckResponse as ad, type LikeResponse as ae, type MCPContent as af, type MCPMessage as ag, type MCPSession as ah, type MCPSessionConfig as ai, type MCPToolResult as aj, type MPCNode as ak, type MagmaFile as al, type MarkViewedInput as am, type MediaType as an, type Message as ao, type MeteredUsage as ap, type ModelLayerInfo as aq, type ModelLayersResponse as ar, type NetworkClientConfig as as, type NetworkStatus as at, type NotificationAction as au, type NotificationActor as av, type NotificationCounts as aw, type NotificationListResponse as ax, type NotificationPostRef as ay, type NotificationRow as az, type AddPointsInput as b, type SocialRemix as b0, type SolPrepaidResult as b1, type SolSubscriptionResult as b2, type SpendDestination as b3, type SpendPointsInput as b4, type StackCapabilities as b5, type StackConfig as b6, type StackKeyInfo as b7, type StackKeysListResponse as b8, type StackListResponse as b9, type WorkflowData as bA, bitmaskToCapabilities as bB, capabilitiesToBitmask as bC, type StackManagementClientConfig as ba, type StackMember as bb, type StackMemberStats as bc, type StackModelAlias as bd, type StackOAuthProvider as be, type StackResponse as bf, type StackStripeProvider as bg, type StackWeb3Provider as bh, type TaskPayload as bi, type TaskResponse as bj, type TaskState as bk, type TaskStatus as bl, type TaskType as bm, type TopupResult as bn, type UsageRecord as bo, type UserClientConfig as bp, type UserProfile as bq, type UserProfileResponse as br, type UserProfileUpdateInput as bs, type Widget as bt, type WidgetCreateInput as bu, type WidgetResponse as bv, type WidgetSystemPromptResponse as bw, type WidgetUpdateInput as bx, type WidgetsClientConfig as by, type WidgetsListResponse as bz, type Agent as c, type AgentCreateInput as d, type AgentExecuteRequest as e, type AgentExecuteResponse as f, type AgentFromPromptInput as g, type AgentResponse as h, type AgentTrigger as i, type AgentUpdateInput as j, type AgentWorkflow as k, type AgentWorkflowEdge as l, type AgentWorkflowNode as m, type AgentsClientConfig as n, type AgentsListResponse as o, type AllowlistConfig as p, type AllowlistMode as q, type AllowlistUpdateInput as r, type AuthMetrics as s, type BillingPlan as t, type BillingPlansResponse as u, type BillingPortalResponse as v, type BillingState as w, type BillingTier as x, type CapabilityKey as y, type ChatCompletionChunk as z };
|
package/dist/clients/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
`);o=A.pop()||"";for(let v of A)if(v.startsWith("data: "))try{let E=JSON.parse(v.slice(6));if(Array.isArray(E)&&E.length>0){let m=E[0].result||"";if(m&&m!==
|
|
3
|
-
`);n=p.pop()||"";for(let g of p)if(g.startsWith("data: "))try{yield JSON.parse(g.slice(6));}catch{}}}finally{s.releaseLock();}}async healthCheck(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNode(){let e=await fetch(`${this.baseUrl}/node`);if(!e.ok)throw new Error(`Failed to get node info: ${e.statusText}`);return e.json()}};function F(a){return new f(a)}var V=F();async function O(a){let e=await crypto.subtle.digest("SHA-256",a);return `baf${Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,52)}`}var y=class{baseUrl;localServerUrl;constructor(e={}){this.baseUrl=e.baseUrl||h,this.localServerUrl=e.localServerUrl||u;}async uploadFile(e){let t=await e.arrayBuffer(),s=await O(t),r=this.arrayBufferToBase64(t);return typeof localStorage<"u"&&localStorage.setItem(`file:${s}`,JSON.stringify({cid:s,name:e.name,type:e.type,size:e.size,data:r})),{cid:s,name:e.name,size:e.size,type:e.type,url:`data:${e.type};base64,${r}`}}async uploadText(e,t){let s=new Blob([e],{type:"text/plain"}),r=new File([s],t,{type:"text/plain"});return this.uploadFile(r)}async storeImagination(e){let t=e.createdBy||"anonymous",r=(await fetch(`${this.localServerUrl}/imaginations/${e.id}`)).ok,n={id:e.id,title:e.title,sources:e.sources,summary:e.summary,character:e.character,workflow:e.workflow,is_public:e.is_public||false,creator_mid:t};if(r){let o=await fetch(`${this.localServerUrl}/imaginations/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to update imagination: ${o.statusText}`);return typeof localStorage<"u"&&localStorage.setItem(`imagination:${e.id}`,e.id),e.id}else {let o=await fetch(`${this.localServerUrl}/imaginations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to store imagination: ${o.statusText}`);let p=(await o.json()).imagination?.id||e.id;return typeof localStorage<"u"&&localStorage.setItem(`imagination:${p}`,p),p}}async getImagination(e){try{let t=await fetch(`${this.localServerUrl}/imaginations/${e}`);if(!t.ok)return null;let s=await t.json();return s.imagination?{id:s.imagination.id,title:s.imagination.title,createdAt:new Date(s.imagination.created_at).toISOString(),createdBy:s.imagination.creator_mid,sources:s.imagination.sources,summary:s.imagination.summary,character:s.imagination.character,workflow:s.imagination.workflow,is_public:s.imagination.is_public}:null}catch(t){return console.error("Failed to retrieve imagination:",t),null}}async getImaginationByCID(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);if(!t.ok)return null;let s=await t.json();return typeof localStorage<"u"&&localStorage.setItem(`imagination:${s.id}`,e),s}catch(t){return console.error("Failed to retrieve imagination by CID:",t),null}}async listImaginations(e){try{let t=e||"anonymous",s=await fetch(`${this.localServerUrl}/imaginations?creator_mid=${encodeURIComponent(t)}`);if(!s.ok)return console.warn("Failed to fetch imaginations from P2P, falling back to localStorage"),this.listImaginationsFromLocalStorage();let n=(await s.json()).imaginations.map(o=>({id:o.id,title:o.title,createdAt:new Date(o.created_at).toISOString(),createdBy:o.creator_mid,sources:o.sources,summary:o.summary,character:o.character,workflow:o.workflow,is_public:o.is_public}));return typeof localStorage<"u"&&n.forEach(o=>{localStorage.setItem(`imagination:${o.id}`,o.id);}),n}catch(t){return console.error("Failed to list imaginations:",t),this.listImaginationsFromLocalStorage()}}async listImaginationsFromLocalStorage(){if(typeof localStorage>"u")return [];let e=[];for(let t=0;t<localStorage.length;t++){let s=localStorage.key(t);if(s&&s.startsWith("imagination:")){let r=s.replace("imagination:",""),n=await this.getImagination(r);n&&e.push(n);}}return e}async getFile(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);return t.ok?await t.blob():null}catch(t){return console.error("Failed to retrieve file:",t),null}}arrayBufferToBase64(e){let t=new Uint8Array(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}};function M(a){return new y(a)}var X=M();var w=class{baseUrl;timeout;sessions=new Map;constructor(e={}){this.baseUrl=e.baseUrl||"http://localhost:3006",this.timeout=e.timeout||3e4;}async createSession(e="default"){let t=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;try{let s={id:t,agentId:e,status:"active",createdAt:new Date};this.sessions.set(t,s);try{await fetch(`${this.baseUrl}/mcp/sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t,agentId:e,clientInfo:{name:"stacknet-sdk",version:"0.1.0"}})});}catch{}return s}catch(s){throw new Error(`Failed to create MCP session: ${s}`)}}getSession(e){return this.sessions.get(e)}async closeSession(e){let t=this.sessions.get(e);if(t){t.status="closed";try{await fetch(`${this.baseUrl}/mcp/sessions/${e}`,{method:"DELETE"});}catch{}this.sessions.delete(e);}}async sendMessage(e,t){let s=this.sessions.get(e);if(!s||s.status!=="active")throw new Error("Invalid or inactive session");try{let r=await fetch(`${this.baseUrl}/mcp/sessions/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:[{role:"user",content:{type:"text",text:t}}]})});if(!r.ok)throw new Error(`MCP request failed: ${r.statusText}`);return r.json()}catch(r){throw new Error(`Failed to send message: ${r}`)}}async callTool(e,t,s={}){let r=this.sessions.get(e);if(!r||r.status!=="active")throw new Error("Invalid or inactive session");try{let n=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok)throw new Error(`Tool call failed: ${n.statusText}`);return n.json()}catch(n){throw new Error(`Failed to call tool: ${n}`)}}async listTools(e){let t=this.sessions.get(e);if(!t||t.status!=="active")throw new Error("Invalid or inactive session");try{let s=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools`);return s.ok?(await s.json()).tools||[]:[]}catch{return []}}getActiveSessions(){return Array.from(this.sessions.values()).filter(e=>e.status==="active")}async closeAllSessions(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(t=>this.closeSession(t)));}};function I(a){return new w(a)}var Q=I();var Z={database:"log",chat:"response",auth:"response",stream:"response",api:"response",history:"response",vote:"response",document:"response",suggestions:"response",task:"response",agent:"response",imagination:"response"},i=class extends Error{type;surface;statusCode;constructor(e,t){super();let[s,r]=e.split(":");this.type=s,this.cause=t,this.surface=r,this.message=ee(e),this.statusCode=te(this.type);}toJSON(){return {code:`${this.type}:${this.surface}`,message:this.message,cause:this.cause,statusCode:this.statusCode}}toResponse(){let e=`${this.type}:${this.surface}`,t=Z[this.surface],{message:s,cause:r,statusCode:n}=this;return t==="log"?(console.error({code:e,message:s,cause:r}),Response.json({code:"",message:"Something went wrong. Please try again later."},{status:n})):Response.json({code:e,message:s,cause:r},{status:n})}};function ee(a){if(a.includes("database"))return "An error occurred while executing a database query.";switch(a){case "bad_request:api":return "The request couldn't be processed. Please check your input and try again.";case "unauthorized:auth":return "You need to sign in before continuing.";case "unauthorized:api":return "Your session has expired. Please sign in again.";case "forbidden:auth":return "Your account does not have access to this feature.";case "rate_limit:chat":return "You have exceeded your maximum number of messages for the day. Please try again later.";case "not_found:chat":return "The requested chat was not found.";case "forbidden:chat":return "This chat belongs to another user.";case "unauthorized:chat":return "You need to sign in to view this chat.";case "offline:chat":return "We're having trouble sending your message. Please check your internet connection.";case "not_found:task":return "The requested task was not found.";case "forbidden:task":return "You do not have access to this task.";case "not_found:agent":return "The requested agent was not found.";case "forbidden:agent":return "You do not have access to this agent.";case "not_found:imagination":return "The requested imagination was not found.";case "forbidden:imagination":return "You do not have access to this imagination.";case "not_found:document":return "The requested document was not found.";case "forbidden:document":return "This document belongs to another user.";case "unauthorized:document":return "You need to sign in to view this document.";case "bad_request:document":return "The request to create or update the document was invalid.";default:return "Something went wrong. Please try again later."}}function te(a){switch(a){case "bad_request":return 400;case "unauthorized":return 401;case "payment_required":return 402;case "forbidden":return 403;case "not_found":return 404;case "rate_limit":return 429;case "offline":return 503;case "internal":return 500;default:return 500}}var k=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get socialUrl(){return `${this.baseUrl}/social`}async getFeed(e={}){let{page:t=1,limit:s=10,mediaType:r}=e,n=new URLSearchParams({page:String(t),limit:String(s)});r&&n.set("media_type",r);let o=await fetch(`${this.socialUrl}/feed?${n}`);if(!o.ok)throw new i("bad_request:api",`Failed to fetch feed: ${o.statusText}`);return o.json()}async getPost(e){let t=await fetch(`${this.socialUrl}/posts/${e}`);if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to fetch post: ${t.statusText}`);return t.json()}async getComments(e){let t=await fetch(`${this.socialUrl}/posts/${e}/comments`);if(!t.ok)throw new i("bad_request:api",`Failed to fetch comments: ${t.statusText}`);return t.json()}async getRemixes(e){let t=await fetch(`${this.socialUrl}/posts/${e}/remixes`);if(!t.ok)throw new i("bad_request:api",`Failed to fetch remixes: ${t.statusText}`);return t.json()}async checkLike(e,t){let s=await fetch(`${this.socialUrl}/posts/${e}/likes/check?userMid=${encodeURIComponent(t)}`);if(!s.ok)throw new i("bad_request:api",`Failed to check like status: ${s.statusText}`);return s.json()}async likePost(e,t){let s=await fetch(`${this.socialUrl}/like`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new i("bad_request:api",`Failed to like post: ${s.statusText}`);return s.json()}async unlikePost(e,t){let s=await fetch(`${this.socialUrl}/unlike`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new i("bad_request:api",`Failed to unlike post: ${s.statusText}`);return s.json()}async addComment(e,t,s){let r=await fetch(`${this.socialUrl}/comment`,{method:"POST",headers:l,body:JSON.stringify({postId:e,userMid:t,content:s})});if(!r.ok)throw new i("bad_request:api",`Failed to add comment: ${r.statusText}`);return r.json()}async createPost(e){let t=await fetch(`${this.socialUrl}/post`,{method:"POST",headers:l,body:JSON.stringify({userMid:e.creatorMid,content:e.content,mediaUrl:e.mediaUrl,mediaType:e.mediaType,orientation:e.orientation,posterUrl:e.posterUrl,remixOf:e.remixOf})});if(!t.ok)throw new i("bad_request:api",`Failed to create post: ${t.statusText}`);return t.json()}async trackView(e,t){await fetch(`${this.socialUrl}/posts/${e}/view`,{method:"POST",headers:l,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:l,body:JSON.stringify({userMid:t})}).catch(()=>{});}async getProfile(e){try{let t=await fetch(`${this.socialUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new i("bad_request:api",`Failed to fetch profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof i)throw t;return null}}};function j(a={}){return new k(a)}var se=j();var S=class{baseUrl;useCpxApi;authToken;constructor(e={}){this.baseUrl=e.baseUrl||u,this.useCpxApi=e.useCpxApi!==false,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}get agentsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/agents`:`${this.baseUrl}/agents`}async list(e={}){let t=new URLSearchParams;e.userMid&&t.set("userMid",e.userMid);let s=t.toString(),r=`${this.agentsUrl}${s?`?${s}`:""}`,n=await fetch(r,{headers:this.headers});if(!n.ok)throw new i("bad_request:api",`Failed to list agents: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.agentsUrl}/${e}`,{headers:this.headers});if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to get agent: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.agentsUrl,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create agent: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.agentsUrl}/${e}`,{method:"PUT",headers:this.headers,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update agent: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.agentsUrl}/${e}`,{method:"DELETE",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to delete agent: ${t.statusText}`);return t.json()}async enable(e){let t=await fetch(`${this.agentsUrl}/${e}/enable`,{method:"POST",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to enable agent: ${t.statusText}`);return t.json()}async disable(e){let t=await fetch(`${this.agentsUrl}/${e}/disable`,{method:"POST",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to disable agent: ${t.statusText}`);return t.json()}async execute(e,t={}){let s=await fetch(`${this.agentsUrl}/${e}/execute`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!s.ok)throw new i("bad_request:api",`Failed to execute agent: ${s.statusText}`);return s.json()}async createFromPrompt(e){let t=await fetch(`${this.agentsUrl}/from-prompt`,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok)throw new i("bad_request:api",`Failed to generate agent from prompt: ${t.statusText}`);let s=await t.json();return this.create({...s,created_by:e.created_by})}};function L(a={}){return new S(a)}var re=L();var b=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get widgetsUrl(){return `${this.baseUrl}/widgets`}async list(e={}){let t=new URLSearchParams;e.creatorMid?t.set("creator_mid",e.creatorMid):e.scope&&t.set("scope",e.scope);let s=t.toString(),r=`${this.widgetsUrl}${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to list widgets: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.widgetsUrl}/${e}`);if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to get widget: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.widgetsUrl,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create widget: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.widgetsUrl}/${e}`,{method:"PUT",headers:l,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update widget: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.widgetsUrl}/${e}`,{method:"DELETE"});if(!t.ok)throw new i("bad_request:api",`Failed to delete widget: ${t.statusText}`);return t.json()}async getSystemPrompt(){let e=await fetch(`${this.widgetsUrl}/system-prompt`);if(!e.ok)throw new i("bad_request:api",`Failed to get widget system prompt: ${e.statusText}`);return e.json()}async trackUsage(e){await fetch(`${this.widgetsUrl}/${e}/usage`,{method:"POST"}).catch(()=>{});}};function D(a={}){return new b(a)}var ne=D();var C=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get userUrl(){return `${this.baseUrl}/user`}async getProfile(e){try{let t=await fetch(`${this.userUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new i("bad_request:api",`Failed to get user profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof i)throw t;return null}}async updateProfile(e,t){let s=await fetch(`${this.userUrl}/profile/${e}`,{method:"PUT",headers:l,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update user profile: ${s.statusText}`)}return s.json()}};function N(a={}){return new C(a)}var ie=N();var P=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get filesUrl(){return `${this.baseUrl}/files`}async upload(e,t){let s=new FormData;s.append("file",e,t);let r=await fetch(`${this.filesUrl}/upload`,{method:"POST",body:s});if(!r.ok)throw new i("bad_request:api",`Failed to upload file: ${r.statusText}`);return r.json()}async uploadFromUrl(e){let t=await fetch(`${this.filesUrl}/upload-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})});if(!t.ok)throw new i("bad_request:api",`Failed to upload file from URL: ${t.statusText}`);return t.json()}getFileUrl(e){return `${this.filesUrl}/${e}`}};function K(a={}){return new P(a)}var oe=K();var $=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||h,this.useCpxApi=e.useCpxApi!==false;}get skillsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/skills`:`${this.baseUrl}/skills`}async list(e){let t=new URLSearchParams;e?.precompiled?(t.set("precompiled","true"),e?.contentType&&t.set("content_type",e.contentType)):e?.contentType?t.set("content_type",e.contentType):e?.creatorMid?t.set("creator_mid",e.creatorMid):e?.scope&&e.scope!=="all"&&t.set("scope",e.scope);let s=t.toString()?`${this.skillsUrl}?${t.toString()}`:this.skillsUrl,r=await fetch(s);if(!r.ok)throw new Error(`Failed to list skills: ${r.statusText}`);return r.json()}async get(e){let t=await fetch(`${this.skillsUrl}/${e}`);if(!t.ok)throw new Error(`Skill not found: ${e}`);return t.json()}async create(e){let t=await fetch(this.skillsUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to create skill: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.skillsUrl}/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new Error(r.error||`Failed to update skill: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.skillsUrl}/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to delete skill: ${t.statusText}`)}return t.json()}async trackUsage(e){try{await fetch(`${this.skillsUrl}/${e}/usage`,{method:"POST"});}catch{}}async verify(e){let t=await fetch(`${this.skillsUrl}/${e}/verify`);if(!t.ok)throw new Error(`Failed to verify skill: ${t.statusText}`);return t.json()}async rehash(e){let t=await fetch(`${this.skillsUrl}/${e}/rehash`,{method:"POST"});if(!t.ok)throw new Error(`Failed to rehash skill: ${t.statusText}`);return t.json()}async rehashAll(){let e=await fetch(`${this.skillsUrl}/rehash-all`,{method:"POST"});if(!e.ok)throw new Error(`Failed to rehash all skills: ${e.statusText}`);return e.json()}async getMap(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map${t}`);if(!s.ok)throw new Error(`Failed to get skill map: ${s.statusText}`);return s.json()}async getMapPrompt(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map/prompt${t}`);if(!s.ok)throw new Error(`Failed to get skill map prompt: ${s.statusText}`);return s.json()}async getNonCodeMap(){let e=await fetch(`${this.skillsUrl}/map/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill map: ${e.statusText}`);return e.json()}async getNonCodeSummary(){let e=await fetch(`${this.skillsUrl}/summary/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill summary: ${e.statusText}`);return e.json()}};function B(a){return new $(a)}var ae=B();var T=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}get pointsUrl(){return `${this.baseUrl}/cpx/points`}async initNetworkDomain(){let e=await fetch(`${this.pointsUrl}/init`,{method:"POST",headers:l});if(!e.ok){let t=await e.json().catch(()=>({}));throw new i("bad_request:api",t.error||`Failed to initialize network domain: ${e.statusText}`)}return e.json()}async listDomains(){let e=await fetch(`${this.pointsUrl}/domains`);if(!e.ok)throw new i("bad_request:api",`Failed to list domains: ${e.statusText}`);return e.json()}async getDomain(e){let t=await fetch(`${this.pointsUrl}/domains/${e}`);if(t.status===404)return null;if(!t.ok)throw new i("bad_request:api",`Failed to get domain: ${t.statusText}`);return t.json()}async createDomain(e){let t=await fetch(`${this.pointsUrl}/domains`,{method:"POST",headers:l,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new i("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create domain: ${t.statusText}`)}return t.json()}async listContexts(e){let t=e?`?domainId=${e}`:"",s=await fetch(`${this.pointsUrl}/contexts${t}`);if(!s.ok)throw new i("bad_request:api",`Failed to list contexts: ${s.statusText}`);return s.json()}async getContext(e){let t=await fetch(`${this.pointsUrl}/contexts/${e}`);if(t.status===404)return null;if(!t.ok)throw new i("bad_request:api",`Failed to get context: ${t.statusText}`);return t.json()}async createContext(e){let t=await fetch(`${this.pointsUrl}/contexts`,{method:"POST",headers:l,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new i("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create context: ${t.statusText}`)}return t.json()}async listDelegations(e={}){let t=new URLSearchParams;e.domainId&&t.set("domainId",e.domainId),e.delegator&&t.set("delegator",e.delegator),e.delegate&&t.set("delegate",e.delegate),e.activeOnly&&t.set("activeOnly","true");let s=t.toString(),r=`${this.pointsUrl}/delegations${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to list delegations: ${n.statusText}`);return n.json()}async createDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create delegation: ${t.statusText}`)}return t.json()}async revokeDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to revoke delegation: ${t.statusText}`)}return t.json()}async addPoints(e){let t=await fetch(`${this.pointsUrl}/add`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to add points: ${t.statusText}`)}return t.json()}async spendPoints(e){let t=await fetch(`${this.pointsUrl}/spend`,{method:"POST",headers:l,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to spend points: ${t.statusText}`)}return t.json()}async getBalance(e,t={}){let s=new URLSearchParams;t.domainId&&s.set("domainId",t.domainId),t.contextId&&s.set("contextId",t.contextId);let r=s.toString(),n=`${this.pointsUrl}/balance/${e}${r?`?${r}`:""}`,o=await fetch(n);if(!o.ok)throw new i("bad_request:api",`Failed to get balance: ${o.statusText}`);return o.json()}async getHistory(e={}){let t=new URLSearchParams;e.mid&&t.set("mid",e.mid),e.domainId&&t.set("domainId",e.domainId),e.contextId&&t.set("contextId",e.contextId),e.periodStart&&t.set("periodStart",e.periodStart.toString()),e.periodEnd&&t.set("periodEnd",e.periodEnd.toString()),e.taskId&&t.set("taskId",e.taskId),e.limit&&t.set("limit",e.limit.toString()),e.offset&&t.set("offset",e.offset.toString());let s=t.toString(),r=`${this.pointsUrl}/history${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to get history: ${n.statusText}`);return n.json()}};function W(a={}){return new T(a)}var le=W();var J="/api/v2",x=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${J}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let c=await n.json().catch(()=>({})),p=n.status===404?"not_found":n.status===401?"unauthorized":"bad_request";throw new i(`${p}:api`,c.error?.message||c.error||`Request failed: ${n.statusText}`)}let o=await n.json();return o&&typeof o=="object"&&"data"in o?o.data:o}async createStack(e){return this.request("POST","/stacks",e)}async listStacks(){return this.request("GET","/stacks")}async getStack(e){return this.request("GET",`/stacks/${e}`)}async updateStack(e,t){return this.request("PATCH",`/stacks/${e}`,t)}async deleteStack(e){return this.request("DELETE",`/stacks/${e}`)}async configureOAuthProvider(e,t,s){return this.request("POST",`/stacks/${e}/oauth/${t}`,s)}async removeOAuthProvider(e,t){return this.request("DELETE",`/stacks/${e}/oauth/${t}`)}async configureWeb3Provider(e,t,s){return this.request("POST",`/stacks/${e}/web3/${t}`,s)}async removeWeb3Provider(e,t){return this.request("DELETE",`/stacks/${e}/web3/${t}`)}async configureStripeProvider(e,t){return this.request("POST",`/stacks/${e}/stripe`,t)}async getStripeProvider(e){return this.request("GET",`/stacks/${e}/stripe`)}async removeStripeProvider(e){return this.request("DELETE",`/stacks/${e}/stripe`)}async createPaymentIntent(e,t,s){return this.request("POST",`/stacks/${e}/stripe/payment-intent`,{amountCents:t,metadata:s})}async createKey(e,t,s){return this.request("POST",`/stacks/${e}/keys`,{name:t,permission:s})}async listKeys(e){return this.request("GET",`/stacks/${e}/keys`)}async revokeKey(e,t){return this.request("DELETE",`/stacks/${e}/keys/${t}`)}async getAllowlist(e){return this.request("GET",`/stacks/${e}/auth/allowlist`)}async updateAllowlist(e,t){return this.request("PUT",`/stacks/${e}/auth/allowlist`,t)}async updateCapabilities(e,t){return this.request("PATCH",`/stacks/${e}`,{capabilityBitmask:t})}async getModelLayers(e){return this.request("GET",`/stacks/${e}/model-layers`)}async updateModelAlias(e,t,s,r){return this.request("PATCH",`/stacks/${e}/model-layers`,{layer:t,capability:s,alias:r})}async resetModelAlias(e,t,s){return this.request("DELETE",`/stacks/${e}/model-layers/${t}/${s}`)}async uploadLogo(e,t){let s=`${this.baseUrl}${J}/stacks/${e}/logo`,r=new FormData;r.append("logo",t);let n={};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);let o=await fetch(s,{method:"POST",headers:n,body:r});if(!o.ok){let p=await o.json().catch(()=>({}));throw new i("bad_request:api",p.error?.message||`Failed to upload logo: ${o.statusText}`)}let c=await o.json();return c&&typeof c=="object"&&"data"in c?c.data:c}async deleteLogo(e){return this.request("DELETE",`/stacks/${e}/logo`)}async getMemberStats(e){return this.request("GET",`/stacks/${e}/members/stats`)}async getMembers(e,t){let s=new URLSearchParams;t?.limit&&s.set("limit",String(t.limit)),t?.offset&&s.set("offset",String(t.offset)),t?.role&&s.set("role",t.role);let r=s.toString()?`?${s}`:"";return this.request("GET",`/stacks/${e}/members${r}`)}async updateMemberRole(e,t,s){return this.request("PATCH",`/stacks/${e}/members/${encodeURIComponent(t)}/role`,{role:s})}async getUsageRecords(e,t){let s=new URLSearchParams;t?.page&&s.set("page",String(t.page)),t?.limit&&s.set("limit",String(t.limit)),t?.days&&s.set("days",String(t.days)),t?.model&&s.set("model",t.model);let r=s.toString()?`?${s}`:"";return this.request("GET",`/stacks/${e}/usage/records${r}`)}};function G(a={}){return new x(a)}var ce=G();var U="/api/v2",R=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async request(e,t){let s=await fetch(t,{method:e,headers:this.headers});if(!s.ok){let n=await s.json().catch(()=>({}));throw new i("bad_request:api",n.error?.message||`Request failed: ${s.statusText}`)}let r=await s.json();return r&&typeof r=="object"&&"data"in r?r.data:r}async checkHealth(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNetworkStatus(){return this.request("GET",`${this.baseUrl}${U}/network/status`)}async getMPCNodes(){return this.request("GET",`${this.baseUrl}${U}/network/nodes`)}async getNodeHealth(e){return this.request("GET",`${this.baseUrl}${U}/network/nodes/${e}/health`)}async getConsensusStatus(){return this.request("GET",`${this.baseUrl}/consensus/status`)}async getLeaderStatus(){return this.request("GET",`${this.baseUrl}/consensus/leader`)}async getAuthMetrics(e){let t=e?`/stacks/${e}/metrics`:"/metrics";return this.request("GET",`${this.baseUrl}${U}${t}`)}};function H(a={}){return new R(a)}var ue=H();var pe="/api/v2",_=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||d,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...l};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${pe}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let c=await n.json().catch(()=>({}));throw new i(n.status===402?"payment_required:api":"bad_request:api",c.error?.message||`Request failed: ${n.statusText}`)}let o=await n.json();return o&&typeof o=="object"&&"data"in o?o.data:o}async getPlans(e){return this.request("GET",`/stacks/${e}/billing/plans`)}async getBillingState(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing`)}async createCheckoutSession(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/checkout`,{identity_id:t,plan_id:s,success_url:r,cancel_url:n})}async createBillingPortal(e,t,s){return this.request("POST",`/stacks/${e}/billing/portal`,{identity_id:t,return_url:s})}async recordUsage(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/usage`,{identity_id:t,usage_type:s,quantity:r,idempotency_key:n})}async getCurrentUsage(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/usage`)}async linkStripeCustomer(e,t,s,r){return this.request("POST",`/stacks/${e}/billing/link`,{identity_id:t,stripe_customer_id:s,checkout_session_id:r})}async hasPaymentMethod(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/payment-method`)}async subscribeSol(e,t,s){return this.request("POST",`/stacks/${e}/subscribe-sol`,{planId:t,txSignature:s})}async prepaidSol(e,t,s,r){return this.request("POST",`/stacks/${e}/prepaid-sol`,{amountCents:t,txSignature:s,scope:r})}async topup(e,t,s){return this.request("POST","/account/topup",{amount_cents:e,payment_method:t,payment_ref:s})}};function z(a={}){return new _(a)}var de=z();
|
|
4
|
-
exports.AgentsClient=S;exports.BillingClient=_;exports.FilesClient=P;exports.MCPClient=w;exports.MagmaClient=y;exports.NetworkClient=R;exports.PointsClient=T;exports.SkillsClient=$;exports.SocialClient=k;exports.StackManagementClient=x;exports.TaskNetworkClient=f;exports.UserClient=C;exports.WidgetsClient=b;exports.agentsClient=re;exports.billingClient=
|
|
1
|
+
'use strict';var p="https://stacknet.magma-rpc.com",u=p;var h="https://stacknet.magma-rpc.com";var c={"Content-Type":"application/json"};var f=class{baseUrl;apiKey;timeout;constructor(e={}){this.baseUrl=(e.baseUrl||u).replace(/\/$/,""),this.apiKey=e.apiKey,this.timeout=e.timeout||6e4;}async*chatCompletions(e){let t=e.messages.filter(n=>n.role==="user"),s=t[t.length-1]?.content||"",r=await this.submitTask({type:"ai-prompt",model:e.model,prompt:s,sessionId:e.sessionId,temperature:e.temperature,maxTokens:e.max_tokens,stream:true});yield*this.streamTaskResults(r,e.model);}async submitTask(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let n=await t.text();throw new Error(`Task submission failed: ${n}`)}let s=await t.json(),r=s.taskId||s.id;if(!r)throw new Error("Task submission did not return a taskId");return r}async submitTaskFull(e){let t=await fetch(`${this.baseUrl}/tasks`,{method:"POST",headers:{"Content-Type":"application/json",...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}},body:JSON.stringify(e)});if(!t.ok){let r=await t.text();throw new Error(`Task submission failed: ${r}`)}let s=await t.json();return {taskId:s.taskId||s.id,output:s.output,status:s.status}}async getTask(e){let t=await fetch(`${this.baseUrl}/tasks/${e}`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Failed to get task: ${t.statusText}`);return t.json()}async*streamTaskResults(e,t){let s=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!s.ok)throw new Error(`Stream failed: ${s.statusText}`);if(!s.body)throw new Error("Response body is null");let r=s.body.getReader(),n=new TextDecoder,o="",l="",d=Math.floor(Date.now()/1e3);try{for(;;){let{done:g,value:Y}=await r.read();if(g){yield {id:e,object:"chat.completion.chunk",created:d,model:t,choices:[{index:0,delta:{},finish_reason:"stop"}]};break}o+=n.decode(Y,{stream:!0});let A=o.split(`
|
|
2
|
+
`);o=A.pop()||"";for(let v of A)if(v.startsWith("data: "))try{let E=JSON.parse(v.slice(6));if(Array.isArray(E)&&E.length>0){let m=E[0].result||"";if(m&&m!==l){let q=m.substring(l.length);l=m,q&&(yield {id:e,object:"chat.completion.chunk",created:d,model:t,choices:[{index:0,delta:{role:"assistant",content:q},finish_reason:null}]});}}}catch{}}}finally{r.releaseLock();}}async*streamTaskRaw(e){let t=await fetch(`${this.baseUrl}/tasks/${e}/stream`,{headers:{...this.apiKey&&{Authorization:`Bearer ${this.apiKey}`}}});if(!t.ok)throw new Error(`Stream failed: ${t.statusText}`);if(!t.body)throw new Error("Response body is null");let s=t.body.getReader(),r=new TextDecoder,n="";try{for(;;){let{done:o,value:l}=await s.read();if(o)break;n+=r.decode(l,{stream:!0});let d=n.split(`
|
|
3
|
+
`);n=d.pop()||"";for(let g of d)if(g.startsWith("data: "))try{yield JSON.parse(g.slice(6));}catch{}}}finally{s.releaseLock();}}async healthCheck(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNode(){let e=await fetch(`${this.baseUrl}/node`);if(!e.ok)throw new Error(`Failed to get node info: ${e.statusText}`);return e.json()}};function F(a){return new f(a)}var V=F();async function I(a){let e=await crypto.subtle.digest("SHA-256",a);return `baf${Array.from(new Uint8Array(e)).map(r=>r.toString(16).padStart(2,"0")).join("").substring(0,52)}`}var y=class{baseUrl;localServerUrl;constructor(e={}){this.baseUrl=e.baseUrl||h,this.localServerUrl=e.localServerUrl||u;}async uploadFile(e){let t=await e.arrayBuffer(),s=await I(t),r=this.arrayBufferToBase64(t);return typeof localStorage<"u"&&localStorage.setItem(`file:${s}`,JSON.stringify({cid:s,name:e.name,type:e.type,size:e.size,data:r})),{cid:s,name:e.name,size:e.size,type:e.type,url:`data:${e.type};base64,${r}`}}async uploadText(e,t){let s=new Blob([e],{type:"text/plain"}),r=new File([s],t,{type:"text/plain"});return this.uploadFile(r)}async storeImagination(e){let t=e.createdBy||"anonymous",r=(await fetch(`${this.localServerUrl}/imaginations/${e.id}`)).ok,n={id:e.id,title:e.title,sources:e.sources,summary:e.summary,character:e.character,workflow:e.workflow,is_public:e.is_public||false,creator_mid:t};if(r){let o=await fetch(`${this.localServerUrl}/imaginations/${e.id}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to update imagination: ${o.statusText}`);return typeof localStorage<"u"&&localStorage.setItem(`imagination:${e.id}`,e.id),e.id}else {let o=await fetch(`${this.localServerUrl}/imaginations`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok)throw new Error(`Failed to store imagination: ${o.statusText}`);let d=(await o.json()).imagination?.id||e.id;return typeof localStorage<"u"&&localStorage.setItem(`imagination:${d}`,d),d}}async getImagination(e){try{let t=await fetch(`${this.localServerUrl}/imaginations/${e}`);if(!t.ok)return null;let s=await t.json();return s.imagination?{id:s.imagination.id,title:s.imagination.title,createdAt:new Date(s.imagination.created_at).toISOString(),createdBy:s.imagination.creator_mid,sources:s.imagination.sources,summary:s.imagination.summary,character:s.imagination.character,workflow:s.imagination.workflow,is_public:s.imagination.is_public}:null}catch(t){return console.error("Failed to retrieve imagination:",t),null}}async getImaginationByCID(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);if(!t.ok)return null;let s=await t.json();return typeof localStorage<"u"&&localStorage.setItem(`imagination:${s.id}`,e),s}catch(t){return console.error("Failed to retrieve imagination by CID:",t),null}}async listImaginations(e){try{let t=e||"anonymous",s=await fetch(`${this.localServerUrl}/imaginations?creator_mid=${encodeURIComponent(t)}`);if(!s.ok)return console.warn("Failed to fetch imaginations from P2P, falling back to localStorage"),this.listImaginationsFromLocalStorage();let n=(await s.json()).imaginations.map(o=>({id:o.id,title:o.title,createdAt:new Date(o.created_at).toISOString(),createdBy:o.creator_mid,sources:o.sources,summary:o.summary,character:o.character,workflow:o.workflow,is_public:o.is_public}));return typeof localStorage<"u"&&n.forEach(o=>{localStorage.setItem(`imagination:${o.id}`,o.id);}),n}catch(t){return console.error("Failed to list imaginations:",t),this.listImaginationsFromLocalStorage()}}async listImaginationsFromLocalStorage(){if(typeof localStorage>"u")return [];let e=[];for(let t=0;t<localStorage.length;t++){let s=localStorage.key(t);if(s&&s.startsWith("imagination:")){let r=s.replace("imagination:",""),n=await this.getImagination(r);n&&e.push(n);}}return e}async getFile(e){try{let t=await fetch(`${this.baseUrl}/files/${e}`);return t.ok?await t.blob():null}catch(t){return console.error("Failed to retrieve file:",t),null}}arrayBufferToBase64(e){let t=new Uint8Array(e),s="";for(let r=0;r<t.length;r++)s+=String.fromCharCode(t[r]);return btoa(s)}};function O(a){return new y(a)}var X=O();var w=class{baseUrl;timeout;sessions=new Map;constructor(e={}){this.baseUrl=e.baseUrl||"http://localhost:3006",this.timeout=e.timeout||3e4;}async createSession(e="default"){let t=`session_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;try{let s={id:t,agentId:e,status:"active",createdAt:new Date};this.sessions.set(t,s);try{await fetch(`${this.baseUrl}/mcp/sessions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({sessionId:t,agentId:e,clientInfo:{name:"stacknet-sdk",version:"0.1.0"}})});}catch{}return s}catch(s){throw new Error(`Failed to create MCP session: ${s}`)}}getSession(e){return this.sessions.get(e)}async closeSession(e){let t=this.sessions.get(e);if(t){t.status="closed";try{await fetch(`${this.baseUrl}/mcp/sessions/${e}`,{method:"DELETE"});}catch{}this.sessions.delete(e);}}async sendMessage(e,t){let s=this.sessions.get(e);if(!s||s.status!=="active")throw new Error("Invalid or inactive session");try{let r=await fetch(`${this.baseUrl}/mcp/sessions/${e}/messages`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({messages:[{role:"user",content:{type:"text",text:t}}]})});if(!r.ok)throw new Error(`MCP request failed: ${r.statusText}`);return r.json()}catch(r){throw new Error(`Failed to send message: ${r}`)}}async callTool(e,t,s={}){let r=this.sessions.get(e);if(!r||r.status!=="active")throw new Error("Invalid or inactive session");try{let n=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools/${t}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!n.ok)throw new Error(`Tool call failed: ${n.statusText}`);return n.json()}catch(n){throw new Error(`Failed to call tool: ${n}`)}}async listTools(e){let t=this.sessions.get(e);if(!t||t.status!=="active")throw new Error("Invalid or inactive session");try{let s=await fetch(`${this.baseUrl}/mcp/sessions/${e}/tools`);return s.ok?(await s.json()).tools||[]:[]}catch{return []}}getActiveSessions(){return Array.from(this.sessions.values()).filter(e=>e.status==="active")}async closeAllSessions(){let e=Array.from(this.sessions.keys());await Promise.all(e.map(t=>this.closeSession(t)));}};function M(a){return new w(a)}var Q=M();var Z={database:"log",chat:"response",auth:"response",stream:"response",api:"response",history:"response",vote:"response",document:"response",suggestions:"response",task:"response",agent:"response",imagination:"response"},i=class extends Error{type;surface;statusCode;constructor(e,t){super();let[s,r]=e.split(":");this.type=s,this.cause=t,this.surface=r,this.message=ee(e),this.statusCode=te(this.type);}toJSON(){return {code:`${this.type}:${this.surface}`,message:this.message,cause:this.cause,statusCode:this.statusCode}}toResponse(){let e=`${this.type}:${this.surface}`,t=Z[this.surface],{message:s,cause:r,statusCode:n}=this;return t==="log"?(console.error({code:e,message:s,cause:r}),Response.json({code:"",message:"Something went wrong. Please try again later."},{status:n})):Response.json({code:e,message:s,cause:r},{status:n})}};function ee(a){if(a.includes("database"))return "An error occurred while executing a database query.";switch(a){case "bad_request:api":return "The request couldn't be processed. Please check your input and try again.";case "unauthorized:auth":return "You need to sign in before continuing.";case "unauthorized:api":return "Your session has expired. Please sign in again.";case "forbidden:auth":return "Your account does not have access to this feature.";case "rate_limit:chat":return "You have exceeded your maximum number of messages for the day. Please try again later.";case "not_found:chat":return "The requested chat was not found.";case "forbidden:chat":return "This chat belongs to another user.";case "unauthorized:chat":return "You need to sign in to view this chat.";case "offline:chat":return "We're having trouble sending your message. Please check your internet connection.";case "not_found:task":return "The requested task was not found.";case "forbidden:task":return "You do not have access to this task.";case "not_found:agent":return "The requested agent was not found.";case "forbidden:agent":return "You do not have access to this agent.";case "not_found:imagination":return "The requested imagination was not found.";case "forbidden:imagination":return "You do not have access to this imagination.";case "not_found:document":return "The requested document was not found.";case "forbidden:document":return "This document belongs to another user.";case "unauthorized:document":return "You need to sign in to view this document.";case "bad_request:document":return "The request to create or update the document was invalid.";default:return "Something went wrong. Please try again later."}}function te(a){switch(a){case "bad_request":return 400;case "unauthorized":return 401;case "payment_required":return 402;case "forbidden":return 403;case "not_found":return 404;case "rate_limit":return 429;case "offline":return 503;case "internal":return 500;default:return 500}}var k=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get socialUrl(){return `${this.baseUrl}/social`}async getFeed(e={}){let{page:t=1,limit:s=10,mediaType:r}=e,n=new URLSearchParams({page:String(t),limit:String(s)});r&&n.set("media_type",r);let o=await fetch(`${this.socialUrl}/feed?${n}`);if(!o.ok)throw new i("bad_request:api",`Failed to fetch feed: ${o.statusText}`);return o.json()}async getPost(e){let t=await fetch(`${this.socialUrl}/posts/${e}`);if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to fetch post: ${t.statusText}`);return t.json()}async getComments(e){let t=await fetch(`${this.socialUrl}/posts/${e}/comments`);if(!t.ok)throw new i("bad_request:api",`Failed to fetch comments: ${t.statusText}`);return t.json()}async getRemixes(e){let t=await fetch(`${this.socialUrl}/posts/${e}/remixes`);if(!t.ok)throw new i("bad_request:api",`Failed to fetch remixes: ${t.statusText}`);return t.json()}async checkLike(e,t){let s=await fetch(`${this.socialUrl}/posts/${e}/likes/check?userMid=${encodeURIComponent(t)}`);if(!s.ok)throw new i("bad_request:api",`Failed to check like status: ${s.statusText}`);return s.json()}async likePost(e,t){let s=await fetch(`${this.socialUrl}/like`,{method:"POST",headers:c,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new i("bad_request:api",`Failed to like post: ${s.statusText}`);return s.json()}async unlikePost(e,t){let s=await fetch(`${this.socialUrl}/unlike`,{method:"POST",headers:c,body:JSON.stringify({postId:e,userMid:t})});if(!s.ok)throw new i("bad_request:api",`Failed to unlike post: ${s.statusText}`);return s.json()}async addComment(e,t,s){let r=await fetch(`${this.socialUrl}/comment`,{method:"POST",headers:c,body:JSON.stringify({postId:e,userMid:t,content:s})});if(!r.ok)throw new i("bad_request:api",`Failed to add comment: ${r.statusText}`);return r.json()}async createPost(e){let t=await fetch(`${this.socialUrl}/post`,{method:"POST",headers:c,body:JSON.stringify({userMid:e.creatorMid,title:e.title,content:e.content,mediaUrl:e.mediaUrl,mediaType:e.mediaType,orientation:e.orientation,posterUrl:e.posterUrl,remixOf:e.remixOf})});if(!t.ok)throw new i("bad_request:api",`Failed to create post: ${t.statusText}`);return t.json()}async trackView(e,t){await fetch(`${this.socialUrl}/posts/${e}/view`,{method:"POST",headers:c,body:JSON.stringify({userMid:t})}).catch(()=>{});}async trackPlay(e,t){await fetch(`${this.socialUrl}/posts/${e}/play`,{method:"POST",headers:c,body:JSON.stringify({userMid:t})}).catch(()=>{});}get notificationsUrl(){return `${this.baseUrl}/notifications`}async getNotificationCounts(){let e=await fetch(`${this.notificationsUrl}/counts`,{credentials:"include"});if(!e.ok)throw new i(e.status===401?"unauthorized:api":"bad_request:api",`Failed to fetch notification counts: ${e.statusText}`);return e.json()}async getNotifications(e={}){let t=new URLSearchParams;e.sinceId!==void 0&&t.set("since_id",String(e.sinceId)),e.beforeId!==void 0&&t.set("before_id",String(e.beforeId)),e.action&&t.set("action",e.action),e.limit!==void 0&&t.set("limit",String(e.limit)),e.unviewedOnly&&t.set("unviewed","true");let s=t.toString(),r=await fetch(`${this.notificationsUrl}${s?`?${s}`:""}`,{credentials:"include"});if(!r.ok)throw new i(r.status===401?"unauthorized:api":"bad_request:api",`Failed to fetch notifications: ${r.statusText}`);return r.json()}async markNotificationsViewed(e){let t=await fetch(`${this.notificationsUrl}/mark-viewed`,{method:"POST",credentials:"include",headers:c,body:JSON.stringify({up_to_id:e.upToId,ids:e.ids,action:e.action})});if(!t.ok)throw new i(t.status===401?"unauthorized:api":"bad_request:api",`Failed to mark notifications viewed: ${t.statusText}`);return t.json()}async clearNotifications(e){let t=await fetch(`${this.notificationsUrl}/clear`,{method:"POST",credentials:"include",headers:c,body:JSON.stringify({up_to_id:e.upToId,ids:e.ids,action:e.action})});if(!t.ok)throw new i(t.status===401?"unauthorized:api":"bad_request:api",`Failed to clear notifications: ${t.statusText}`);return t.json()}async getProfile(e){try{let t=await fetch(`${this.socialUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new i("bad_request:api",`Failed to fetch profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof i)throw t;return null}}};function j(a={}){return new k(a)}var se=j();var S=class{baseUrl;useCpxApi;authToken;constructor(e={}){this.baseUrl=e.baseUrl||u,this.useCpxApi=e.useCpxApi!==false,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...c};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}get agentsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/agents`:`${this.baseUrl}/agents`}async list(e={}){let t=new URLSearchParams;e.userMid&&t.set("userMid",e.userMid);let s=t.toString(),r=`${this.agentsUrl}${s?`?${s}`:""}`,n=await fetch(r,{headers:this.headers});if(!n.ok)throw new i("bad_request:api",`Failed to list agents: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.agentsUrl}/${e}`,{headers:this.headers});if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to get agent: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.agentsUrl,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create agent: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.agentsUrl}/${e}`,{method:"PUT",headers:this.headers,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update agent: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.agentsUrl}/${e}`,{method:"DELETE",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to delete agent: ${t.statusText}`);return t.json()}async enable(e){let t=await fetch(`${this.agentsUrl}/${e}/enable`,{method:"POST",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to enable agent: ${t.statusText}`);return t.json()}async disable(e){let t=await fetch(`${this.agentsUrl}/${e}/disable`,{method:"POST",headers:this.headers});if(!t.ok)throw new i("bad_request:api",`Failed to disable agent: ${t.statusText}`);return t.json()}async execute(e,t={}){let s=await fetch(`${this.agentsUrl}/${e}/execute`,{method:"POST",headers:this.headers,body:JSON.stringify(t)});if(!s.ok)throw new i("bad_request:api",`Failed to execute agent: ${s.statusText}`);return s.json()}async createFromPrompt(e){let t=await fetch(`${this.agentsUrl}/from-prompt`,{method:"POST",headers:this.headers,body:JSON.stringify(e)});if(!t.ok)throw new i("bad_request:api",`Failed to generate agent from prompt: ${t.statusText}`);let s=await t.json();return this.create({...s,created_by:e.created_by})}};function L(a={}){return new S(a)}var re=L();var b=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get widgetsUrl(){return `${this.baseUrl}/widgets`}async list(e={}){let t=new URLSearchParams;e.creatorMid?t.set("creator_mid",e.creatorMid):e.scope&&t.set("scope",e.scope);let s=t.toString(),r=`${this.widgetsUrl}${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to list widgets: ${n.statusText}`);return n.json()}async get(e){let t=await fetch(`${this.widgetsUrl}/${e}`);if(!t.ok)throw new i(t.status===404?"not_found:api":"bad_request:api",`Failed to get widget: ${t.statusText}`);return t.json()}async create(e){let t=await fetch(this.widgetsUrl,{method:"POST",headers:c,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create widget: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.widgetsUrl}/${e}`,{method:"PUT",headers:c,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update widget: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.widgetsUrl}/${e}`,{method:"DELETE"});if(!t.ok)throw new i("bad_request:api",`Failed to delete widget: ${t.statusText}`);return t.json()}async getSystemPrompt(){let e=await fetch(`${this.widgetsUrl}/system-prompt`);if(!e.ok)throw new i("bad_request:api",`Failed to get widget system prompt: ${e.statusText}`);return e.json()}async trackUsage(e){await fetch(`${this.widgetsUrl}/${e}/usage`,{method:"POST"}).catch(()=>{});}};function N(a={}){return new b(a)}var ne=N();var C=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get userUrl(){return `${this.baseUrl}/user`}async getProfile(e){try{let t=await fetch(`${this.userUrl}/profile/${e}`);if(!t.ok){if(t.status===404)return null;throw new i("bad_request:api",`Failed to get user profile: ${t.statusText}`)}return t.json()}catch(t){if(t instanceof i)throw t;return null}}async updateProfile(e,t){let s=await fetch(`${this.userUrl}/profile/${e}`,{method:"PUT",headers:c,body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new i("bad_request:api",r.error||`Failed to update user profile: ${s.statusText}`)}return s.json()}};function D(a={}){return new C(a)}var ie=D();var P=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||u;}get filesUrl(){return `${this.baseUrl}/files`}async upload(e,t){let s=new FormData;s.append("file",e,t);let r=await fetch(`${this.filesUrl}/upload`,{method:"POST",body:s});if(!r.ok)throw new i("bad_request:api",`Failed to upload file: ${r.statusText}`);return r.json()}async uploadFromUrl(e){let t=await fetch(`${this.filesUrl}/upload-url`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})});if(!t.ok)throw new i("bad_request:api",`Failed to upload file from URL: ${t.statusText}`);return t.json()}getFileUrl(e){return `${this.filesUrl}/${e}`}};function K(a={}){return new P(a)}var oe=K();var $=class{baseUrl;useCpxApi;constructor(e={}){this.baseUrl=e.baseUrl||h,this.useCpxApi=e.useCpxApi!==false;}get skillsUrl(){return this.useCpxApi?`${this.baseUrl}/cpx/agent/skills`:`${this.baseUrl}/skills`}async list(e){let t=new URLSearchParams;e?.precompiled?(t.set("precompiled","true"),e?.contentType&&t.set("content_type",e.contentType)):e?.contentType?t.set("content_type",e.contentType):e?.creatorMid?t.set("creator_mid",e.creatorMid):e?.scope&&e.scope!=="all"&&t.set("scope",e.scope);let s=t.toString()?`${this.skillsUrl}?${t.toString()}`:this.skillsUrl,r=await fetch(s);if(!r.ok)throw new Error(`Failed to list skills: ${r.statusText}`);return r.json()}async get(e){let t=await fetch(`${this.skillsUrl}/${e}`);if(!t.ok)throw new Error(`Skill not found: ${e}`);return t.json()}async create(e){let t=await fetch(this.skillsUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to create skill: ${t.statusText}`)}return t.json()}async update(e,t){let s=await fetch(`${this.skillsUrl}/${e}`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let r=await s.json().catch(()=>({}));throw new Error(r.error||`Failed to update skill: ${s.statusText}`)}return s.json()}async delete(e){let t=await fetch(`${this.skillsUrl}/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new Error(s.error||`Failed to delete skill: ${t.statusText}`)}return t.json()}async trackUsage(e){try{await fetch(`${this.skillsUrl}/${e}/usage`,{method:"POST"});}catch{}}async verify(e){let t=await fetch(`${this.skillsUrl}/${e}/verify`);if(!t.ok)throw new Error(`Failed to verify skill: ${t.statusText}`);return t.json()}async rehash(e){let t=await fetch(`${this.skillsUrl}/${e}/rehash`,{method:"POST"});if(!t.ok)throw new Error(`Failed to rehash skill: ${t.statusText}`);return t.json()}async rehashAll(){let e=await fetch(`${this.skillsUrl}/rehash-all`,{method:"POST"});if(!e.ok)throw new Error(`Failed to rehash all skills: ${e.statusText}`);return e.json()}async getMap(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map${t}`);if(!s.ok)throw new Error(`Failed to get skill map: ${s.statusText}`);return s.json()}async getMapPrompt(e){let t=e?`?content_type=${e}`:"",s=await fetch(`${this.skillsUrl}/map/prompt${t}`);if(!s.ok)throw new Error(`Failed to get skill map prompt: ${s.statusText}`);return s.json()}async getNonCodeMap(){let e=await fetch(`${this.skillsUrl}/map/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill map: ${e.statusText}`);return e.json()}async getNonCodeSummary(){let e=await fetch(`${this.skillsUrl}/summary/noncode`);if(!e.ok)throw new Error(`Failed to get non-code skill summary: ${e.statusText}`);return e.json()}};function B(a){return new $(a)}var ae=B();var T=class{baseUrl;constructor(e={}){this.baseUrl=e.baseUrl||h;}get pointsUrl(){return `${this.baseUrl}/cpx/points`}async initNetworkDomain(){let e=await fetch(`${this.pointsUrl}/init`,{method:"POST",headers:c});if(!e.ok){let t=await e.json().catch(()=>({}));throw new i("bad_request:api",t.error||`Failed to initialize network domain: ${e.statusText}`)}return e.json()}async listDomains(){let e=await fetch(`${this.pointsUrl}/domains`);if(!e.ok)throw new i("bad_request:api",`Failed to list domains: ${e.statusText}`);return e.json()}async getDomain(e){let t=await fetch(`${this.pointsUrl}/domains/${e}`);if(t.status===404)return null;if(!t.ok)throw new i("bad_request:api",`Failed to get domain: ${t.statusText}`);return t.json()}async createDomain(e){let t=await fetch(`${this.pointsUrl}/domains`,{method:"POST",headers:c,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new i("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create domain: ${t.statusText}`)}return t.json()}async listContexts(e){let t=e?`?domainId=${e}`:"",s=await fetch(`${this.pointsUrl}/contexts${t}`);if(!s.ok)throw new i("bad_request:api",`Failed to list contexts: ${s.statusText}`);return s.json()}async getContext(e){let t=await fetch(`${this.pointsUrl}/contexts/${e}`);if(t.status===404)return null;if(!t.ok)throw new i("bad_request:api",`Failed to get context: ${t.statusText}`);return t.json()}async createContext(e){let t=await fetch(`${this.pointsUrl}/contexts`,{method:"POST",headers:c,body:JSON.stringify(e)});if(t.status===402){let s=await t.json();throw new i("payment_required:api",`${s.error}${s.paymentDetails?` (Payment: ${JSON.stringify(s.paymentDetails)})`:""}`)}if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create context: ${t.statusText}`)}return t.json()}async listDelegations(e={}){let t=new URLSearchParams;e.domainId&&t.set("domainId",e.domainId),e.delegator&&t.set("delegator",e.delegator),e.delegate&&t.set("delegate",e.delegate),e.activeOnly&&t.set("activeOnly","true");let s=t.toString(),r=`${this.pointsUrl}/delegations${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to list delegations: ${n.statusText}`);return n.json()}async createDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations`,{method:"POST",headers:c,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to create delegation: ${t.statusText}`)}return t.json()}async revokeDelegation(e){let t=await fetch(`${this.pointsUrl}/delegations/${e}`,{method:"DELETE"});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to revoke delegation: ${t.statusText}`)}return t.json()}async addPoints(e){let t=await fetch(`${this.pointsUrl}/add`,{method:"POST",headers:c,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to add points: ${t.statusText}`)}return t.json()}async spendPoints(e){let t=await fetch(`${this.pointsUrl}/spend`,{method:"POST",headers:c,body:JSON.stringify(e)});if(!t.ok){let s=await t.json().catch(()=>({}));throw new i("bad_request:api",s.error||`Failed to spend points: ${t.statusText}`)}return t.json()}async getBalance(e,t={}){let s=new URLSearchParams;t.domainId&&s.set("domainId",t.domainId),t.contextId&&s.set("contextId",t.contextId);let r=s.toString(),n=`${this.pointsUrl}/balance/${e}${r?`?${r}`:""}`,o=await fetch(n);if(!o.ok)throw new i("bad_request:api",`Failed to get balance: ${o.statusText}`);return o.json()}async getHistory(e={}){let t=new URLSearchParams;e.mid&&t.set("mid",e.mid),e.domainId&&t.set("domainId",e.domainId),e.contextId&&t.set("contextId",e.contextId),e.periodStart&&t.set("periodStart",e.periodStart.toString()),e.periodEnd&&t.set("periodEnd",e.periodEnd.toString()),e.taskId&&t.set("taskId",e.taskId),e.limit&&t.set("limit",e.limit.toString()),e.offset&&t.set("offset",e.offset.toString());let s=t.toString(),r=`${this.pointsUrl}/history${s?`?${s}`:""}`,n=await fetch(r);if(!n.ok)throw new i("bad_request:api",`Failed to get history: ${n.statusText}`);return n.json()}};function W(a={}){return new T(a)}var ce=W();var J="/api/v2",x=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||p,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...c};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${J}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let l=await n.json().catch(()=>({})),d=n.status===404?"not_found":n.status===401?"unauthorized":"bad_request";throw new i(`${d}:api`,l.error?.message||l.error||`Request failed: ${n.statusText}`)}let o=await n.json();return o&&typeof o=="object"&&"data"in o?o.data:o}async createStack(e){return this.request("POST","/stacks",e)}async listStacks(){return this.request("GET","/stacks")}async getStack(e){return this.request("GET",`/stacks/${e}`)}async updateStack(e,t){return this.request("PATCH",`/stacks/${e}`,t)}async deleteStack(e){return this.request("DELETE",`/stacks/${e}`)}async configureOAuthProvider(e,t,s){return this.request("POST",`/stacks/${e}/oauth/${t}`,s)}async removeOAuthProvider(e,t){return this.request("DELETE",`/stacks/${e}/oauth/${t}`)}async configureWeb3Provider(e,t,s){return this.request("POST",`/stacks/${e}/web3/${t}`,s)}async removeWeb3Provider(e,t){return this.request("DELETE",`/stacks/${e}/web3/${t}`)}async configureStripeProvider(e,t){return this.request("POST",`/stacks/${e}/stripe`,t)}async getStripeProvider(e){return this.request("GET",`/stacks/${e}/stripe`)}async removeStripeProvider(e){return this.request("DELETE",`/stacks/${e}/stripe`)}async createPaymentIntent(e,t,s){return this.request("POST",`/stacks/${e}/stripe/payment-intent`,{amountCents:t,metadata:s})}async createKey(e,t,s){return this.request("POST",`/stacks/${e}/keys`,{name:t,permission:s})}async listKeys(e){return this.request("GET",`/stacks/${e}/keys`)}async revokeKey(e,t){return this.request("DELETE",`/stacks/${e}/keys/${t}`)}async getAllowlist(e){return this.request("GET",`/stacks/${e}/auth/allowlist`)}async updateAllowlist(e,t){return this.request("PUT",`/stacks/${e}/auth/allowlist`,t)}async updateCapabilities(e,t){return this.request("PATCH",`/stacks/${e}`,{capabilityBitmask:t})}async getModelLayers(e){return this.request("GET",`/stacks/${e}/model-layers`)}async updateModelAlias(e,t,s,r){return this.request("PATCH",`/stacks/${e}/model-layers`,{layer:t,capability:s,alias:r})}async resetModelAlias(e,t,s){return this.request("DELETE",`/stacks/${e}/model-layers/${t}/${s}`)}async uploadLogo(e,t){let s=`${this.baseUrl}${J}/stacks/${e}/logo`,r=new FormData;r.append("logo",t);let n={};this.authToken&&(n.Authorization=`Bearer ${this.authToken}`);let o=await fetch(s,{method:"POST",headers:n,body:r});if(!o.ok){let d=await o.json().catch(()=>({}));throw new i("bad_request:api",d.error?.message||`Failed to upload logo: ${o.statusText}`)}let l=await o.json();return l&&typeof l=="object"&&"data"in l?l.data:l}async deleteLogo(e){return this.request("DELETE",`/stacks/${e}/logo`)}async getMemberStats(e){return this.request("GET",`/stacks/${e}/members/stats`)}async getMembers(e,t){let s=new URLSearchParams;t?.limit&&s.set("limit",String(t.limit)),t?.offset&&s.set("offset",String(t.offset)),t?.role&&s.set("role",t.role);let r=s.toString()?`?${s}`:"";return this.request("GET",`/stacks/${e}/members${r}`)}async updateMemberRole(e,t,s){return this.request("PATCH",`/stacks/${e}/members/${encodeURIComponent(t)}/role`,{role:s})}async getUsageRecords(e,t){let s=new URLSearchParams;t?.page&&s.set("page",String(t.page)),t?.limit&&s.set("limit",String(t.limit)),t?.days&&s.set("days",String(t.days)),t?.model&&s.set("model",t.model);let r=s.toString()?`?${s}`:"";return this.request("GET",`/stacks/${e}/usage/records${r}`)}};function G(a={}){return new x(a)}var le=G();var U="/api/v2",R=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||p,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...c};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}async request(e,t){let s=await fetch(t,{method:e,headers:this.headers});if(!s.ok){let n=await s.json().catch(()=>({}));throw new i("bad_request:api",n.error?.message||`Request failed: ${s.statusText}`)}let r=await s.json();return r&&typeof r=="object"&&"data"in r?r.data:r}async checkHealth(){try{return (await fetch(`${this.baseUrl}/health`)).ok}catch{return false}}async getNetworkStatus(){return this.request("GET",`${this.baseUrl}${U}/network/status`)}async getMPCNodes(){return this.request("GET",`${this.baseUrl}${U}/network/nodes`)}async getNodeHealth(e){return this.request("GET",`${this.baseUrl}${U}/network/nodes/${e}/health`)}async getConsensusStatus(){return this.request("GET",`${this.baseUrl}/consensus/status`)}async getLeaderStatus(){return this.request("GET",`${this.baseUrl}/consensus/leader`)}async getAuthMetrics(e){let t=e?`/stacks/${e}/metrics`:"/metrics";return this.request("GET",`${this.baseUrl}${U}${t}`)}};function H(a={}){return new R(a)}var ue=H();var de="/api/v2",_=class{baseUrl;authToken;constructor(e={}){this.baseUrl=e.baseUrl||p,this.authToken=e.authToken||null;}setAuthToken(e){this.authToken=e;}get headers(){let e={...c};return this.authToken&&(e.Authorization=`Bearer ${this.authToken}`),e}url(e){return `${this.baseUrl}${de}${e}`}async request(e,t,s){let r={method:e,headers:this.headers};s&&e!=="GET"&&(r.body=JSON.stringify(s));let n=await fetch(this.url(t),r);if(!n.ok){let l=await n.json().catch(()=>({}));throw new i(n.status===402?"payment_required:api":"bad_request:api",l.error?.message||`Request failed: ${n.statusText}`)}let o=await n.json();return o&&typeof o=="object"&&"data"in o?o.data:o}async getPlans(e){return this.request("GET",`/stacks/${e}/billing/plans`)}async getBillingState(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing`)}async createCheckoutSession(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/checkout`,{identity_id:t,plan_id:s,success_url:r,cancel_url:n})}async createBillingPortal(e,t,s){return this.request("POST",`/stacks/${e}/billing/portal`,{identity_id:t,return_url:s})}async recordUsage(e,t,s,r,n){return this.request("POST",`/stacks/${e}/billing/usage`,{identity_id:t,usage_type:s,quantity:r,idempotency_key:n})}async getCurrentUsage(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/usage`)}async linkStripeCustomer(e,t,s,r){return this.request("POST",`/stacks/${e}/billing/link`,{identity_id:t,stripe_customer_id:s,checkout_session_id:r})}async hasPaymentMethod(e,t){return this.request("GET",`/stacks/${e}/identities/${t}/billing/payment-method`)}async subscribeSol(e,t,s){return this.request("POST",`/stacks/${e}/subscribe-sol`,{planId:t,txSignature:s})}async prepaidSol(e,t,s,r){return this.request("POST",`/stacks/${e}/prepaid-sol`,{amountCents:t,txSignature:s,scope:r})}async topup(e,t,s){return this.request("POST","/account/topup",{amount_cents:e,payment_method:t,payment_ref:s})}};function z(a={}){return new _(a)}var pe=z();
|
|
4
|
+
exports.AgentsClient=S;exports.BillingClient=_;exports.FilesClient=P;exports.MCPClient=w;exports.MagmaClient=y;exports.NetworkClient=R;exports.PointsClient=T;exports.SkillsClient=$;exports.SocialClient=k;exports.StackManagementClient=x;exports.TaskNetworkClient=f;exports.UserClient=C;exports.WidgetsClient=b;exports.agentsClient=re;exports.billingClient=pe;exports.createAgentsClient=L;exports.createBillingClient=z;exports.createFilesClient=K;exports.createMCPClient=M;exports.createMagmaClient=O;exports.createNetworkClient=H;exports.createPointsClient=W;exports.createSkillsClient=B;exports.createSocialClient=j;exports.createStackManagementClient=G;exports.createTaskNetworkClient=F;exports.createUserClient=D;exports.createWidgetsClient=N;exports.filesClient=oe;exports.magmaClient=X;exports.mcpClient=Q;exports.networkClient=ue;exports.pointsClient=ce;exports.skillsClient=ae;exports.socialClient=se;exports.stackManagementClient=le;exports.taskNetworkClient=V;exports.userClient=ie;exports.widgetsClient=ne;
|
package/dist/clients/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { D as ChatCompletionRequest, z as ChatCompletionChunk, bi as TaskPayload, al as MagmaFile, a9 as ImaginationMetadata, ai as MCPSessionConfig, ah as MCPSession, aj as MCPToolResult, aZ as SocialClientConfig, an as MediaType, a3 as FeedResponse, aL as PostResponse, G as CommentsResponse, aN as RemixesResponse, ad as LikeCheckResponse, ae as LikeResponse, F as CommentResponse, U as CreatePostInput, V as CreatePostResponse, aw as NotificationCounts, au as NotificationAction, ax as NotificationListResponse, am as MarkViewedInput, aM as ProfileResponse, n as AgentsClientConfig, o as AgentsListResponse, c as Agent, d as AgentCreateInput, h as AgentResponse, j as AgentUpdateInput, e as AgentExecuteRequest, f as AgentExecuteResponse, g as AgentFromPromptInput, by as WidgetsClientConfig, bz as WidgetsListResponse, bt as Widget, bu as WidgetCreateInput, bv as WidgetResponse, bx as WidgetUpdateInput, bw as WidgetSystemPromptResponse, bp as UserClientConfig, bq as UserProfile, bs as UserProfileUpdateInput, br as UserProfileResponse, a5 as FilesClientConfig, a4 as FileUploadResponse, aW as SkillsClientConfig, aX as SkillsListResponse, aO as Skill, aP as SkillCreateInput, aS as SkillResponse, aU as SkillUpdateInput, aV as SkillVerifyResponse, aR as SkillMapResponse, aQ as SkillMapPromptResponse, aT as SkillSummaryResponse, aK as PointsClientConfig, ab as InitNetworkResponse, a2 as DomainsListResponse, M as ContextDomain, S as CreateDomainInput, a1 as DomainResponse, O as ContextsListResponse, aF as PointContext, Q as CreateContextInput, N as ContextResponse, Z as DelegationFilters, a0 as DelegationsListResponse, R as CreateDelegationInput, _ as DelegationResponse, b as AddPointsInput, aH as PointRecordResponse, b4 as SpendPointsInput, aJ as PointSpendResponse, aE as PointBalance, a6 as HistoryFilters, a7 as HistoryResponse, ba as StackManagementClientConfig, W as CreateStackRequest, bf as StackResponse, b9 as StackListResponse, b6 as StackConfig, H as ConfigureOAuthInput, be as StackOAuthProvider, J as ConfigureWeb3Input, bh as StackWeb3Provider, I as ConfigureStripeInput, bg as StackStripeProvider, T as CreateKeyResponse, b8 as StackKeysListResponse, p as AllowlistConfig, r as AllowlistUpdateInput, ar as ModelLayersResponse, bc as StackMemberStats, bb as StackMember, as as NetworkClientConfig, at as NetworkStatus, ak as MPCNode, L as ConsensusStatus, ac as LeaderStatus, s as AuthMetrics, B as BillingClientConfig, u as BillingPlansResponse, w as BillingState, P as CreateCheckoutSessionResponse, v as BillingPortalResponse } from '../billing-cj0eSVrp.cjs';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* TaskNetworkClient - OpenAI-compatible SDK for StackNet
|
|
@@ -238,6 +238,29 @@ declare class SocialClient {
|
|
|
238
238
|
* Track a play on audio/video post
|
|
239
239
|
*/
|
|
240
240
|
trackPlay(postId: string, userMid?: string): Promise<void>;
|
|
241
|
+
private get notificationsUrl();
|
|
242
|
+
/** Unviewed counts for the authenticated user, grouped by action. */
|
|
243
|
+
getNotificationCounts(): Promise<NotificationCounts>;
|
|
244
|
+
/** Recent notification rows for the authenticated user. */
|
|
245
|
+
getNotifications(options?: {
|
|
246
|
+
sinceId?: number;
|
|
247
|
+
beforeId?: number;
|
|
248
|
+
action?: NotificationAction;
|
|
249
|
+
limit?: number;
|
|
250
|
+
unviewedOnly?: boolean;
|
|
251
|
+
}): Promise<NotificationListResponse>;
|
|
252
|
+
/** Mark notifications viewed (by id list, up_to_id, and/or action). */
|
|
253
|
+
markNotificationsViewed(input: MarkViewedInput): Promise<{
|
|
254
|
+
updated: number;
|
|
255
|
+
}>;
|
|
256
|
+
/**
|
|
257
|
+
* Permanently remove notifications. Used by clients that want
|
|
258
|
+
* "view = remove" semantics (the geoff hover panel and /activity page
|
|
259
|
+
* both call this on render). Body shape mirrors mark-viewed.
|
|
260
|
+
*/
|
|
261
|
+
clearNotifications(input: MarkViewedInput): Promise<{
|
|
262
|
+
deleted: number;
|
|
263
|
+
}>;
|
|
241
264
|
/**
|
|
242
265
|
* Get user profile by MID
|
|
243
266
|
*/
|