@statewavedev/sdk 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -0
- package/README.md +148 -0
- package/dist/client.d.ts +48 -0
- package/dist/client.js +212 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/types.d.ts +117 -0
- package/dist/types.js +2 -0
- package/package.json +56 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
# @statewavedev/sdk
|
|
2
|
+
|
|
3
|
+
[](https://github.com/smaramwbc/statewave-ts/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/@statewavedev/sdk)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
Official TypeScript SDK for [Statewave](https://github.com/smaramwbc/statewave) — memory runtime for AI agents and applications.
|
|
8
|
+
|
|
9
|
+
> **Part of the Statewave ecosystem:** [Server](https://github.com/smaramwbc/statewave) · [Python SDK](https://github.com/smaramwbc/statewave-py) · **TypeScript SDK** · [Connectors](https://github.com/smaramwbc/statewave-connectors) · [Docs](https://github.com/smaramwbc/statewave-docs) · [Examples](https://github.com/smaramwbc/statewave-examples) · [Website + demo](https://statewave.ai) · [Admin](https://github.com/smaramwbc/statewave-admin)
|
|
10
|
+
>
|
|
11
|
+
> 📋 **Issues & feature requests:** [statewave/issues](https://github.com/smaramwbc/statewave/issues) (centralized tracker)
|
|
12
|
+
|
|
13
|
+
## Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
npm install @statewavedev/sdk
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
> Before public launch, this package used the internal name `statewave-ts`. New code should use `@statewavedev/sdk`.
|
|
20
|
+
|
|
21
|
+
## Quick start
|
|
22
|
+
|
|
23
|
+
```typescript
|
|
24
|
+
import { StatewaveClient } from "@statewavedev/sdk";
|
|
25
|
+
|
|
26
|
+
// Basic (no auth)
|
|
27
|
+
const sw = new StatewaveClient("http://localhost:8100");
|
|
28
|
+
|
|
29
|
+
// With authentication and tenant
|
|
30
|
+
const swAuth = new StatewaveClient({
|
|
31
|
+
baseUrl: "http://localhost:8100",
|
|
32
|
+
apiKey: "your-key",
|
|
33
|
+
tenantId: "acme",
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
// Record an episode
|
|
37
|
+
await sw.createEpisode({
|
|
38
|
+
subject_id: "user-42",
|
|
39
|
+
source: "support-chat",
|
|
40
|
+
type: "conversation",
|
|
41
|
+
payload: {
|
|
42
|
+
messages: [
|
|
43
|
+
{ role: "user", content: "My name is Alice and I work at Globex." },
|
|
44
|
+
{ role: "assistant", content: "Welcome Alice!" },
|
|
45
|
+
],
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
|
|
49
|
+
// Compile memories (idempotent)
|
|
50
|
+
const result = await sw.compileMemories("user-42");
|
|
51
|
+
console.log(`Created ${result.memories_created} memories`);
|
|
52
|
+
|
|
53
|
+
// Retrieve ranked, token-bounded context
|
|
54
|
+
const ctx = await sw.getContext({
|
|
55
|
+
subject_id: "user-42",
|
|
56
|
+
task: "Help with billing",
|
|
57
|
+
max_tokens: 300,
|
|
58
|
+
});
|
|
59
|
+
console.log(ctx.assembled_context);
|
|
60
|
+
|
|
61
|
+
// Batch ingestion (up to 100)
|
|
62
|
+
await sw.createEpisodesBatch([
|
|
63
|
+
{ subject_id: "user-42", source: "crm", type: "note", payload: { text: "Prefers email" } },
|
|
64
|
+
{ subject_id: "user-42", source: "crm", type: "note", payload: { text: "Enterprise plan" } },
|
|
65
|
+
]);
|
|
66
|
+
|
|
67
|
+
// Search memories
|
|
68
|
+
const facts = await sw.searchMemories({
|
|
69
|
+
subject_id: "user-42",
|
|
70
|
+
kind: "profile_fact",
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
// Semantic search (requires embeddings)
|
|
74
|
+
const results = await sw.searchMemories({
|
|
75
|
+
subject_id: "user-42",
|
|
76
|
+
query: "billing",
|
|
77
|
+
semantic: true,
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// List all known subjects
|
|
81
|
+
const subjects = await sw.listSubjects();
|
|
82
|
+
for (const s of subjects.subjects) {
|
|
83
|
+
console.log(`${s.subject_id}: ${s.episode_count} episodes, ${s.memory_count} memories`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Get timeline
|
|
87
|
+
const timeline = await sw.getTimeline("user-42");
|
|
88
|
+
console.log(`${timeline.episodes.length} episodes, ${timeline.memories.length} memories`);
|
|
89
|
+
|
|
90
|
+
// Delete all subject data
|
|
91
|
+
await sw.deleteSubject("user-42");
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Error handling
|
|
95
|
+
|
|
96
|
+
```typescript
|
|
97
|
+
import { StatewaveClient, StatewaveAPIError, StatewaveConnectionError } from "@statewavedev/sdk";
|
|
98
|
+
|
|
99
|
+
const sw = new StatewaveClient();
|
|
100
|
+
|
|
101
|
+
try {
|
|
102
|
+
await sw.compileMemories("user-42");
|
|
103
|
+
} catch (e) {
|
|
104
|
+
if (e instanceof StatewaveAPIError) {
|
|
105
|
+
console.error(`API error [${e.statusCode}]: ${e.code} — ${e.message}`);
|
|
106
|
+
console.error(`Request ID: ${e.requestId}`);
|
|
107
|
+
} else if (e instanceof StatewaveConnectionError) {
|
|
108
|
+
console.error("Cannot connect to Statewave server");
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
## Where does data go?
|
|
114
|
+
|
|
115
|
+
The SDK is a thin client over the Statewave HTTP API. What leaves the network is determined by the **server's** compiler and embedding configuration, not by the SDK:
|
|
116
|
+
|
|
117
|
+
- Default deployment (heuristic compiler, no embeddings) — nothing leaves your infrastructure.
|
|
118
|
+
- LLM compiler or hosted embeddings — the server sends content to the provider you configure.
|
|
119
|
+
|
|
120
|
+
See [Privacy & Data Flow](https://github.com/smaramwbc/statewave-docs/blob/main/architecture/privacy-and-data-flow.md) for the full breakdown.
|
|
121
|
+
|
|
122
|
+
## Types
|
|
123
|
+
|
|
124
|
+
All response types are fully typed:
|
|
125
|
+
|
|
126
|
+
- `Episode` — raw interaction record
|
|
127
|
+
- `Memory` — compiled memory with provenance
|
|
128
|
+
- `CompileResult` — compilation response
|
|
129
|
+
- `SearchResult` — search response
|
|
130
|
+
- `ContextBundle` — assembled context with facts, episodes, provenance
|
|
131
|
+
- `Timeline` — chronological subject history
|
|
132
|
+
- `DeleteResult` — deletion confirmation
|
|
133
|
+
- `BatchCreateResult` — batch ingestion response
|
|
134
|
+
- `SubjectSummary` — subject with episode/memory counts
|
|
135
|
+
- `ListSubjectsResult` — paginated subject listing
|
|
136
|
+
|
|
137
|
+
Param types: `CreateEpisodeParams`, `SearchMemoriesParams`, `GetContextParams`
|
|
138
|
+
|
|
139
|
+
## Running tests
|
|
140
|
+
|
|
141
|
+
```bash
|
|
142
|
+
npm install
|
|
143
|
+
npm test
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## License
|
|
147
|
+
|
|
148
|
+
Apache-2.0
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { BatchCreateResult, ClientOptions, CompileJob, CompileResult, ContextBundle, CreateEpisodeParams, DeleteResult, Episode, GetContextParams, ListSubjectsResult, SearchMemoriesParams, SearchResult, Timeline } from "./types.js";
|
|
2
|
+
/** Structured error from the Statewave API. */
|
|
3
|
+
export declare class StatewaveAPIError extends Error {
|
|
4
|
+
readonly statusCode: number;
|
|
5
|
+
readonly code: string;
|
|
6
|
+
readonly details?: unknown;
|
|
7
|
+
readonly requestId?: string;
|
|
8
|
+
constructor(statusCode: number, code: string, message: string, details?: unknown, requestId?: string);
|
|
9
|
+
}
|
|
10
|
+
/** Raised when the SDK cannot reach the Statewave server. */
|
|
11
|
+
export declare class StatewaveConnectionError extends Error {
|
|
12
|
+
constructor(message?: string);
|
|
13
|
+
}
|
|
14
|
+
export declare class StatewaveClient {
|
|
15
|
+
private baseUrl;
|
|
16
|
+
private defaultHeaders;
|
|
17
|
+
private retryConfig;
|
|
18
|
+
constructor(options?: ClientOptions | string);
|
|
19
|
+
createEpisode(params: CreateEpisodeParams): Promise<Episode>;
|
|
20
|
+
createEpisodesBatch(episodes: CreateEpisodeParams[]): Promise<BatchCreateResult>;
|
|
21
|
+
compileMemories(subjectId: string): Promise<CompileResult>;
|
|
22
|
+
/** Submit async compilation — returns immediately with a job_id. */
|
|
23
|
+
compileMemoriesAsync(subjectId: string): Promise<CompileJob>;
|
|
24
|
+
/** Poll the status of an async compile job. */
|
|
25
|
+
getCompileStatus(jobId: string): Promise<CompileJob>;
|
|
26
|
+
/** Submit async compilation and poll until terminal state or timeout. */
|
|
27
|
+
compileMemoriesWait(subjectId: string, options?: {
|
|
28
|
+
pollInterval?: number;
|
|
29
|
+
timeout?: number;
|
|
30
|
+
}): Promise<CompileJob>;
|
|
31
|
+
searchMemories(params: SearchMemoriesParams): Promise<SearchResult>;
|
|
32
|
+
getContext(params: GetContextParams): Promise<ContextBundle>;
|
|
33
|
+
/** Return just the assembled context string, ready to inject into a prompt. */
|
|
34
|
+
getContextString(params: GetContextParams): Promise<string>;
|
|
35
|
+
getTimeline(subjectId: string): Promise<Timeline>;
|
|
36
|
+
deleteSubject(subjectId: string): Promise<DeleteResult>;
|
|
37
|
+
listSubjects(params?: {
|
|
38
|
+
limit?: number;
|
|
39
|
+
offset?: number;
|
|
40
|
+
}): Promise<ListSubjectsResult>;
|
|
41
|
+
private get;
|
|
42
|
+
private post;
|
|
43
|
+
private request;
|
|
44
|
+
private delayForAttempt;
|
|
45
|
+
private parseRetryAfter;
|
|
46
|
+
private sleep;
|
|
47
|
+
private handleErrorResponse;
|
|
48
|
+
}
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/** Structured error from the Statewave API. */
|
|
2
|
+
export class StatewaveAPIError extends Error {
|
|
3
|
+
statusCode;
|
|
4
|
+
code;
|
|
5
|
+
details;
|
|
6
|
+
requestId;
|
|
7
|
+
constructor(statusCode, code, message, details, requestId) {
|
|
8
|
+
super(`[${statusCode}] ${code}: ${message}`);
|
|
9
|
+
this.name = "StatewaveAPIError";
|
|
10
|
+
this.statusCode = statusCode;
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.details = details;
|
|
13
|
+
this.requestId = requestId;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Raised when the SDK cannot reach the Statewave server. */
|
|
17
|
+
export class StatewaveConnectionError extends Error {
|
|
18
|
+
constructor(message = "Cannot connect to Statewave server") {
|
|
19
|
+
super(message);
|
|
20
|
+
this.name = "StatewaveConnectionError";
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
export class StatewaveClient {
|
|
24
|
+
baseUrl;
|
|
25
|
+
defaultHeaders;
|
|
26
|
+
retryConfig;
|
|
27
|
+
constructor(options = "http://localhost:8100") {
|
|
28
|
+
const opts = typeof options === "string" ? { baseUrl: options } : options;
|
|
29
|
+
const rawBaseUrl = opts.baseUrl ?? "http://localhost:8100";
|
|
30
|
+
let end = rawBaseUrl.length;
|
|
31
|
+
while (end > 0 && rawBaseUrl[end - 1] === "/")
|
|
32
|
+
end--;
|
|
33
|
+
this.baseUrl = rawBaseUrl.slice(0, end);
|
|
34
|
+
this.defaultHeaders = {};
|
|
35
|
+
if (opts.apiKey)
|
|
36
|
+
this.defaultHeaders["X-API-Key"] = opts.apiKey;
|
|
37
|
+
if (opts.tenantId)
|
|
38
|
+
this.defaultHeaders["X-Tenant-ID"] = opts.tenantId;
|
|
39
|
+
const retry = opts.retry === false ? { maxRetries: 0 } : (opts.retry ?? {});
|
|
40
|
+
this.retryConfig = {
|
|
41
|
+
maxRetries: retry.maxRetries ?? 3,
|
|
42
|
+
backoffBase: retry.backoffBase ?? 500,
|
|
43
|
+
backoffMax: retry.backoffMax ?? 30_000,
|
|
44
|
+
jitter: retry.jitter ?? true,
|
|
45
|
+
retryOnStatus: retry.retryOnStatus ?? [429, 500, 502, 503, 504],
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
async createEpisode(params) {
|
|
49
|
+
return this.post("/v1/episodes", {
|
|
50
|
+
subject_id: params.subject_id,
|
|
51
|
+
source: params.source,
|
|
52
|
+
type: params.type,
|
|
53
|
+
payload: params.payload,
|
|
54
|
+
metadata: params.metadata ?? {},
|
|
55
|
+
provenance: params.provenance ?? {},
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
async createEpisodesBatch(episodes) {
|
|
59
|
+
return this.post("/v1/episodes/batch", { episodes: episodes.map(e => ({
|
|
60
|
+
subject_id: e.subject_id,
|
|
61
|
+
source: e.source,
|
|
62
|
+
type: e.type,
|
|
63
|
+
payload: e.payload,
|
|
64
|
+
metadata: e.metadata ?? {},
|
|
65
|
+
provenance: e.provenance ?? {},
|
|
66
|
+
})) });
|
|
67
|
+
}
|
|
68
|
+
async compileMemories(subjectId) {
|
|
69
|
+
return this.post("/v1/memories/compile", { subject_id: subjectId });
|
|
70
|
+
}
|
|
71
|
+
/** Submit async compilation — returns immediately with a job_id. */
|
|
72
|
+
async compileMemoriesAsync(subjectId) {
|
|
73
|
+
return this.post("/v1/memories/compile", { subject_id: subjectId, async: true });
|
|
74
|
+
}
|
|
75
|
+
/** Poll the status of an async compile job. */
|
|
76
|
+
async getCompileStatus(jobId) {
|
|
77
|
+
return this.get(`/v1/memories/compile/${encodeURIComponent(jobId)}`);
|
|
78
|
+
}
|
|
79
|
+
/** Submit async compilation and poll until terminal state or timeout. */
|
|
80
|
+
async compileMemoriesWait(subjectId, options) {
|
|
81
|
+
const pollInterval = options?.pollInterval ?? 500;
|
|
82
|
+
const timeout = options?.timeout ?? 60_000;
|
|
83
|
+
const job = await this.compileMemoriesAsync(subjectId);
|
|
84
|
+
const start = Date.now();
|
|
85
|
+
while (Date.now() - start < timeout) {
|
|
86
|
+
await new Promise(r => setTimeout(r, pollInterval));
|
|
87
|
+
const status = await this.getCompileStatus(job.job_id);
|
|
88
|
+
if (status.status === "completed" || status.status === "failed") {
|
|
89
|
+
return status;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
throw new Error(`Compile job ${job.job_id} did not complete within ${timeout}ms`);
|
|
93
|
+
}
|
|
94
|
+
async searchMemories(params) {
|
|
95
|
+
const qs = new URLSearchParams({ subject_id: params.subject_id });
|
|
96
|
+
if (params.kind)
|
|
97
|
+
qs.set("kind", params.kind);
|
|
98
|
+
if (params.query)
|
|
99
|
+
qs.set("q", params.query);
|
|
100
|
+
if (params.semantic)
|
|
101
|
+
qs.set("semantic", "true");
|
|
102
|
+
if (params.limit !== undefined)
|
|
103
|
+
qs.set("limit", String(params.limit));
|
|
104
|
+
return this.get(`/v1/memories/search?${qs}`);
|
|
105
|
+
}
|
|
106
|
+
async getContext(params) {
|
|
107
|
+
return this.post("/v1/context", {
|
|
108
|
+
subject_id: params.subject_id,
|
|
109
|
+
task: params.task,
|
|
110
|
+
...(params.max_tokens !== undefined && { max_tokens: params.max_tokens }),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
/** Return just the assembled context string, ready to inject into a prompt. */
|
|
114
|
+
async getContextString(params) {
|
|
115
|
+
const bundle = await this.getContext(params);
|
|
116
|
+
return bundle.assembled_context;
|
|
117
|
+
}
|
|
118
|
+
async getTimeline(subjectId) {
|
|
119
|
+
return this.get(`/v1/timeline?subject_id=${encodeURIComponent(subjectId)}`);
|
|
120
|
+
}
|
|
121
|
+
async deleteSubject(subjectId) {
|
|
122
|
+
return this.request("DELETE", `/v1/subjects/${encodeURIComponent(subjectId)}`);
|
|
123
|
+
}
|
|
124
|
+
async listSubjects(params) {
|
|
125
|
+
const qs = new URLSearchParams();
|
|
126
|
+
if (params?.limit !== undefined)
|
|
127
|
+
qs.set("limit", String(params.limit));
|
|
128
|
+
if (params?.offset !== undefined)
|
|
129
|
+
qs.set("offset", String(params.offset));
|
|
130
|
+
const query = qs.toString();
|
|
131
|
+
return this.get(`/v1/subjects${query ? `?${query}` : ""}`);
|
|
132
|
+
}
|
|
133
|
+
// ------------------------------------------------------------------
|
|
134
|
+
async get(path) {
|
|
135
|
+
return this.request("GET", path);
|
|
136
|
+
}
|
|
137
|
+
async post(path, body) {
|
|
138
|
+
return this.request("POST", path, body);
|
|
139
|
+
}
|
|
140
|
+
async request(method, path, body) {
|
|
141
|
+
let lastError;
|
|
142
|
+
for (let attempt = 0; attempt <= this.retryConfig.maxRetries; attempt++) {
|
|
143
|
+
let resp;
|
|
144
|
+
try {
|
|
145
|
+
const headers = { ...this.defaultHeaders };
|
|
146
|
+
if (body)
|
|
147
|
+
headers["Content-Type"] = "application/json";
|
|
148
|
+
resp = await fetch(`${this.baseUrl}${path}`, {
|
|
149
|
+
method,
|
|
150
|
+
headers,
|
|
151
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
catch (err) {
|
|
155
|
+
// Network/connection error — retryable
|
|
156
|
+
lastError = err instanceof Error ? err : new Error(String(err));
|
|
157
|
+
if (attempt < this.retryConfig.maxRetries) {
|
|
158
|
+
await this.sleep(this.delayForAttempt(attempt));
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
throw new StatewaveConnectionError(lastError.message);
|
|
162
|
+
}
|
|
163
|
+
if (resp.ok) {
|
|
164
|
+
return resp.json();
|
|
165
|
+
}
|
|
166
|
+
// Check if retryable status
|
|
167
|
+
if (this.retryConfig.retryOnStatus.includes(resp.status) && attempt < this.retryConfig.maxRetries) {
|
|
168
|
+
const retryAfter = this.parseRetryAfter(resp);
|
|
169
|
+
await this.sleep(this.delayForAttempt(attempt, retryAfter));
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
172
|
+
await this.handleErrorResponse(resp);
|
|
173
|
+
}
|
|
174
|
+
// Should not reach here
|
|
175
|
+
throw new StatewaveConnectionError(lastError?.message ?? "Retry attempts exhausted");
|
|
176
|
+
}
|
|
177
|
+
delayForAttempt(attempt, retryAfterMs) {
|
|
178
|
+
if (retryAfterMs !== undefined) {
|
|
179
|
+
return Math.min(retryAfterMs, this.retryConfig.backoffMax);
|
|
180
|
+
}
|
|
181
|
+
let delay = this.retryConfig.backoffBase * (2 ** attempt);
|
|
182
|
+
delay = Math.min(delay, this.retryConfig.backoffMax);
|
|
183
|
+
if (this.retryConfig.jitter) {
|
|
184
|
+
delay *= 0.5 + Math.random();
|
|
185
|
+
}
|
|
186
|
+
return delay;
|
|
187
|
+
}
|
|
188
|
+
parseRetryAfter(resp) {
|
|
189
|
+
const value = resp.headers.get("retry-after");
|
|
190
|
+
if (!value)
|
|
191
|
+
return undefined;
|
|
192
|
+
const seconds = parseFloat(value);
|
|
193
|
+
return isNaN(seconds) ? undefined : seconds * 1000;
|
|
194
|
+
}
|
|
195
|
+
sleep(ms) {
|
|
196
|
+
return new Promise(resolve => setTimeout(resolve, ms));
|
|
197
|
+
}
|
|
198
|
+
async handleErrorResponse(resp) {
|
|
199
|
+
try {
|
|
200
|
+
const body = await resp.json();
|
|
201
|
+
const err = body?.error;
|
|
202
|
+
if (err && typeof err.code === "string") {
|
|
203
|
+
throw new StatewaveAPIError(resp.status, err.code, err.message ?? resp.statusText, err.details, err.request_id);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
catch (e) {
|
|
207
|
+
if (e instanceof StatewaveAPIError)
|
|
208
|
+
throw e;
|
|
209
|
+
}
|
|
210
|
+
throw new StatewaveAPIError(resp.status, "unknown", resp.statusText);
|
|
211
|
+
}
|
|
212
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { StatewaveClient, StatewaveAPIError, StatewaveConnectionError } from "./client.js";
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/** Statewave API types — mirrors the backend contract. */
|
|
2
|
+
export interface Episode {
|
|
3
|
+
id: string;
|
|
4
|
+
subject_id: string;
|
|
5
|
+
source: string;
|
|
6
|
+
type: string;
|
|
7
|
+
payload: Record<string, unknown>;
|
|
8
|
+
metadata: Record<string, unknown>;
|
|
9
|
+
provenance: Record<string, unknown>;
|
|
10
|
+
created_at: string;
|
|
11
|
+
}
|
|
12
|
+
export interface Memory {
|
|
13
|
+
id: string;
|
|
14
|
+
subject_id: string;
|
|
15
|
+
kind: string;
|
|
16
|
+
content: string;
|
|
17
|
+
summary: string;
|
|
18
|
+
confidence: number;
|
|
19
|
+
valid_from: string;
|
|
20
|
+
valid_to: string | null;
|
|
21
|
+
source_episode_ids: string[];
|
|
22
|
+
metadata: Record<string, unknown>;
|
|
23
|
+
status: string;
|
|
24
|
+
created_at: string;
|
|
25
|
+
updated_at: string;
|
|
26
|
+
}
|
|
27
|
+
export interface CompileResult {
|
|
28
|
+
subject_id: string;
|
|
29
|
+
memories_created: number;
|
|
30
|
+
memories: Memory[];
|
|
31
|
+
}
|
|
32
|
+
export interface SearchResult {
|
|
33
|
+
memories: Memory[];
|
|
34
|
+
}
|
|
35
|
+
export interface ContextBundle {
|
|
36
|
+
subject_id: string;
|
|
37
|
+
task: string;
|
|
38
|
+
facts: Memory[];
|
|
39
|
+
episodes: Episode[];
|
|
40
|
+
procedures: Memory[];
|
|
41
|
+
provenance: Record<string, unknown>;
|
|
42
|
+
assembled_context: string;
|
|
43
|
+
token_estimate: number;
|
|
44
|
+
}
|
|
45
|
+
export interface Timeline {
|
|
46
|
+
subject_id: string;
|
|
47
|
+
episodes: Episode[];
|
|
48
|
+
memories: Memory[];
|
|
49
|
+
}
|
|
50
|
+
export interface DeleteResult {
|
|
51
|
+
subject_id: string;
|
|
52
|
+
episodes_deleted: number;
|
|
53
|
+
memories_deleted: number;
|
|
54
|
+
}
|
|
55
|
+
export interface BatchCreateResult {
|
|
56
|
+
episodes_created: number;
|
|
57
|
+
episodes: Episode[];
|
|
58
|
+
}
|
|
59
|
+
export interface SubjectSummary {
|
|
60
|
+
subject_id: string;
|
|
61
|
+
episode_count: number;
|
|
62
|
+
memory_count: number;
|
|
63
|
+
}
|
|
64
|
+
export interface ListSubjectsResult {
|
|
65
|
+
subjects: SubjectSummary[];
|
|
66
|
+
total: number;
|
|
67
|
+
}
|
|
68
|
+
/** Status of an async compile job. */
|
|
69
|
+
export interface CompileJob {
|
|
70
|
+
job_id: string;
|
|
71
|
+
status: "pending" | "running" | "completed" | "failed";
|
|
72
|
+
subject_id: string;
|
|
73
|
+
memories_created?: number;
|
|
74
|
+
memories?: Memory[];
|
|
75
|
+
error?: string;
|
|
76
|
+
}
|
|
77
|
+
export interface CreateEpisodeParams {
|
|
78
|
+
subject_id: string;
|
|
79
|
+
source: string;
|
|
80
|
+
type: string;
|
|
81
|
+
payload: Record<string, unknown>;
|
|
82
|
+
metadata?: Record<string, unknown>;
|
|
83
|
+
provenance?: Record<string, unknown>;
|
|
84
|
+
session_id?: string;
|
|
85
|
+
}
|
|
86
|
+
export interface SearchMemoriesParams {
|
|
87
|
+
subject_id: string;
|
|
88
|
+
kind?: string;
|
|
89
|
+
query?: string;
|
|
90
|
+
semantic?: boolean;
|
|
91
|
+
limit?: number;
|
|
92
|
+
}
|
|
93
|
+
export interface GetContextParams {
|
|
94
|
+
subject_id: string;
|
|
95
|
+
task: string;
|
|
96
|
+
max_tokens?: number;
|
|
97
|
+
}
|
|
98
|
+
export interface ClientOptions {
|
|
99
|
+
baseUrl?: string;
|
|
100
|
+
apiKey?: string;
|
|
101
|
+
tenantId?: string;
|
|
102
|
+
/** Retry configuration. Set to false to disable retries. */
|
|
103
|
+
retry?: RetryConfig | false;
|
|
104
|
+
}
|
|
105
|
+
/** Configuration for automatic retry on transient failures. */
|
|
106
|
+
export interface RetryConfig {
|
|
107
|
+
/** Maximum number of retry attempts (default: 3). */
|
|
108
|
+
maxRetries?: number;
|
|
109
|
+
/** Base delay in ms for exponential backoff (default: 500). */
|
|
110
|
+
backoffBase?: number;
|
|
111
|
+
/** Maximum delay cap in ms (default: 30000). */
|
|
112
|
+
backoffMax?: number;
|
|
113
|
+
/** Whether to add random jitter (default: true). */
|
|
114
|
+
jitter?: boolean;
|
|
115
|
+
/** HTTP status codes that trigger a retry (default: [429, 500, 502, 503, 504]). */
|
|
116
|
+
retryOnStatus?: number[];
|
|
117
|
+
}
|
package/dist/types.js
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@statewavedev/sdk",
|
|
3
|
+
"version": "0.7.0",
|
|
4
|
+
"description": "Official TypeScript SDK for Statewave — Memory OS for AI agents",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./package.json": "./package.json"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"README.md",
|
|
18
|
+
"LICENSE"
|
|
19
|
+
],
|
|
20
|
+
"license": "Apache-2.0",
|
|
21
|
+
"author": "Statewave <hello@statewave.ai>",
|
|
22
|
+
"keywords": [
|
|
23
|
+
"statewave",
|
|
24
|
+
"ai",
|
|
25
|
+
"agents",
|
|
26
|
+
"memory",
|
|
27
|
+
"context",
|
|
28
|
+
"sdk",
|
|
29
|
+
"typescript"
|
|
30
|
+
],
|
|
31
|
+
"repository": {
|
|
32
|
+
"type": "git",
|
|
33
|
+
"url": "https://github.com/smaramwbc/statewave-ts.git"
|
|
34
|
+
},
|
|
35
|
+
"bugs": {
|
|
36
|
+
"url": "https://github.com/smaramwbc/statewave-ts/issues"
|
|
37
|
+
},
|
|
38
|
+
"homepage": "https://statewave.ai",
|
|
39
|
+
"engines": {
|
|
40
|
+
"node": ">=18"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public",
|
|
44
|
+
"provenance": true
|
|
45
|
+
},
|
|
46
|
+
"sideEffects": false,
|
|
47
|
+
"scripts": {
|
|
48
|
+
"build": "tsc",
|
|
49
|
+
"prepublishOnly": "tsc",
|
|
50
|
+
"test": "vitest run"
|
|
51
|
+
},
|
|
52
|
+
"devDependencies": {
|
|
53
|
+
"typescript": "^6.0",
|
|
54
|
+
"vitest": "^4.1"
|
|
55
|
+
}
|
|
56
|
+
}
|