@maximem/synap-js-sdk 0.5.21 → 0.6.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/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Encoder, a as AnticipationCacheSnapshot } from './errors-BvUA5EW8.cjs';
2
- export { b as ANY_SCOPE, c as AgentUnavailableError, A as AnticipationCache, d as AnticipationCacheOptions, e as AuthenticationError, B as BundleItem, C as ConflictError, f as ConnectionError, g as ContextBundle, h as ContextNotFoundError, i as CustomerIdNotAcceptedError, j as ExitReason, I as InsufficientCreditsError, k as InvalidConversationIdError, l as InvalidInputError, m as InvalidInstanceIdError, L as ListeningAlreadyActiveError, n as ListeningNotActiveError, o as LookupParams, p as LookupResult, q as LookupTelemetry, N as NetworkTimeoutError, P as PermanentError, R as RateLimitError, r as SDKError, s as ServiceUnavailableError, t as SessionExpiredError, u as SnapshotBundle, v as SnapshotItemPreview, w as SnapshotItemRecord, S as SynapError, x as SynapErrorCode, y as SynapErrorOptions, z as SynapPermanentError, D as SynapTransientError, T as TranscriptConflictError, F as TransientError, G as isSynapError } from './errors-BvUA5EW8.cjs';
1
+ import { E as Encoder, a as AnticipationCacheSnapshot } from './errors-DWjdpExq.cjs';
2
+ export { b as ANY_SCOPE, c as AgentUnavailableError, A as AnticipationCache, d as AnticipationCacheOptions, e as AuthenticationError, B as BundleItem, C as ConflictError, f as ConnectionError, g as ContextBundle, h as ContextNotFoundError, i as CustomerIdNotAcceptedError, j as ExitReason, I as InstanceBuildFailedError, k as InstanceNotReadyError, l as InsufficientCreditsError, m as InvalidConversationIdError, n as InvalidInputError, o as InvalidInstanceIdError, L as ListeningAlreadyActiveError, p as ListeningNotActiveError, q as LookupParams, r as LookupResult, s as LookupTelemetry, N as NetworkTimeoutError, P as PermanentError, R as RateLimitError, t as SDKError, u as ServiceUnavailableError, v as SessionExpiredError, w as SnapshotBundle, x as SnapshotItemPreview, y as SnapshotItemRecord, S as SynapError, z as SynapErrorCode, D as SynapErrorOptions, F as SynapPermanentError, G as SynapTransientError, T as TranscriptConflictError, H as TransientError, J as isSynapError } from './errors-DWjdpExq.cjs';
3
3
 
4
4
  /**
5
5
  * AUTOGENERATED FROM synap/sdk/CONTRACT/endpoints.yaml -- DO NOT EDIT.
@@ -240,7 +240,11 @@ interface KeepAliveOptions {
240
240
 
241
241
  declare const DEFAULT_BASE_URL = "https://synap-cloud-prod.maximem.ai";
242
242
  interface TimeoutConfig {
243
- /** Seconds. Mirrors TimeoutConfig in the Python SDK. */
243
+ /**
244
+ * Seconds. Same fields as TimeoutConfig in the Python SDK, but only `read`
245
+ * is applied here: it limits the whole request. `connect` and `write` are
246
+ * accepted so a config round-trips between the SDKs, and have no effect.
247
+ */
244
248
  connect: number;
245
249
  read: number;
246
250
  write: number;
@@ -269,6 +273,8 @@ interface HttpTransportOptions {
269
273
  userAgent?: string;
270
274
  /** Injected in tests. Defaults to global fetch. */
271
275
  fetchImpl?: typeof fetch;
276
+ /** Monotonic clock in milliseconds. Injected in tests; defaults to `performance.now`. */
277
+ clock?: () => number;
272
278
  }
273
279
  interface RequestOptions {
274
280
  pathParams?: Record<string, string | number>;
@@ -296,6 +302,8 @@ declare class HttpTransport {
296
302
  private readonly keepAliveOptions;
297
303
  private readonly heartbeat;
298
304
  private closed;
305
+ private readonly clock;
306
+ private readonly notReadyCooldown;
299
307
  constructor(options: HttpTransportOptions);
300
308
  /** Start keeping the connection warm. Opt-in: it is pointless in serverless. */
301
309
  startHeartbeat(): void;
@@ -352,6 +360,10 @@ declare class HttpTransport {
352
360
  */
353
361
  setRetryPolicy(policy: Partial<RetryPolicy> | null): void;
354
362
  close(): void;
363
+ /** Throw InstanceNotReadyError locally if this instance is cooling down. */
364
+ private cooldownCheck;
365
+ /** Remember a server refusal. Never longer than the server's hint. */
366
+ private cooldownStart;
355
367
  request<T = unknown>(name: EndpointName, options?: RequestOptions): Promise<T>;
356
368
  private attempt;
357
369
  private buildUrl;
@@ -1216,7 +1228,10 @@ interface LedgerOptions {
1216
1228
  }
1217
1229
 
1218
1230
  /**
1219
- * Cache namespace. Mirrors `CacheInterface` in the Python SDK.
1231
+ * Cache namespace. Same method names as `CacheInterface` in the Python SDK,
1232
+ * but it covers only the in-memory cache of prefetched context: `stats()`
1233
+ * returns `{ bundles, items }`, not Python's `enabled`, `total_entries`,
1234
+ * `total_bytes` and `backends`. There is no on-disk cache in JS.
1220
1235
  *
1221
1236
  * This is a deliberately narrow facade over the AnticipationCache rather than
1222
1237
  * the cache object itself. Exposing the instance directly leaked internals
@@ -1892,7 +1907,7 @@ declare class SynapClient {
1892
1907
  * build when the two disagree, which is the only thing that makes a manual
1893
1908
  * publish safe.
1894
1909
  */
1895
- declare const SDK_VERSION = "0.5.21";
1910
+ declare const SDK_VERSION = "0.6.1";
1896
1911
 
1897
1912
  /**
1898
1913
  * `response_shape: "ranked"`: one list in the order the server ranked it.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { E as Encoder, a as AnticipationCacheSnapshot } from './errors-BvUA5EW8.js';
2
- export { b as ANY_SCOPE, c as AgentUnavailableError, A as AnticipationCache, d as AnticipationCacheOptions, e as AuthenticationError, B as BundleItem, C as ConflictError, f as ConnectionError, g as ContextBundle, h as ContextNotFoundError, i as CustomerIdNotAcceptedError, j as ExitReason, I as InsufficientCreditsError, k as InvalidConversationIdError, l as InvalidInputError, m as InvalidInstanceIdError, L as ListeningAlreadyActiveError, n as ListeningNotActiveError, o as LookupParams, p as LookupResult, q as LookupTelemetry, N as NetworkTimeoutError, P as PermanentError, R as RateLimitError, r as SDKError, s as ServiceUnavailableError, t as SessionExpiredError, u as SnapshotBundle, v as SnapshotItemPreview, w as SnapshotItemRecord, S as SynapError, x as SynapErrorCode, y as SynapErrorOptions, z as SynapPermanentError, D as SynapTransientError, T as TranscriptConflictError, F as TransientError, G as isSynapError } from './errors-BvUA5EW8.js';
1
+ import { E as Encoder, a as AnticipationCacheSnapshot } from './errors-DWjdpExq.js';
2
+ export { b as ANY_SCOPE, c as AgentUnavailableError, A as AnticipationCache, d as AnticipationCacheOptions, e as AuthenticationError, B as BundleItem, C as ConflictError, f as ConnectionError, g as ContextBundle, h as ContextNotFoundError, i as CustomerIdNotAcceptedError, j as ExitReason, I as InstanceBuildFailedError, k as InstanceNotReadyError, l as InsufficientCreditsError, m as InvalidConversationIdError, n as InvalidInputError, o as InvalidInstanceIdError, L as ListeningAlreadyActiveError, p as ListeningNotActiveError, q as LookupParams, r as LookupResult, s as LookupTelemetry, N as NetworkTimeoutError, P as PermanentError, R as RateLimitError, t as SDKError, u as ServiceUnavailableError, v as SessionExpiredError, w as SnapshotBundle, x as SnapshotItemPreview, y as SnapshotItemRecord, S as SynapError, z as SynapErrorCode, D as SynapErrorOptions, F as SynapPermanentError, G as SynapTransientError, T as TranscriptConflictError, H as TransientError, J as isSynapError } from './errors-DWjdpExq.js';
3
3
 
4
4
  /**
5
5
  * AUTOGENERATED FROM synap/sdk/CONTRACT/endpoints.yaml -- DO NOT EDIT.
@@ -240,7 +240,11 @@ interface KeepAliveOptions {
240
240
 
241
241
  declare const DEFAULT_BASE_URL = "https://synap-cloud-prod.maximem.ai";
242
242
  interface TimeoutConfig {
243
- /** Seconds. Mirrors TimeoutConfig in the Python SDK. */
243
+ /**
244
+ * Seconds. Same fields as TimeoutConfig in the Python SDK, but only `read`
245
+ * is applied here: it limits the whole request. `connect` and `write` are
246
+ * accepted so a config round-trips between the SDKs, and have no effect.
247
+ */
244
248
  connect: number;
245
249
  read: number;
246
250
  write: number;
@@ -269,6 +273,8 @@ interface HttpTransportOptions {
269
273
  userAgent?: string;
270
274
  /** Injected in tests. Defaults to global fetch. */
271
275
  fetchImpl?: typeof fetch;
276
+ /** Monotonic clock in milliseconds. Injected in tests; defaults to `performance.now`. */
277
+ clock?: () => number;
272
278
  }
273
279
  interface RequestOptions {
274
280
  pathParams?: Record<string, string | number>;
@@ -296,6 +302,8 @@ declare class HttpTransport {
296
302
  private readonly keepAliveOptions;
297
303
  private readonly heartbeat;
298
304
  private closed;
305
+ private readonly clock;
306
+ private readonly notReadyCooldown;
299
307
  constructor(options: HttpTransportOptions);
300
308
  /** Start keeping the connection warm. Opt-in: it is pointless in serverless. */
301
309
  startHeartbeat(): void;
@@ -352,6 +360,10 @@ declare class HttpTransport {
352
360
  */
353
361
  setRetryPolicy(policy: Partial<RetryPolicy> | null): void;
354
362
  close(): void;
363
+ /** Throw InstanceNotReadyError locally if this instance is cooling down. */
364
+ private cooldownCheck;
365
+ /** Remember a server refusal. Never longer than the server's hint. */
366
+ private cooldownStart;
355
367
  request<T = unknown>(name: EndpointName, options?: RequestOptions): Promise<T>;
356
368
  private attempt;
357
369
  private buildUrl;
@@ -1216,7 +1228,10 @@ interface LedgerOptions {
1216
1228
  }
1217
1229
 
1218
1230
  /**
1219
- * Cache namespace. Mirrors `CacheInterface` in the Python SDK.
1231
+ * Cache namespace. Same method names as `CacheInterface` in the Python SDK,
1232
+ * but it covers only the in-memory cache of prefetched context: `stats()`
1233
+ * returns `{ bundles, items }`, not Python's `enabled`, `total_entries`,
1234
+ * `total_bytes` and `backends`. There is no on-disk cache in JS.
1220
1235
  *
1221
1236
  * This is a deliberately narrow facade over the AnticipationCache rather than
1222
1237
  * the cache object itself. Exposing the instance directly leaked internals
@@ -1892,7 +1907,7 @@ declare class SynapClient {
1892
1907
  * build when the two disagree, which is the only thing that makes a manual
1893
1908
  * publish safe.
1894
1909
  */
1895
- declare const SDK_VERSION = "0.5.21";
1910
+ declare const SDK_VERSION = "0.6.1";
1896
1911
 
1897
1912
  /**
1898
1913
  * `response_shape: "ranked"`: one list in the order the server ranked it.
package/dist/index.js CHANGED
@@ -21,6 +21,8 @@ import {
21
21
  ConnectionError,
22
22
  ContextNotFoundError,
23
23
  CustomerIdNotAcceptedError,
24
+ InstanceBuildFailedError,
25
+ InstanceNotReadyError,
24
26
  InsufficientCreditsError,
25
27
  InvalidConversationIdError,
26
28
  InvalidInputError,
@@ -40,7 +42,7 @@ import {
40
42
  TransientError,
41
43
  isSynapError,
42
44
  newCorrelationId
43
- } from "./chunk-4GE7SORD.js";
45
+ } from "./chunk-DEFC7NHQ.js";
44
46
 
45
47
  // src/transport/endpoints.ts
46
48
  var ENDPOINTS = {
@@ -203,6 +205,36 @@ function checkCustomerId(isolation, customerId, where, instanceId) {
203
205
 
204
206
  // src/transport/http.ts
205
207
  var DEFAULT_BASE_URL = "https://synap-cloud-prod.maximem.ai";
208
+ var GATED_POST_PATHS = [
209
+ "/v1/context/conversation/fetch",
210
+ // sdk_context.py
211
+ "/v1/context/user/fetch",
212
+ // sdk_context.py
213
+ "/v1/context/customer/fetch",
214
+ // sdk_context.py
215
+ "/v1/context/client/fetch",
216
+ // sdk_context.py
217
+ "/v1/conversations/messages",
218
+ // sdk_conversations.py (+ /messages/batch)
219
+ "/v1/conversations/ingest",
220
+ // sdk_conversations.py
221
+ "/v1/events/batch",
222
+ // sdk_events.py
223
+ "/api/v1/memories/create",
224
+ // sdk_memories.py
225
+ "/api/v1/memories/batch",
226
+ // sdk_memories.py
227
+ "/api/v1/memories/upload",
228
+ // sdk_memories.py
229
+ "/v1/migrations"
230
+ // migrations.py (create, /{id}/approve, /{id}/run)
231
+ ];
232
+ var COOLDOWN_MAX_SECONDS = 300;
233
+ function isGatedPath(method, path) {
234
+ if (method.toUpperCase() !== "POST") return false;
235
+ const bare = (path.split("?", 1)[0] ?? "").replace(/\/+$/, "");
236
+ return GATED_POST_PATHS.some((p) => bare === p || bare.startsWith(p + "/"));
237
+ }
206
238
  var DEFAULT_TIMEOUTS = {
207
239
  connect: 5,
208
240
  read: 30,
@@ -221,7 +253,12 @@ var HttpTransport = class {
221
253
  keepAliveOptions;
222
254
  heartbeat;
223
255
  closed = false;
256
+ clock;
257
+ // instance id -> when the refusal's wait ends (monotonic ms), and what was said.
258
+ // One JS thread runs every request, so a plain Map needs no lock.
259
+ notReadyCooldown = /* @__PURE__ */ new Map();
224
260
  constructor(options) {
261
+ this.clock = options.clock ?? (() => performance.now());
225
262
  this.#credentials = options.credentials;
226
263
  this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
227
264
  this.timeouts = { ...DEFAULT_TIMEOUTS, ...options.timeouts };
@@ -312,18 +349,54 @@ var HttpTransport = class {
312
349
  this.closed = true;
313
350
  this.heartbeat.stop();
314
351
  }
352
+ /** Throw InstanceNotReadyError locally if this instance is cooling down. */
353
+ cooldownCheck(instanceId, correlationId) {
354
+ const entry = this.notReadyCooldown.get(instanceId);
355
+ if (entry === void 0) return;
356
+ const remainingMs = entry.until - this.clock();
357
+ if (remainingMs <= 0) {
358
+ this.notReadyCooldown.delete(instanceId);
359
+ return;
360
+ }
361
+ throw new InstanceNotReadyError(entry.message, {
362
+ correlationId,
363
+ retryAfterSeconds: Math.max(1, Math.ceil(remainingMs / 1e3)),
364
+ instanceId,
365
+ state: entry.state,
366
+ fromCooldown: true
367
+ });
368
+ }
369
+ /** Remember a server refusal. Never longer than the server's hint. */
370
+ cooldownStart(instanceId, error) {
371
+ const hint = error.retryAfterSeconds;
372
+ if (hint === null || !(hint > 0)) return;
373
+ const waitMs = Math.min(hint, COOLDOWN_MAX_SECONDS) * 1e3;
374
+ this.notReadyCooldown.set(instanceId, {
375
+ until: this.clock() + waitMs,
376
+ message: error.message,
377
+ state: error.state
378
+ });
379
+ }
315
380
  async request(name, options = {}) {
316
381
  const spec = ENDPOINTS[name];
317
382
  const correlationId = options.correlationId ?? newCorrelationId();
318
383
  const idempotent = options.idempotent ?? spec.idempotent;
319
384
  if (name !== "whoami") await this.ready();
385
+ const gated = isGatedPath(spec.method, resolvePath(name, options.pathParams));
386
+ const cooldownKey = this.#credentials.instanceId;
387
+ if (gated) this.cooldownCheck(cooldownKey, correlationId);
320
388
  let attempt = 0;
321
389
  let last = null;
322
390
  while (attempt < this.retryPolicy.maxAttempts) {
323
391
  attempt += 1;
324
392
  try {
325
- return await this.attempt(name, options, correlationId);
393
+ const result = await this.attempt(name, options, correlationId);
394
+ if (gated) this.notReadyCooldown.delete(cooldownKey);
395
+ return result;
326
396
  } catch (error) {
397
+ if (gated && error instanceof InstanceNotReadyError && !error.fromCooldown) {
398
+ this.cooldownStart(cooldownKey, error);
399
+ }
327
400
  last = { error, outcomeUnknown: isOutcomeUnknown(error) };
328
401
  const decision = shouldRetry({
329
402
  error,
@@ -492,6 +565,35 @@ async function toHttpError(response, correlationId) {
492
565
  });
493
566
  }
494
567
  case 409:
568
+ if (parsed["error"] === "instance_build_failed" || detailObject?.["code"] === "instance_build_failed" || detailObject?.["error"] === "instance_build_failed") {
569
+ const pick4 = (key) => parsed[key] ?? detailObject?.[key];
570
+ const msg = pick4("message");
571
+ const attempts = Number(pick4("attempts"));
572
+ return new InstanceBuildFailedError(
573
+ typeof msg === "string" && msg !== "" ? msg : "This instance's memory architecture build failed.",
574
+ {
575
+ ...opts,
576
+ instanceId: stringOrNull(pick4("instance_id")),
577
+ attempts: pick4("attempts") !== void 0 && pick4("attempts") !== null && Number.isFinite(attempts) ? Math.trunc(attempts) : null,
578
+ hint: stringOrNull(pick4("hint"))
579
+ }
580
+ );
581
+ }
582
+ if (parsed["error"] === "instance_not_ready" || detailObject?.["code"] === "instance_not_ready" || detailObject?.["error"] === "instance_not_ready") {
583
+ const pick4 = (key) => parsed[key] ?? detailObject?.[key];
584
+ const rawWait = pick4("retry_after_seconds") ?? response.headers.get("retry-after");
585
+ const wait = rawWait !== null && rawWait !== void 0 && String(rawWait).trim() !== "" ? Number(rawWait) : NaN;
586
+ const msg = pick4("message");
587
+ return new InstanceNotReadyError(
588
+ typeof msg === "string" && msg !== "" ? msg : "This instance's memory architecture is still being built.",
589
+ {
590
+ ...opts,
591
+ retryAfterSeconds: Number.isFinite(wait) ? Math.trunc(wait) : null,
592
+ instanceId: stringOrNull(pick4("instance_id")),
593
+ state: stringOrNull(pick4("state")) ?? "building"
594
+ }
595
+ );
596
+ }
495
597
  if (detailObject !== null && detailObject["code"] === "transcript_conflict") {
496
598
  return new TranscriptConflictError(message, opts);
497
599
  }
@@ -1860,7 +1962,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
1860
1962
  onListen?.();
1861
1963
  } catch {
1862
1964
  }
1863
- const { GrpcStreamClient } = await import("./stream-client-2UMDGCMQ.js");
1965
+ const { GrpcStreamClient } = await import("./stream-client-GRDVRBFA.js");
1864
1966
  const onContext = options.on_context ?? options.onContext;
1865
1967
  const onDisconnect = options.on_disconnect ?? options.onDisconnect;
1866
1968
  const onReconnect = options.on_reconnect ?? options.onReconnect;
@@ -2049,7 +2151,7 @@ function createInstanceNamespace(credentials, cache, onTurn, agentModel = () =>
2049
2151
  }
2050
2152
 
2051
2153
  // src/version.ts
2052
- var SDK_VERSION = "0.5.21";
2154
+ var SDK_VERSION = "0.6.1";
2053
2155
 
2054
2156
  // src/registry.ts
2055
2157
  var instances = /* @__PURE__ */ new Map();
@@ -4599,6 +4701,8 @@ export {
4599
4701
  HttpTransport,
4600
4702
  INGEST_MODES,
4601
4703
  ITEM_COLLECTIONS,
4704
+ InstanceBuildFailedError,
4705
+ InstanceNotReadyError,
4602
4706
  InsufficientCreditsError,
4603
4707
  InvalidConversationIdError,
4604
4708
  InvalidInputError,