@masorinho99/statesync-client 0.1.1
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 +21 -0
- package/README.md +150 -0
- package/dist/index.cjs +181 -0
- package/dist/index.d.cts +130 -0
- package/dist/index.d.ts +130 -0
- package/dist/index.js +155 -0
- package/package.json +57 -0
- package/src/index.ts +278 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 StateSync
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
# @masorinho99/statesync-client
|
|
2
|
+
|
|
3
|
+
**StateSync โ the global state database for AI coding agents.**
|
|
4
|
+
|
|
5
|
+
Two lines. Any agent. Persistent memory.
|
|
6
|
+
|
|
7
|
+
๐ **[Full documentation โ](https://www.statesync.it/docs)** ยท ๐ **[Quickstart](https://www.statesync.it/docs/quickstart)** ยท ๐ **[Get an API key](https://www.statesync.it/dashboard/api-keys)** ยท ๐ฌ **[MCP guide](https://www.statesync.it/docs/cursor)**
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install @masorinho99/statesync-client
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { StateSync } from "@masorinho99/statesync-client";
|
|
17
|
+
|
|
18
|
+
const sync = new StateSync({ apiKey: "ss_live_..." }); // 1
|
|
19
|
+
|
|
20
|
+
await sync.checkpoint({ project: "my-app", messages: history }); // 2a
|
|
21
|
+
const ctx = await sync.pull({ project: "my-app", agent: "windsurf" }); // 2b โ 70% smaller
|
|
22
|
+
```
|
|
23
|
+
|
|
24
|
+
## What it does
|
|
25
|
+
|
|
26
|
+
StateSync is a middleware layer that gives every AI agent in your stack the same
|
|
27
|
+
long-term memory. It captures each agent's checkpoints (messages, files, decisions,
|
|
28
|
+
test results) and returns a compressed, unified brief when the next agent starts โ
|
|
29
|
+
so Windsurf can pick up exactly where Cursor left off, without re-sending 50k tokens.
|
|
30
|
+
|
|
31
|
+
Under the hood: real semantic embeddings (BAAI/bge-small-en-v1.5) + temporal
|
|
32
|
+
decay + LLM summarization โ 70โ85% smaller context on every sync.
|
|
33
|
+
|
|
34
|
+
๐ [Read the concepts guide](https://www.statesync.it/docs/concepts)
|
|
35
|
+
|
|
36
|
+
## Quickstart
|
|
37
|
+
|
|
38
|
+
Full walkthrough: **https://www.statesync.it/docs/quickstart**
|
|
39
|
+
|
|
40
|
+
### OpenAI Agents SDK pattern
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import OpenAI from "openai";
|
|
44
|
+
import { StateSync } from "@masorinho99/statesync-client";
|
|
45
|
+
|
|
46
|
+
const openai = new OpenAI();
|
|
47
|
+
const sync = new StateSync({ apiKey: process.env.STATESYNC_API_KEY });
|
|
48
|
+
|
|
49
|
+
// 1) On every turn, pull the compressed brief instead of the full history:
|
|
50
|
+
const { compressed_context } = await sync.pull({
|
|
51
|
+
project: "todo-app",
|
|
52
|
+
agent: "openai-agents",
|
|
53
|
+
query: userTurn.content,
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const messages = [
|
|
57
|
+
{ role: "system", content: compressed_context.summary },
|
|
58
|
+
...compressed_context.highlights,
|
|
59
|
+
...compressed_context.recent,
|
|
60
|
+
userTurn,
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
const resp = await openai.chat.completions.create({
|
|
64
|
+
model: "gpt-4o-mini",
|
|
65
|
+
messages,
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
// 2) After the turn, save the state so the next agent (Cursor, Claude, whatever)
|
|
69
|
+
// picks up exactly here:
|
|
70
|
+
await sync.checkpoint({
|
|
71
|
+
project: "todo-app",
|
|
72
|
+
agent: "openai-agents",
|
|
73
|
+
messages: [...messages, resp.choices[0].message],
|
|
74
|
+
files: ["src/App.tsx"],
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## API reference
|
|
79
|
+
|
|
80
|
+
Complete reference with endpoint tables, params, and response examples:
|
|
81
|
+
|
|
82
|
+
| Topic | Docs link |
|
|
83
|
+
|---|---|
|
|
84
|
+
| Projects API | https://www.statesync.it/docs/api-projects |
|
|
85
|
+
| Snapshots API | https://www.statesync.it/docs/api-snapshots |
|
|
86
|
+
| Sync & Compress | https://www.statesync.it/docs/api-sync |
|
|
87
|
+
| Analytics & Audit | https://www.statesync.it/docs/api-analytics |
|
|
88
|
+
| Rate limits & pricing | https://www.statesync.it/docs/guide-rate-limits |
|
|
89
|
+
|
|
90
|
+
Node-SDK-specific reference: **https://www.statesync.it/docs/sdk-node**
|
|
91
|
+
|
|
92
|
+
## Windsurf / Cursor / Claude Desktop (MCP)
|
|
93
|
+
|
|
94
|
+
`@masorinho99/statesync-client` is the direct HTTP SDK. If you'd rather have your editor
|
|
95
|
+
attach snapshots as native context, StateSync also runs as an MCP server โ
|
|
96
|
+
drop this into your MCP config:
|
|
97
|
+
|
|
98
|
+
```json
|
|
99
|
+
{
|
|
100
|
+
"mcpServers": {
|
|
101
|
+
"statesync": {
|
|
102
|
+
"url": "https://www.statesync.it/api/mcp",
|
|
103
|
+
"headers": { "Authorization": "Bearer ss_live_..." }
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
Full MCP integration guide: **https://www.statesync.it/docs/cursor**
|
|
110
|
+
Tools exposed: `statesync_list_projects`, `statesync_create_project`,
|
|
111
|
+
`statesync_checkpoint`, `statesync_pull`.
|
|
112
|
+
Resources exposed: `statesync://project/{id}`, `statesync://project/{id}/snapshots`,
|
|
113
|
+
`statesync://snapshot/{id}`, `statesync://audit`.
|
|
114
|
+
|
|
115
|
+
## API surface
|
|
116
|
+
|
|
117
|
+
### `new StateSync({ apiKey, baseUrl?, timeoutMs?, fetchImpl? })`
|
|
118
|
+
|
|
119
|
+
- `apiKey` โ required (or set `STATESYNC_API_KEY`).
|
|
120
|
+
- `baseUrl` โ defaults to the hosted service.
|
|
121
|
+
- `timeoutMs` โ request timeout (default 30 000).
|
|
122
|
+
- `fetchImpl` โ custom fetch (Node 18+ has global fetch).
|
|
123
|
+
|
|
124
|
+
### `sync.checkpoint({ project, messages, files?, decisions?, testsPassed?, testsFailed?, agent?, metadata? })`
|
|
125
|
+
Save an agent state snapshot. `project` accepts either a `proj_...` id or a project name
|
|
126
|
+
(auto-created on first use).
|
|
127
|
+
|
|
128
|
+
### `sync.pull({ project, agent?, query?, maxTokens? })`
|
|
129
|
+
Return the compressed unified context. See `CompressedContext` in the types.
|
|
130
|
+
|
|
131
|
+
### `sync.compress({ messages, query?, maxTokens?, projectName? })`
|
|
132
|
+
One-shot compression (no project required) โ useful to preview savings.
|
|
133
|
+
|
|
134
|
+
### `sync.listProjects()` / `sync.createProject(name, description?)`
|
|
135
|
+
|
|
136
|
+
## Get an API key
|
|
137
|
+
|
|
138
|
+
Sign up free at https://www.statesync.it โ 1,000 syncs/mo, no credit card.
|
|
139
|
+
Create a key from **Dashboard โ API Keys**.
|
|
140
|
+
|
|
141
|
+
## Links
|
|
142
|
+
|
|
143
|
+
- ๐ Documentation: https://www.statesync.it/docs
|
|
144
|
+
- ๐๏ธ Dashboard: https://www.statesync.it/dashboard
|
|
145
|
+
- ๐ OpenAPI spec: https://www.statesync.it/openapi.json
|
|
146
|
+
- ๐ฆ Sister SDK (Python): https://pypi.org/project/agent-state-api/
|
|
147
|
+
|
|
148
|
+
## License
|
|
149
|
+
|
|
150
|
+
MIT.
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/index.ts
|
|
21
|
+
var index_exports = {};
|
|
22
|
+
__export(index_exports, {
|
|
23
|
+
StateSync: () => StateSync,
|
|
24
|
+
StateSyncError: () => StateSyncError,
|
|
25
|
+
default: () => index_default
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(index_exports);
|
|
28
|
+
var DEFAULT_BASE_URL = "https://www.statesync.it/api";
|
|
29
|
+
var DEFAULT_TIMEOUT = 3e4;
|
|
30
|
+
var StateSyncError = class extends Error {
|
|
31
|
+
status;
|
|
32
|
+
payload;
|
|
33
|
+
constructor(message, status, payload) {
|
|
34
|
+
super(message);
|
|
35
|
+
this.name = "StateSyncError";
|
|
36
|
+
this.status = status;
|
|
37
|
+
this.payload = payload;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
function normaliseMessages(input) {
|
|
41
|
+
if (!input) return [];
|
|
42
|
+
return input.map((m) => ({
|
|
43
|
+
role: m.role || "user",
|
|
44
|
+
content: String(m.content ?? "")
|
|
45
|
+
}));
|
|
46
|
+
}
|
|
47
|
+
var StateSync = class {
|
|
48
|
+
apiKey;
|
|
49
|
+
baseUrl;
|
|
50
|
+
timeoutMs;
|
|
51
|
+
fetchImpl;
|
|
52
|
+
projectCache = /* @__PURE__ */ new Map();
|
|
53
|
+
constructor(opts = {}) {
|
|
54
|
+
const apiKey = opts.apiKey || (typeof process !== "undefined" ? process.env.STATESYNC_API_KEY : void 0);
|
|
55
|
+
if (!apiKey) {
|
|
56
|
+
throw new StateSyncError(
|
|
57
|
+
"Missing API key. Pass { apiKey } or set STATESYNC_API_KEY env var."
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
this.apiKey = apiKey;
|
|
61
|
+
this.baseUrl = (opts.baseUrl || (typeof process !== "undefined" ? process.env.STATESYNC_BASE_URL : void 0) || DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
62
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT;
|
|
63
|
+
if (opts.fetchImpl) {
|
|
64
|
+
this.fetchImpl = opts.fetchImpl;
|
|
65
|
+
} else if (typeof fetch !== "undefined") {
|
|
66
|
+
this.fetchImpl = fetch.bind(globalThis);
|
|
67
|
+
} else {
|
|
68
|
+
throw new StateSyncError(
|
|
69
|
+
"No fetch implementation found. Pass { fetchImpl } (e.g. node-fetch)."
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async request(method, path, body) {
|
|
74
|
+
const url = `${this.baseUrl}${path}`;
|
|
75
|
+
const controller = new AbortController();
|
|
76
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
77
|
+
let res;
|
|
78
|
+
try {
|
|
79
|
+
res = await this.fetchImpl(url, {
|
|
80
|
+
method,
|
|
81
|
+
headers: {
|
|
82
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
83
|
+
"Content-Type": "application/json",
|
|
84
|
+
"User-Agent": "@masorinho99/statesync-client/0.1.1"
|
|
85
|
+
},
|
|
86
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
87
|
+
signal: controller.signal
|
|
88
|
+
});
|
|
89
|
+
} catch (e) {
|
|
90
|
+
throw new StateSyncError(`Network error: ${e?.message || e}`);
|
|
91
|
+
} finally {
|
|
92
|
+
clearTimeout(timer);
|
|
93
|
+
}
|
|
94
|
+
if (!res.ok) {
|
|
95
|
+
let payload = void 0;
|
|
96
|
+
const text = await res.text();
|
|
97
|
+
try {
|
|
98
|
+
payload = JSON.parse(text);
|
|
99
|
+
} catch {
|
|
100
|
+
payload = text;
|
|
101
|
+
}
|
|
102
|
+
const detail = (payload && typeof payload === "object" && "detail" in payload ? payload.detail : void 0) || payload;
|
|
103
|
+
throw new StateSyncError(
|
|
104
|
+
`${res.status} ${typeof detail === "string" ? detail : JSON.stringify(detail)}`,
|
|
105
|
+
res.status,
|
|
106
|
+
payload
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
return await res.json();
|
|
110
|
+
}
|
|
111
|
+
async resolveProjectId(project) {
|
|
112
|
+
if (project.startsWith("proj_")) return project;
|
|
113
|
+
const cached = this.projectCache.get(project);
|
|
114
|
+
if (cached) return cached;
|
|
115
|
+
const items = await this.request("GET", "/projects") || [];
|
|
116
|
+
for (const p of items) {
|
|
117
|
+
if (p.name === project) {
|
|
118
|
+
this.projectCache.set(project, p.project_id);
|
|
119
|
+
return p.project_id;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const created = await this.request("POST", "/projects", {
|
|
123
|
+
name: project,
|
|
124
|
+
description: ""
|
|
125
|
+
});
|
|
126
|
+
this.projectCache.set(project, created.project_id);
|
|
127
|
+
return created.project_id;
|
|
128
|
+
}
|
|
129
|
+
/** List all projects owned by the authenticated user. */
|
|
130
|
+
listProjects() {
|
|
131
|
+
return this.request("GET", "/projects");
|
|
132
|
+
}
|
|
133
|
+
/** Create a new project explicitly (checkpoint() auto-creates by name too). */
|
|
134
|
+
createProject(name, description = "") {
|
|
135
|
+
return this.request("POST", "/projects", { name, description });
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Save an agent state snapshot to a project.
|
|
139
|
+
* `project` may be a project_id (`proj_...`) or a name (auto-created).
|
|
140
|
+
*/
|
|
141
|
+
async checkpoint(input) {
|
|
142
|
+
const projectId = await this.resolveProjectId(input.project);
|
|
143
|
+
return this.request("POST", "/snapshots", {
|
|
144
|
+
project_id: projectId,
|
|
145
|
+
agent: input.agent ?? "sdk-js",
|
|
146
|
+
messages: normaliseMessages(input.messages),
|
|
147
|
+
files_modified: input.files ?? [],
|
|
148
|
+
decisions: input.decisions ?? [],
|
|
149
|
+
tests_passed: input.testsPassed ?? [],
|
|
150
|
+
tests_failed: input.testsFailed ?? [],
|
|
151
|
+
metadata: input.metadata ?? {}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Pull the compressed unified context for a project.
|
|
156
|
+
*/
|
|
157
|
+
async pull(input) {
|
|
158
|
+
const projectId = await this.resolveProjectId(input.project);
|
|
159
|
+
return this.request("POST", "/sync", {
|
|
160
|
+
project_id: projectId,
|
|
161
|
+
agent: input.agent ?? "sdk-js",
|
|
162
|
+
query: input.query ?? "",
|
|
163
|
+
max_tokens: input.maxTokens ?? 4e3
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
/** One-shot compression (no project required) โ useful to preview savings. */
|
|
167
|
+
compress(input) {
|
|
168
|
+
return this.request("POST", "/compress", {
|
|
169
|
+
messages: normaliseMessages(input.messages),
|
|
170
|
+
query: input.query ?? "",
|
|
171
|
+
max_tokens: input.maxTokens ?? 4e3,
|
|
172
|
+
project_name: input.projectName ?? ""
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
};
|
|
176
|
+
var index_default = StateSync;
|
|
177
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
178
|
+
0 && (module.exports = {
|
|
179
|
+
StateSync,
|
|
180
|
+
StateSyncError
|
|
181
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* StateSync โ the global state database for AI coding agents.
|
|
3
|
+
*
|
|
4
|
+
* npm install @masorinho99/statesync-client
|
|
5
|
+
*
|
|
6
|
+
* import { StateSync } from "@masorinho99/statesync-client";
|
|
7
|
+
* const sync = new StateSync({ apiKey: "ss_live_..." });
|
|
8
|
+
* await sync.checkpoint({ project: "my-app", messages: history, files: ["App.js"] });
|
|
9
|
+
* const ctx = await sync.pull({ project: "my-app", agent: "windsurf" });
|
|
10
|
+
*/
|
|
11
|
+
interface StateSyncOptions {
|
|
12
|
+
/** Your StateSync API key (starts with `ss_live_`). Falls back to STATESYNC_API_KEY env var. */
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
/** Base URL โ defaults to the hosted service. */
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
/** Request timeout in milliseconds. Default 30_000. */
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
/** Custom fetch implementation (Node 18+ has global fetch). */
|
|
19
|
+
fetchImpl?: typeof fetch;
|
|
20
|
+
}
|
|
21
|
+
interface Message {
|
|
22
|
+
role: "user" | "assistant" | "system" | "tool" | string;
|
|
23
|
+
content: string;
|
|
24
|
+
}
|
|
25
|
+
interface CheckpointInput {
|
|
26
|
+
project: string;
|
|
27
|
+
messages?: (Message | {
|
|
28
|
+
role?: string;
|
|
29
|
+
content?: string;
|
|
30
|
+
})[] | undefined;
|
|
31
|
+
files?: string[];
|
|
32
|
+
decisions?: string[];
|
|
33
|
+
testsPassed?: string[];
|
|
34
|
+
testsFailed?: string[];
|
|
35
|
+
agent?: string;
|
|
36
|
+
metadata?: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
interface Snapshot {
|
|
39
|
+
snapshot_id: string;
|
|
40
|
+
project_id: string;
|
|
41
|
+
user_id: string;
|
|
42
|
+
agent: string;
|
|
43
|
+
messages: Message[];
|
|
44
|
+
files_modified: string[];
|
|
45
|
+
decisions: string[];
|
|
46
|
+
tests_passed: string[];
|
|
47
|
+
tests_failed: string[];
|
|
48
|
+
metadata: Record<string, unknown>;
|
|
49
|
+
original_tokens: number;
|
|
50
|
+
compressed_tokens: number;
|
|
51
|
+
savings_pct: number;
|
|
52
|
+
created_at: string;
|
|
53
|
+
}
|
|
54
|
+
interface CompressedContext {
|
|
55
|
+
summary: string;
|
|
56
|
+
recent: Message[];
|
|
57
|
+
highlights: Message[];
|
|
58
|
+
original_tokens: number;
|
|
59
|
+
compressed_tokens: number;
|
|
60
|
+
savings_pct: number;
|
|
61
|
+
scoring?: string;
|
|
62
|
+
}
|
|
63
|
+
interface PullResult {
|
|
64
|
+
project: {
|
|
65
|
+
project_id: string;
|
|
66
|
+
name: string;
|
|
67
|
+
description?: string;
|
|
68
|
+
created_at: string;
|
|
69
|
+
};
|
|
70
|
+
compressed_context: CompressedContext;
|
|
71
|
+
files_modified: string[];
|
|
72
|
+
decisions: string[];
|
|
73
|
+
message_count: number;
|
|
74
|
+
}
|
|
75
|
+
interface Project {
|
|
76
|
+
project_id: string;
|
|
77
|
+
user_id: string;
|
|
78
|
+
name: string;
|
|
79
|
+
description: string;
|
|
80
|
+
created_at: string;
|
|
81
|
+
snapshot_count?: number;
|
|
82
|
+
last_activity?: string;
|
|
83
|
+
}
|
|
84
|
+
interface PullInput {
|
|
85
|
+
project: string;
|
|
86
|
+
agent?: string;
|
|
87
|
+
query?: string;
|
|
88
|
+
maxTokens?: number;
|
|
89
|
+
}
|
|
90
|
+
interface CompressInput {
|
|
91
|
+
messages: (Message | {
|
|
92
|
+
role?: string;
|
|
93
|
+
content?: string;
|
|
94
|
+
})[];
|
|
95
|
+
query?: string;
|
|
96
|
+
maxTokens?: number;
|
|
97
|
+
projectName?: string;
|
|
98
|
+
}
|
|
99
|
+
declare class StateSyncError extends Error {
|
|
100
|
+
status?: number;
|
|
101
|
+
payload?: unknown;
|
|
102
|
+
constructor(message: string, status?: number, payload?: unknown);
|
|
103
|
+
}
|
|
104
|
+
declare class StateSync {
|
|
105
|
+
private apiKey;
|
|
106
|
+
private baseUrl;
|
|
107
|
+
private timeoutMs;
|
|
108
|
+
private fetchImpl;
|
|
109
|
+
private projectCache;
|
|
110
|
+
constructor(opts?: StateSyncOptions);
|
|
111
|
+
private request;
|
|
112
|
+
private resolveProjectId;
|
|
113
|
+
/** List all projects owned by the authenticated user. */
|
|
114
|
+
listProjects(): Promise<Project[]>;
|
|
115
|
+
/** Create a new project explicitly (checkpoint() auto-creates by name too). */
|
|
116
|
+
createProject(name: string, description?: string): Promise<Project>;
|
|
117
|
+
/**
|
|
118
|
+
* Save an agent state snapshot to a project.
|
|
119
|
+
* `project` may be a project_id (`proj_...`) or a name (auto-created).
|
|
120
|
+
*/
|
|
121
|
+
checkpoint(input: CheckpointInput): Promise<Snapshot>;
|
|
122
|
+
/**
|
|
123
|
+
* Pull the compressed unified context for a project.
|
|
124
|
+
*/
|
|
125
|
+
pull(input: PullInput): Promise<PullResult>;
|
|
126
|
+
/** One-shot compression (no project required) โ useful to preview savings. */
|
|
127
|
+
compress(input: CompressInput): Promise<CompressedContext>;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export { type CheckpointInput, type CompressInput, type CompressedContext, type Message, type Project, type PullInput, type PullResult, type Snapshot, StateSync, StateSyncError, type StateSyncOptions, StateSync as default };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* StateSync โ the global state database for AI coding agents.
|
|
3
|
+
*
|
|
4
|
+
* npm install @masorinho99/statesync-client
|
|
5
|
+
*
|
|
6
|
+
* import { StateSync } from "@masorinho99/statesync-client";
|
|
7
|
+
* const sync = new StateSync({ apiKey: "ss_live_..." });
|
|
8
|
+
* await sync.checkpoint({ project: "my-app", messages: history, files: ["App.js"] });
|
|
9
|
+
* const ctx = await sync.pull({ project: "my-app", agent: "windsurf" });
|
|
10
|
+
*/
|
|
11
|
+
interface StateSyncOptions {
|
|
12
|
+
/** Your StateSync API key (starts with `ss_live_`). Falls back to STATESYNC_API_KEY env var. */
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
/** Base URL โ defaults to the hosted service. */
|
|
15
|
+
baseUrl?: string;
|
|
16
|
+
/** Request timeout in milliseconds. Default 30_000. */
|
|
17
|
+
timeoutMs?: number;
|
|
18
|
+
/** Custom fetch implementation (Node 18+ has global fetch). */
|
|
19
|
+
fetchImpl?: typeof fetch;
|
|
20
|
+
}
|
|
21
|
+
interface Message {
|
|
22
|
+
role: "user" | "assistant" | "system" | "tool" | string;
|
|
23
|
+
content: string;
|
|
24
|
+
}
|
|
25
|
+
interface CheckpointInput {
|
|
26
|
+
project: string;
|
|
27
|
+
messages?: (Message | {
|
|
28
|
+
role?: string;
|
|
29
|
+
content?: string;
|
|
30
|
+
})[] | undefined;
|
|
31
|
+
files?: string[];
|
|
32
|
+
decisions?: string[];
|
|
33
|
+
testsPassed?: string[];
|
|
34
|
+
testsFailed?: string[];
|
|
35
|
+
agent?: string;
|
|
36
|
+
metadata?: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
interface Snapshot {
|
|
39
|
+
snapshot_id: string;
|
|
40
|
+
project_id: string;
|
|
41
|
+
user_id: string;
|
|
42
|
+
agent: string;
|
|
43
|
+
messages: Message[];
|
|
44
|
+
files_modified: string[];
|
|
45
|
+
decisions: string[];
|
|
46
|
+
tests_passed: string[];
|
|
47
|
+
tests_failed: string[];
|
|
48
|
+
metadata: Record<string, unknown>;
|
|
49
|
+
original_tokens: number;
|
|
50
|
+
compressed_tokens: number;
|
|
51
|
+
savings_pct: number;
|
|
52
|
+
created_at: string;
|
|
53
|
+
}
|
|
54
|
+
interface CompressedContext {
|
|
55
|
+
summary: string;
|
|
56
|
+
recent: Message[];
|
|
57
|
+
highlights: Message[];
|
|
58
|
+
original_tokens: number;
|
|
59
|
+
compressed_tokens: number;
|
|
60
|
+
savings_pct: number;
|
|
61
|
+
scoring?: string;
|
|
62
|
+
}
|
|
63
|
+
interface PullResult {
|
|
64
|
+
project: {
|
|
65
|
+
project_id: string;
|
|
66
|
+
name: string;
|
|
67
|
+
description?: string;
|
|
68
|
+
created_at: string;
|
|
69
|
+
};
|
|
70
|
+
compressed_context: CompressedContext;
|
|
71
|
+
files_modified: string[];
|
|
72
|
+
decisions: string[];
|
|
73
|
+
message_count: number;
|
|
74
|
+
}
|
|
75
|
+
interface Project {
|
|
76
|
+
project_id: string;
|
|
77
|
+
user_id: string;
|
|
78
|
+
name: string;
|
|
79
|
+
description: string;
|
|
80
|
+
created_at: string;
|
|
81
|
+
snapshot_count?: number;
|
|
82
|
+
last_activity?: string;
|
|
83
|
+
}
|
|
84
|
+
interface PullInput {
|
|
85
|
+
project: string;
|
|
86
|
+
agent?: string;
|
|
87
|
+
query?: string;
|
|
88
|
+
maxTokens?: number;
|
|
89
|
+
}
|
|
90
|
+
interface CompressInput {
|
|
91
|
+
messages: (Message | {
|
|
92
|
+
role?: string;
|
|
93
|
+
content?: string;
|
|
94
|
+
})[];
|
|
95
|
+
query?: string;
|
|
96
|
+
maxTokens?: number;
|
|
97
|
+
projectName?: string;
|
|
98
|
+
}
|
|
99
|
+
declare class StateSyncError extends Error {
|
|
100
|
+
status?: number;
|
|
101
|
+
payload?: unknown;
|
|
102
|
+
constructor(message: string, status?: number, payload?: unknown);
|
|
103
|
+
}
|
|
104
|
+
declare class StateSync {
|
|
105
|
+
private apiKey;
|
|
106
|
+
private baseUrl;
|
|
107
|
+
private timeoutMs;
|
|
108
|
+
private fetchImpl;
|
|
109
|
+
private projectCache;
|
|
110
|
+
constructor(opts?: StateSyncOptions);
|
|
111
|
+
private request;
|
|
112
|
+
private resolveProjectId;
|
|
113
|
+
/** List all projects owned by the authenticated user. */
|
|
114
|
+
listProjects(): Promise<Project[]>;
|
|
115
|
+
/** Create a new project explicitly (checkpoint() auto-creates by name too). */
|
|
116
|
+
createProject(name: string, description?: string): Promise<Project>;
|
|
117
|
+
/**
|
|
118
|
+
* Save an agent state snapshot to a project.
|
|
119
|
+
* `project` may be a project_id (`proj_...`) or a name (auto-created).
|
|
120
|
+
*/
|
|
121
|
+
checkpoint(input: CheckpointInput): Promise<Snapshot>;
|
|
122
|
+
/**
|
|
123
|
+
* Pull the compressed unified context for a project.
|
|
124
|
+
*/
|
|
125
|
+
pull(input: PullInput): Promise<PullResult>;
|
|
126
|
+
/** One-shot compression (no project required) โ useful to preview savings. */
|
|
127
|
+
compress(input: CompressInput): Promise<CompressedContext>;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export { type CheckpointInput, type CompressInput, type CompressedContext, type Message, type Project, type PullInput, type PullResult, type Snapshot, StateSync, StateSyncError, type StateSyncOptions, StateSync as default };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
var DEFAULT_BASE_URL = "https://www.statesync.it/api";
|
|
3
|
+
var DEFAULT_TIMEOUT = 3e4;
|
|
4
|
+
var StateSyncError = class extends Error {
|
|
5
|
+
status;
|
|
6
|
+
payload;
|
|
7
|
+
constructor(message, status, payload) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "StateSyncError";
|
|
10
|
+
this.status = status;
|
|
11
|
+
this.payload = payload;
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
function normaliseMessages(input) {
|
|
15
|
+
if (!input) return [];
|
|
16
|
+
return input.map((m) => ({
|
|
17
|
+
role: m.role || "user",
|
|
18
|
+
content: String(m.content ?? "")
|
|
19
|
+
}));
|
|
20
|
+
}
|
|
21
|
+
var StateSync = class {
|
|
22
|
+
apiKey;
|
|
23
|
+
baseUrl;
|
|
24
|
+
timeoutMs;
|
|
25
|
+
fetchImpl;
|
|
26
|
+
projectCache = /* @__PURE__ */ new Map();
|
|
27
|
+
constructor(opts = {}) {
|
|
28
|
+
const apiKey = opts.apiKey || (typeof process !== "undefined" ? process.env.STATESYNC_API_KEY : void 0);
|
|
29
|
+
if (!apiKey) {
|
|
30
|
+
throw new StateSyncError(
|
|
31
|
+
"Missing API key. Pass { apiKey } or set STATESYNC_API_KEY env var."
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
this.apiKey = apiKey;
|
|
35
|
+
this.baseUrl = (opts.baseUrl || (typeof process !== "undefined" ? process.env.STATESYNC_BASE_URL : void 0) || DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
36
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT;
|
|
37
|
+
if (opts.fetchImpl) {
|
|
38
|
+
this.fetchImpl = opts.fetchImpl;
|
|
39
|
+
} else if (typeof fetch !== "undefined") {
|
|
40
|
+
this.fetchImpl = fetch.bind(globalThis);
|
|
41
|
+
} else {
|
|
42
|
+
throw new StateSyncError(
|
|
43
|
+
"No fetch implementation found. Pass { fetchImpl } (e.g. node-fetch)."
|
|
44
|
+
);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
async request(method, path, body) {
|
|
48
|
+
const url = `${this.baseUrl}${path}`;
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
51
|
+
let res;
|
|
52
|
+
try {
|
|
53
|
+
res = await this.fetchImpl(url, {
|
|
54
|
+
method,
|
|
55
|
+
headers: {
|
|
56
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
57
|
+
"Content-Type": "application/json",
|
|
58
|
+
"User-Agent": "@masorinho99/statesync-client/0.1.1"
|
|
59
|
+
},
|
|
60
|
+
body: body === void 0 ? void 0 : JSON.stringify(body),
|
|
61
|
+
signal: controller.signal
|
|
62
|
+
});
|
|
63
|
+
} catch (e) {
|
|
64
|
+
throw new StateSyncError(`Network error: ${e?.message || e}`);
|
|
65
|
+
} finally {
|
|
66
|
+
clearTimeout(timer);
|
|
67
|
+
}
|
|
68
|
+
if (!res.ok) {
|
|
69
|
+
let payload = void 0;
|
|
70
|
+
const text = await res.text();
|
|
71
|
+
try {
|
|
72
|
+
payload = JSON.parse(text);
|
|
73
|
+
} catch {
|
|
74
|
+
payload = text;
|
|
75
|
+
}
|
|
76
|
+
const detail = (payload && typeof payload === "object" && "detail" in payload ? payload.detail : void 0) || payload;
|
|
77
|
+
throw new StateSyncError(
|
|
78
|
+
`${res.status} ${typeof detail === "string" ? detail : JSON.stringify(detail)}`,
|
|
79
|
+
res.status,
|
|
80
|
+
payload
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
return await res.json();
|
|
84
|
+
}
|
|
85
|
+
async resolveProjectId(project) {
|
|
86
|
+
if (project.startsWith("proj_")) return project;
|
|
87
|
+
const cached = this.projectCache.get(project);
|
|
88
|
+
if (cached) return cached;
|
|
89
|
+
const items = await this.request("GET", "/projects") || [];
|
|
90
|
+
for (const p of items) {
|
|
91
|
+
if (p.name === project) {
|
|
92
|
+
this.projectCache.set(project, p.project_id);
|
|
93
|
+
return p.project_id;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const created = await this.request("POST", "/projects", {
|
|
97
|
+
name: project,
|
|
98
|
+
description: ""
|
|
99
|
+
});
|
|
100
|
+
this.projectCache.set(project, created.project_id);
|
|
101
|
+
return created.project_id;
|
|
102
|
+
}
|
|
103
|
+
/** List all projects owned by the authenticated user. */
|
|
104
|
+
listProjects() {
|
|
105
|
+
return this.request("GET", "/projects");
|
|
106
|
+
}
|
|
107
|
+
/** Create a new project explicitly (checkpoint() auto-creates by name too). */
|
|
108
|
+
createProject(name, description = "") {
|
|
109
|
+
return this.request("POST", "/projects", { name, description });
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Save an agent state snapshot to a project.
|
|
113
|
+
* `project` may be a project_id (`proj_...`) or a name (auto-created).
|
|
114
|
+
*/
|
|
115
|
+
async checkpoint(input) {
|
|
116
|
+
const projectId = await this.resolveProjectId(input.project);
|
|
117
|
+
return this.request("POST", "/snapshots", {
|
|
118
|
+
project_id: projectId,
|
|
119
|
+
agent: input.agent ?? "sdk-js",
|
|
120
|
+
messages: normaliseMessages(input.messages),
|
|
121
|
+
files_modified: input.files ?? [],
|
|
122
|
+
decisions: input.decisions ?? [],
|
|
123
|
+
tests_passed: input.testsPassed ?? [],
|
|
124
|
+
tests_failed: input.testsFailed ?? [],
|
|
125
|
+
metadata: input.metadata ?? {}
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* Pull the compressed unified context for a project.
|
|
130
|
+
*/
|
|
131
|
+
async pull(input) {
|
|
132
|
+
const projectId = await this.resolveProjectId(input.project);
|
|
133
|
+
return this.request("POST", "/sync", {
|
|
134
|
+
project_id: projectId,
|
|
135
|
+
agent: input.agent ?? "sdk-js",
|
|
136
|
+
query: input.query ?? "",
|
|
137
|
+
max_tokens: input.maxTokens ?? 4e3
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
/** One-shot compression (no project required) โ useful to preview savings. */
|
|
141
|
+
compress(input) {
|
|
142
|
+
return this.request("POST", "/compress", {
|
|
143
|
+
messages: normaliseMessages(input.messages),
|
|
144
|
+
query: input.query ?? "",
|
|
145
|
+
max_tokens: input.maxTokens ?? 4e3,
|
|
146
|
+
project_name: input.projectName ?? ""
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
var index_default = StateSync;
|
|
151
|
+
export {
|
|
152
|
+
StateSync,
|
|
153
|
+
StateSyncError,
|
|
154
|
+
index_default as default
|
|
155
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@masorinho99/statesync-client",
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "StateSync \u2014 the global state database for AI agents. Two-line SDK to unify memory across Cursor, Claude, OpenAI and Emergent.",
|
|
5
|
+
"main": "dist/index.cjs",
|
|
6
|
+
"module": "dist/index.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"type": "module",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"import": "./dist/index.js",
|
|
13
|
+
"require": "./dist/index.cjs"
|
|
14
|
+
}
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"src",
|
|
19
|
+
"README.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"scripts": {
|
|
23
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean",
|
|
24
|
+
"test": "node --test test/*.test.mjs",
|
|
25
|
+
"prepublishOnly": "npm run build"
|
|
26
|
+
},
|
|
27
|
+
"keywords": [
|
|
28
|
+
"ai",
|
|
29
|
+
"agents",
|
|
30
|
+
"llm",
|
|
31
|
+
"mcp",
|
|
32
|
+
"context",
|
|
33
|
+
"compression",
|
|
34
|
+
"cursor",
|
|
35
|
+
"claude",
|
|
36
|
+
"openai",
|
|
37
|
+
"state-management"
|
|
38
|
+
],
|
|
39
|
+
"author": "StateSync",
|
|
40
|
+
"license": "MIT",
|
|
41
|
+
"repository": {
|
|
42
|
+
"type": "git",
|
|
43
|
+
"url": "https://github.com/statesync/client-js"
|
|
44
|
+
},
|
|
45
|
+
"homepage": "https://www.statesync.it/docs",
|
|
46
|
+
"bugs": {
|
|
47
|
+
"url": "https://www.statesync.it/docs"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@types/node": "^26.1.1",
|
|
51
|
+
"tsup": "^8.0.0",
|
|
52
|
+
"typescript": "^5.4.0"
|
|
53
|
+
},
|
|
54
|
+
"engines": {
|
|
55
|
+
"node": ">=18"
|
|
56
|
+
}
|
|
57
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* StateSync โ the global state database for AI coding agents.
|
|
3
|
+
*
|
|
4
|
+
* npm install @masorinho99/statesync-client
|
|
5
|
+
*
|
|
6
|
+
* import { StateSync } from "@masorinho99/statesync-client";
|
|
7
|
+
* const sync = new StateSync({ apiKey: "ss_live_..." });
|
|
8
|
+
* await sync.checkpoint({ project: "my-app", messages: history, files: ["App.js"] });
|
|
9
|
+
* const ctx = await sync.pull({ project: "my-app", agent: "windsurf" });
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
export interface StateSyncOptions {
|
|
13
|
+
/** Your StateSync API key (starts with `ss_live_`). Falls back to STATESYNC_API_KEY env var. */
|
|
14
|
+
apiKey?: string;
|
|
15
|
+
/** Base URL โ defaults to the hosted service. */
|
|
16
|
+
baseUrl?: string;
|
|
17
|
+
/** Request timeout in milliseconds. Default 30_000. */
|
|
18
|
+
timeoutMs?: number;
|
|
19
|
+
/** Custom fetch implementation (Node 18+ has global fetch). */
|
|
20
|
+
fetchImpl?: typeof fetch;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface Message {
|
|
24
|
+
role: "user" | "assistant" | "system" | "tool" | string;
|
|
25
|
+
content: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface CheckpointInput {
|
|
29
|
+
project: string;
|
|
30
|
+
messages?: (Message | { role?: string; content?: string })[] | undefined;
|
|
31
|
+
files?: string[];
|
|
32
|
+
decisions?: string[];
|
|
33
|
+
testsPassed?: string[];
|
|
34
|
+
testsFailed?: string[];
|
|
35
|
+
agent?: string;
|
|
36
|
+
metadata?: Record<string, unknown>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface Snapshot {
|
|
40
|
+
snapshot_id: string;
|
|
41
|
+
project_id: string;
|
|
42
|
+
user_id: string;
|
|
43
|
+
agent: string;
|
|
44
|
+
messages: Message[];
|
|
45
|
+
files_modified: string[];
|
|
46
|
+
decisions: string[];
|
|
47
|
+
tests_passed: string[];
|
|
48
|
+
tests_failed: string[];
|
|
49
|
+
metadata: Record<string, unknown>;
|
|
50
|
+
original_tokens: number;
|
|
51
|
+
compressed_tokens: number;
|
|
52
|
+
savings_pct: number;
|
|
53
|
+
created_at: string;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface CompressedContext {
|
|
57
|
+
summary: string;
|
|
58
|
+
recent: Message[];
|
|
59
|
+
highlights: Message[];
|
|
60
|
+
original_tokens: number;
|
|
61
|
+
compressed_tokens: number;
|
|
62
|
+
savings_pct: number;
|
|
63
|
+
scoring?: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface PullResult {
|
|
67
|
+
project: {
|
|
68
|
+
project_id: string;
|
|
69
|
+
name: string;
|
|
70
|
+
description?: string;
|
|
71
|
+
created_at: string;
|
|
72
|
+
};
|
|
73
|
+
compressed_context: CompressedContext;
|
|
74
|
+
files_modified: string[];
|
|
75
|
+
decisions: string[];
|
|
76
|
+
message_count: number;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface Project {
|
|
80
|
+
project_id: string;
|
|
81
|
+
user_id: string;
|
|
82
|
+
name: string;
|
|
83
|
+
description: string;
|
|
84
|
+
created_at: string;
|
|
85
|
+
snapshot_count?: number;
|
|
86
|
+
last_activity?: string;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface PullInput {
|
|
90
|
+
project: string;
|
|
91
|
+
agent?: string;
|
|
92
|
+
query?: string;
|
|
93
|
+
maxTokens?: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export interface CompressInput {
|
|
97
|
+
messages: (Message | { role?: string; content?: string })[];
|
|
98
|
+
query?: string;
|
|
99
|
+
maxTokens?: number;
|
|
100
|
+
projectName?: string;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const DEFAULT_BASE_URL = "https://www.statesync.it/api";
|
|
104
|
+
const DEFAULT_TIMEOUT = 30_000;
|
|
105
|
+
|
|
106
|
+
export class StateSyncError extends Error {
|
|
107
|
+
status?: number;
|
|
108
|
+
payload?: unknown;
|
|
109
|
+
constructor(message: string, status?: number, payload?: unknown) {
|
|
110
|
+
super(message);
|
|
111
|
+
this.name = "StateSyncError";
|
|
112
|
+
this.status = status;
|
|
113
|
+
this.payload = payload;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function normaliseMessages(
|
|
118
|
+
input?: (Message | { role?: string; content?: string })[]
|
|
119
|
+
): Message[] {
|
|
120
|
+
if (!input) return [];
|
|
121
|
+
return input.map((m) => ({
|
|
122
|
+
role: (m.role as string) || "user",
|
|
123
|
+
content: String(m.content ?? ""),
|
|
124
|
+
}));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export class StateSync {
|
|
128
|
+
private apiKey: string;
|
|
129
|
+
private baseUrl: string;
|
|
130
|
+
private timeoutMs: number;
|
|
131
|
+
private fetchImpl: typeof fetch;
|
|
132
|
+
private projectCache = new Map<string, string>();
|
|
133
|
+
|
|
134
|
+
constructor(opts: StateSyncOptions = {}) {
|
|
135
|
+
const apiKey =
|
|
136
|
+
opts.apiKey ||
|
|
137
|
+
(typeof process !== "undefined" ? process.env.STATESYNC_API_KEY : undefined);
|
|
138
|
+
if (!apiKey) {
|
|
139
|
+
throw new StateSyncError(
|
|
140
|
+
"Missing API key. Pass { apiKey } or set STATESYNC_API_KEY env var."
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
this.apiKey = apiKey;
|
|
144
|
+
this.baseUrl = (
|
|
145
|
+
opts.baseUrl ||
|
|
146
|
+
(typeof process !== "undefined" ? process.env.STATESYNC_BASE_URL : undefined) ||
|
|
147
|
+
DEFAULT_BASE_URL
|
|
148
|
+
).replace(/\/$/, "");
|
|
149
|
+
this.timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT;
|
|
150
|
+
if (opts.fetchImpl) {
|
|
151
|
+
this.fetchImpl = opts.fetchImpl;
|
|
152
|
+
} else if (typeof fetch !== "undefined") {
|
|
153
|
+
this.fetchImpl = fetch.bind(globalThis);
|
|
154
|
+
} else {
|
|
155
|
+
throw new StateSyncError(
|
|
156
|
+
"No fetch implementation found. Pass { fetchImpl } (e.g. node-fetch)."
|
|
157
|
+
);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
private async request<T = unknown>(
|
|
162
|
+
method: string,
|
|
163
|
+
path: string,
|
|
164
|
+
body?: unknown
|
|
165
|
+
): Promise<T> {
|
|
166
|
+
const url = `${this.baseUrl}${path}`;
|
|
167
|
+
const controller = new AbortController();
|
|
168
|
+
const timer = setTimeout(() => controller.abort(), this.timeoutMs);
|
|
169
|
+
let res: Response;
|
|
170
|
+
try {
|
|
171
|
+
res = await this.fetchImpl(url, {
|
|
172
|
+
method,
|
|
173
|
+
headers: {
|
|
174
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
175
|
+
"Content-Type": "application/json",
|
|
176
|
+
"User-Agent": "@masorinho99/statesync-client/0.1.1",
|
|
177
|
+
},
|
|
178
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
179
|
+
signal: controller.signal,
|
|
180
|
+
});
|
|
181
|
+
} catch (e: any) {
|
|
182
|
+
throw new StateSyncError(`Network error: ${e?.message || e}`);
|
|
183
|
+
} finally {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
}
|
|
186
|
+
if (!res.ok) {
|
|
187
|
+
let payload: unknown = undefined;
|
|
188
|
+
const text = await res.text();
|
|
189
|
+
try {
|
|
190
|
+
payload = JSON.parse(text);
|
|
191
|
+
} catch {
|
|
192
|
+
payload = text;
|
|
193
|
+
}
|
|
194
|
+
const detail =
|
|
195
|
+
(payload && typeof payload === "object" && "detail" in payload
|
|
196
|
+
? (payload as any).detail
|
|
197
|
+
: undefined) || payload;
|
|
198
|
+
throw new StateSyncError(
|
|
199
|
+
`${res.status} ${typeof detail === "string" ? detail : JSON.stringify(detail)}`,
|
|
200
|
+
res.status,
|
|
201
|
+
payload
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
return (await res.json()) as T;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
private async resolveProjectId(project: string): Promise<string> {
|
|
208
|
+
if (project.startsWith("proj_")) return project;
|
|
209
|
+
const cached = this.projectCache.get(project);
|
|
210
|
+
if (cached) return cached;
|
|
211
|
+
const items = (await this.request<Project[]>("GET", "/projects")) || [];
|
|
212
|
+
for (const p of items) {
|
|
213
|
+
if (p.name === project) {
|
|
214
|
+
this.projectCache.set(project, p.project_id);
|
|
215
|
+
return p.project_id;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
const created = await this.request<Project>("POST", "/projects", {
|
|
219
|
+
name: project,
|
|
220
|
+
description: "",
|
|
221
|
+
});
|
|
222
|
+
this.projectCache.set(project, created.project_id);
|
|
223
|
+
return created.project_id;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** List all projects owned by the authenticated user. */
|
|
227
|
+
listProjects(): Promise<Project[]> {
|
|
228
|
+
return this.request<Project[]>("GET", "/projects");
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/** Create a new project explicitly (checkpoint() auto-creates by name too). */
|
|
232
|
+
createProject(name: string, description = ""): Promise<Project> {
|
|
233
|
+
return this.request<Project>("POST", "/projects", { name, description });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Save an agent state snapshot to a project.
|
|
238
|
+
* `project` may be a project_id (`proj_...`) or a name (auto-created).
|
|
239
|
+
*/
|
|
240
|
+
async checkpoint(input: CheckpointInput): Promise<Snapshot> {
|
|
241
|
+
const projectId = await this.resolveProjectId(input.project);
|
|
242
|
+
return this.request<Snapshot>("POST", "/snapshots", {
|
|
243
|
+
project_id: projectId,
|
|
244
|
+
agent: input.agent ?? "sdk-js",
|
|
245
|
+
messages: normaliseMessages(input.messages),
|
|
246
|
+
files_modified: input.files ?? [],
|
|
247
|
+
decisions: input.decisions ?? [],
|
|
248
|
+
tests_passed: input.testsPassed ?? [],
|
|
249
|
+
tests_failed: input.testsFailed ?? [],
|
|
250
|
+
metadata: input.metadata ?? {},
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Pull the compressed unified context for a project.
|
|
256
|
+
*/
|
|
257
|
+
async pull(input: PullInput): Promise<PullResult> {
|
|
258
|
+
const projectId = await this.resolveProjectId(input.project);
|
|
259
|
+
return this.request<PullResult>("POST", "/sync", {
|
|
260
|
+
project_id: projectId,
|
|
261
|
+
agent: input.agent ?? "sdk-js",
|
|
262
|
+
query: input.query ?? "",
|
|
263
|
+
max_tokens: input.maxTokens ?? 4000,
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** One-shot compression (no project required) โ useful to preview savings. */
|
|
268
|
+
compress(input: CompressInput): Promise<CompressedContext> {
|
|
269
|
+
return this.request<CompressedContext>("POST", "/compress", {
|
|
270
|
+
messages: normaliseMessages(input.messages),
|
|
271
|
+
query: input.query ?? "",
|
|
272
|
+
max_tokens: input.maxTokens ?? 4000,
|
|
273
|
+
project_name: input.projectName ?? "",
|
|
274
|
+
});
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
export default StateSync;
|