@personize/sdk 0.2.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/dist/client.js ADDED
@@ -0,0 +1,318 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Personize = void 0;
7
+ const axios_1 = __importDefault(require("axios"));
8
+ const errors_1 = require("./errors");
9
+ class Personize {
10
+ constructor(config) {
11
+ this.variables = {
12
+ /**
13
+ * GET /api/v1/variables — List variables for the organization (paginated).
14
+ * Pass `limit` and `nextToken` for cursor-based pagination.
15
+ */
16
+ list: async (options) => {
17
+ const params = {};
18
+ if (options?.limit != null)
19
+ params.limit = String(options.limit);
20
+ if (options?.nextToken)
21
+ params.nextToken = options.nextToken;
22
+ if (options?.summary)
23
+ params.summary = 'true';
24
+ if (options?.tags)
25
+ params.tags = Array.isArray(options.tags) ? options.tags.join(',') : options.tags;
26
+ if (options?.excludeTags)
27
+ params.excludeTags = Array.isArray(options.excludeTags) ? options.excludeTags.join(',') : options.excludeTags;
28
+ const response = await this.client.get('/api/v1/variables', { params });
29
+ return response.data;
30
+ },
31
+ /**
32
+ * GET /api/v1/variables/:id/structure — Get variable headings
33
+ */
34
+ getStructure: async (id) => {
35
+ const response = await this.client.get(`/api/v1/variables/${id}/structure`);
36
+ return response.data;
37
+ },
38
+ /**
39
+ * GET /api/v1/variables/:id/section — Get a section of a variable by header
40
+ */
41
+ getSection: async (id, options) => {
42
+ const response = await this.client.get(`/api/v1/variables/${id}/section`, {
43
+ params: { header: options.header },
44
+ });
45
+ return response.data;
46
+ },
47
+ /**
48
+ * PATCH /api/v1/variables/:id — Partial update to a variable
49
+ */
50
+ update: async (id, payload) => {
51
+ const organizationId = await this.getOrganizationId();
52
+ const { historyNote, ...rest } = payload;
53
+ const response = await this.client.patch(`/api/v1/variables/${id}`, {
54
+ organizationId,
55
+ historyNote,
56
+ payload: rest,
57
+ });
58
+ return response.data;
59
+ },
60
+ /**
61
+ * POST /api/v1/variables — Create a new variable
62
+ */
63
+ create: async (payload) => {
64
+ const response = await this.client.post('/api/v1/variables', payload);
65
+ return response.data;
66
+ },
67
+ /**
68
+ * DELETE /api/v1/variables/:id — Delete a variable
69
+ */
70
+ delete: async (id) => {
71
+ const response = await this.client.delete(`/api/v1/variables/${id}`);
72
+ return response.data;
73
+ },
74
+ /**
75
+ * GET /api/v1/actions/:id/history — Get version history for a variable
76
+ */
77
+ history: async (id, options) => {
78
+ const organizationId = await this.getOrganizationId();
79
+ const response = await this.client.get(`/api/v1/actions/${id}/history`, {
80
+ params: { organizationId, limit: options?.limit },
81
+ });
82
+ return response.data;
83
+ },
84
+ };
85
+ this.collections = {
86
+ /**
87
+ * GET /api/v1/collections — List property collections (paginated).
88
+ * Pass `limit` and `nextToken` for cursor-based pagination.
89
+ */
90
+ list: async (options) => {
91
+ const params = {};
92
+ if (options?.limit != null)
93
+ params.limit = String(options.limit);
94
+ if (options?.nextToken)
95
+ params.nextToken = options.nextToken;
96
+ if (options?.summary)
97
+ params.summary = 'true';
98
+ if (options?.tags)
99
+ params.tags = Array.isArray(options.tags) ? options.tags.join(',') : options.tags;
100
+ if (options?.excludeTags)
101
+ params.excludeTags = Array.isArray(options.excludeTags) ? options.excludeTags.join(',') : options.excludeTags;
102
+ const response = await this.client.get('/api/v1/collections', { params });
103
+ return response.data;
104
+ },
105
+ /**
106
+ * POST /api/v1/collections — Create a new property collection
107
+ */
108
+ create: async (payload) => {
109
+ const response = await this.client.post('/api/v1/collections', payload);
110
+ return response.data;
111
+ },
112
+ /**
113
+ * PATCH /api/v1/collections/:id — Update a property collection (smart merge for properties array)
114
+ */
115
+ update: async (id, payload) => {
116
+ const organizationId = await this.getOrganizationId();
117
+ const response = await this.client.patch(`/api/v1/collections/${id}`, {
118
+ organizationId,
119
+ payload,
120
+ });
121
+ return response.data;
122
+ },
123
+ /**
124
+ * DELETE /api/v1/collections/:id — Delete a property collection
125
+ */
126
+ delete: async (id) => {
127
+ const response = await this.client.delete(`/api/v1/collections/${id}`);
128
+ return response.data;
129
+ },
130
+ /**
131
+ * GET /api/v1/collections/:id/history — Version history for a collection.
132
+ * Use mode='diff' for token-efficient diffs (~80% fewer tokens than full snapshots).
133
+ */
134
+ history: async (id, options) => {
135
+ const organizationId = await this.getOrganizationId();
136
+ const response = await this.client.get(`/api/v1/collections/${id}/history`, {
137
+ params: { organizationId, limit: options?.limit, mode: options?.mode },
138
+ });
139
+ return response.data;
140
+ },
141
+ };
142
+ this.ai = {
143
+ /**
144
+ * POST /api/v1/ai/smart-context — Semantic context routing
145
+ */
146
+ smartContext: async (options) => {
147
+ const response = await this.client.post('/api/v1/ai/smart-context', options);
148
+ return response.data;
149
+ },
150
+ /**
151
+ * POST /api/v1/prompt — Execute a prompt with tools, output extraction, and evaluation.
152
+ *
153
+ * Supports simple mode (single prompt) and advanced mode (multi-step instructions).
154
+ * Use `outputs` for server-side structured output extraction via `<output>` markers.
155
+ * Use `evaluate` for server-side auto-evaluation.
156
+ * Use `memorize` to auto-save outputs and tool results to memory.
157
+ */
158
+ prompt: async (options) => {
159
+ const response = await this.client.post('/api/v1/prompt', options);
160
+ return response.data;
161
+ },
162
+ };
163
+ this.agents = {
164
+ /**
165
+ * GET /api/v1/agents — List available agents (paginated).
166
+ * Pass `limit` and `nextToken` for cursor-based pagination.
167
+ */
168
+ list: async (options) => {
169
+ const params = {};
170
+ if (options?.limit != null)
171
+ params.limit = String(options.limit);
172
+ if (options?.nextToken)
173
+ params.nextToken = options.nextToken;
174
+ if (options?.summary)
175
+ params.summary = 'true';
176
+ if (options?.tags)
177
+ params.tags = Array.isArray(options.tags) ? options.tags.join(',') : options.tags;
178
+ if (options?.excludeTags)
179
+ params.excludeTags = Array.isArray(options.excludeTags) ? options.excludeTags.join(',') : options.excludeTags;
180
+ const response = await this.client.get('/api/v1/agents', { params });
181
+ return response.data;
182
+ },
183
+ /**
184
+ * POST /api/v1/agents/:id/run — Run an agent
185
+ */
186
+ run: async (id, options) => {
187
+ const response = await this.client.post(`/api/v1/agents/${id}/run`, options || {});
188
+ return response.data;
189
+ },
190
+ };
191
+ this.memory = {
192
+ /**
193
+ * POST /api/v1/memorize_pro — Advanced memorization (RAG)
194
+ */
195
+ memorize: async (data) => {
196
+ const response = await this.client.post('/api/v1/memorize_pro', data);
197
+ return response.data;
198
+ },
199
+ /**
200
+ * POST /api/v1/recall_pro — Advanced recall with reflection (RAG)
201
+ */
202
+ recall: async (data) => {
203
+ const response = await this.client.post('/api/v1/recall_pro', data);
204
+ return response.data;
205
+ },
206
+ /**
207
+ * POST /api/v1/export — Filter and export records
208
+ */
209
+ export: async (data) => {
210
+ const response = await this.client.post('/api/v1/export', data);
211
+ return response.data;
212
+ },
213
+ /**
214
+ * POST /api/v1/upsert — Structured upsert (no AI extraction)
215
+ */
216
+ upsert: async (data) => {
217
+ const organizationId = await this.getOrganizationId();
218
+ const response = await this.client.post('/api/v1/upsert', {
219
+ ...data,
220
+ orgId: organizationId,
221
+ });
222
+ return response.data;
223
+ },
224
+ /**
225
+ * POST /api/v1/upsert — Batch upsert (memories array format)
226
+ */
227
+ upsertBatch: async (data) => {
228
+ const organizationId = await this.getOrganizationId();
229
+ const response = await this.client.post('/api/v1/upsert', {
230
+ ...data,
231
+ orgId: organizationId,
232
+ });
233
+ return response.data;
234
+ },
235
+ /**
236
+ * POST /api/v1/batch-memorize — Unified batch sync with per-property extractMemories flag.
237
+ * Properties with extractMemories: true go through AI extraction + vectors.
238
+ * Properties without it (or false) are stored as structured data only.
239
+ */
240
+ memorizeBatch: async (data) => {
241
+ const { organizationId, userId } = await this.resolveIdentity();
242
+ const response = await this.client.post('/api/v1/batch-memorize', {
243
+ ...data,
244
+ orgId: organizationId,
245
+ userId,
246
+ });
247
+ return response.data;
248
+ },
249
+ /**
250
+ * POST /api/v1/smart-memory-digest — Get compiled context bundle for an entity.
251
+ * Combines DynamoDB properties + LanceDB memories into a token-budgeted markdown block.
252
+ */
253
+ smartDigest: async (data) => {
254
+ const response = await this.client.post('/api/v1/smart-memory-digest', data);
255
+ return response.data;
256
+ },
257
+ };
258
+ this.maxRetries = config.maxRetries ?? 3;
259
+ this.retryDelay = config.retryDelay ?? 1000;
260
+ this.client = axios_1.default.create({
261
+ baseURL: config.baseURL || 'https://api.personize.ai',
262
+ timeout: config.timeout ?? 30000,
263
+ headers: {
264
+ 'Authorization': `Bearer ${config.secretKey}`,
265
+ 'Content-Type': 'application/json',
266
+ },
267
+ });
268
+ this.client.interceptors.response.use((response) => response, async (error) => {
269
+ const reqConfig = error.config;
270
+ if (!reqConfig)
271
+ throw (0, errors_1.toPersonizeError)(error);
272
+ const retryCount = reqConfig._retryCount ?? 0;
273
+ const status = error.response?.status;
274
+ const isRetryable = status === 429 || (status !== undefined && status >= 500);
275
+ if (isRetryable && retryCount < this.maxRetries) {
276
+ reqConfig._retryCount = retryCount + 1;
277
+ let delay;
278
+ if (status === 429) {
279
+ const body = error.response?.data;
280
+ const retryAfter = body?.retryAfterSeconds || 0;
281
+ delay = retryAfter > 0
282
+ ? retryAfter * 1000
283
+ : this.retryDelay * Math.pow(2, retryCount);
284
+ }
285
+ else {
286
+ delay = this.retryDelay * Math.pow(2, retryCount);
287
+ }
288
+ await new Promise(resolve => setTimeout(resolve, delay));
289
+ return this.client.request(reqConfig);
290
+ }
291
+ throw (0, errors_1.toPersonizeError)(error);
292
+ });
293
+ }
294
+ async resolveIdentity() {
295
+ if (!this._organizationId || !this._userId) {
296
+ const me = await this.me();
297
+ this._organizationId = me.data?.organization?.id;
298
+ this._userId = me.data?.user?.id;
299
+ }
300
+ if (!this._organizationId)
301
+ throw new Error('Could not resolve organizationId from API key');
302
+ if (!this._userId)
303
+ throw new Error('Could not resolve userId from API key');
304
+ return { organizationId: this._organizationId, userId: this._userId };
305
+ }
306
+ async getOrganizationId() {
307
+ const { organizationId } = await this.resolveIdentity();
308
+ return organizationId;
309
+ }
310
+ /**
311
+ * GET /api/v1/me — Current context (org, user, plan)
312
+ */
313
+ async me() {
314
+ const response = await this.client.get('/api/v1/me');
315
+ return response.data;
316
+ }
317
+ }
318
+ exports.Personize = Personize;
@@ -0,0 +1,58 @@
1
+ import { AxiosError } from 'axios';
2
+ /**
3
+ * Base error class for all Personize SDK errors.
4
+ */
5
+ export declare class PersonizeError extends Error {
6
+ readonly status?: number;
7
+ readonly endpoint?: string;
8
+ readonly method?: string;
9
+ readonly cause?: AxiosError;
10
+ constructor(message: string, options?: {
11
+ status?: number;
12
+ endpoint?: string;
13
+ method?: string;
14
+ cause?: AxiosError;
15
+ });
16
+ }
17
+ /**
18
+ * Thrown when the API returns 401 (invalid/expired API key).
19
+ */
20
+ export declare class AuthenticationError extends PersonizeError {
21
+ constructor(message: string, options?: {
22
+ endpoint?: string;
23
+ method?: string;
24
+ cause?: AxiosError;
25
+ });
26
+ }
27
+ /**
28
+ * Thrown when the API returns 429 (rate limit exceeded).
29
+ */
30
+ export declare class RateLimitExceededError extends PersonizeError {
31
+ readonly limit?: number;
32
+ readonly current?: number;
33
+ readonly window?: 'per_minute' | 'per_month';
34
+ readonly retryAfterSeconds?: number;
35
+ constructor(message: string, options?: {
36
+ endpoint?: string;
37
+ method?: string;
38
+ cause?: AxiosError;
39
+ limit?: number;
40
+ current?: number;
41
+ window?: 'per_minute' | 'per_month';
42
+ retryAfterSeconds?: number;
43
+ });
44
+ }
45
+ /**
46
+ * Thrown when a request times out.
47
+ */
48
+ export declare class TimeoutError extends PersonizeError {
49
+ constructor(message: string, options?: {
50
+ endpoint?: string;
51
+ method?: string;
52
+ cause?: AxiosError;
53
+ });
54
+ }
55
+ /**
56
+ * Converts an AxiosError into the appropriate PersonizeError subclass.
57
+ */
58
+ export declare function toPersonizeError(error: AxiosError): PersonizeError;
package/dist/errors.js ADDED
@@ -0,0 +1,86 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TimeoutError = exports.RateLimitExceededError = exports.AuthenticationError = exports.PersonizeError = void 0;
4
+ exports.toPersonizeError = toPersonizeError;
5
+ /**
6
+ * Base error class for all Personize SDK errors.
7
+ */
8
+ class PersonizeError extends Error {
9
+ constructor(message, options) {
10
+ super(message);
11
+ this.name = 'PersonizeError';
12
+ this.status = options?.status;
13
+ this.endpoint = options?.endpoint;
14
+ this.method = options?.method;
15
+ this.cause = options?.cause;
16
+ Object.setPrototypeOf(this, new.target.prototype);
17
+ }
18
+ }
19
+ exports.PersonizeError = PersonizeError;
20
+ /**
21
+ * Thrown when the API returns 401 (invalid/expired API key).
22
+ */
23
+ class AuthenticationError extends PersonizeError {
24
+ constructor(message, options) {
25
+ super(message, { ...options, status: 401 });
26
+ this.name = 'AuthenticationError';
27
+ }
28
+ }
29
+ exports.AuthenticationError = AuthenticationError;
30
+ /**
31
+ * Thrown when the API returns 429 (rate limit exceeded).
32
+ */
33
+ class RateLimitExceededError extends PersonizeError {
34
+ constructor(message, options) {
35
+ super(message, { ...options, status: 429 });
36
+ this.name = 'RateLimitExceededError';
37
+ this.limit = options?.limit;
38
+ this.current = options?.current;
39
+ this.window = options?.window;
40
+ this.retryAfterSeconds = options?.retryAfterSeconds;
41
+ }
42
+ }
43
+ exports.RateLimitExceededError = RateLimitExceededError;
44
+ /**
45
+ * Thrown when a request times out.
46
+ */
47
+ class TimeoutError extends PersonizeError {
48
+ constructor(message, options) {
49
+ super(message, { ...options, status: undefined });
50
+ this.name = 'TimeoutError';
51
+ }
52
+ }
53
+ exports.TimeoutError = TimeoutError;
54
+ /**
55
+ * Converts an AxiosError into the appropriate PersonizeError subclass.
56
+ */
57
+ function toPersonizeError(error) {
58
+ const endpoint = error.config?.url;
59
+ const method = error.config?.method?.toUpperCase();
60
+ const status = error.response?.status;
61
+ const body = error.response?.data;
62
+ if (error.code === 'ECONNABORTED' || error.code === 'ETIMEDOUT') {
63
+ return new TimeoutError(`Request timed out: ${method} ${endpoint}`, { endpoint, method, cause: error });
64
+ }
65
+ if (status === 401) {
66
+ return new AuthenticationError(body?.message || 'Invalid or expired API key', { endpoint, method, cause: error });
67
+ }
68
+ if (status === 429) {
69
+ return new RateLimitExceededError(body?.message || 'Rate limit exceeded', {
70
+ endpoint,
71
+ method,
72
+ cause: error,
73
+ limit: body?.limit,
74
+ current: body?.current,
75
+ window: body?.window,
76
+ retryAfterSeconds: body?.retryAfterSeconds,
77
+ });
78
+ }
79
+ if (!error.response) {
80
+ return new PersonizeError(`Network error: ${error.message}`, { endpoint, method, cause: error });
81
+ }
82
+ const message = body?.message
83
+ || body?.error
84
+ || `Request failed with status ${status}`;
85
+ return new PersonizeError(`${message} (${method} ${endpoint})`, { status, endpoint, method, cause: error });
86
+ }
@@ -0,0 +1,3 @@
1
+ export * from './types';
2
+ export * from './client';
3
+ export * from './errors';
package/dist/index.js ADDED
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
18
+ __exportStar(require("./client"), exports);
19
+ __exportStar(require("./errors"), exports);