@maximem/synap-js-sdk 0.6.8 → 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.
Files changed (36) hide show
  1. package/dist/anticipation-cache-Q7IYC3ID.cjs.map +1 -1
  2. package/dist/{chunk-DEFC7NHQ.js → chunk-BMA3HZEX.js} +6 -1
  3. package/dist/chunk-BMA3HZEX.js.map +1 -0
  4. package/dist/chunk-BYUGILQI.cjs.map +1 -1
  5. package/dist/{chunk-7IZHVYO2.cjs → chunk-JPDEKN5M.cjs} +28 -23
  6. package/dist/chunk-JPDEKN5M.cjs.map +1 -0
  7. package/dist/{chunk-YUCHB2YK.js → chunk-RKKTOLXP.js} +2 -2
  8. package/dist/{chunk-EI4AGILN.cjs → chunk-SAKMZI7G.cjs} +6 -6
  9. package/dist/chunk-SAKMZI7G.cjs.map +1 -0
  10. package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
  11. package/dist/env-55ULHNJZ.cjs.map +1 -1
  12. package/dist/{errors-x5bpgxmC.d.ts → errors-DEJFTN6v.d.cts} +9 -2
  13. package/dist/{errors-x5bpgxmC.d.cts → errors-DEJFTN6v.d.ts} +9 -2
  14. package/dist/grpc/index.cjs +7 -7
  15. package/dist/grpc/index.cjs.map +1 -1
  16. package/dist/grpc/index.d.cts +1 -1
  17. package/dist/grpc/index.d.ts +1 -1
  18. package/dist/grpc/index.js +3 -3
  19. package/dist/index.cjs +666 -232
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +171 -4
  22. package/dist/index.d.ts +171 -4
  23. package/dist/index.js +443 -9
  24. package/dist/index.js.map +1 -1
  25. package/dist/onnx-encoder-4RSL6ID4.cjs.map +1 -1
  26. package/dist/{stream-client-Q2RR5SCS.js → stream-client-7A2DQ3H3.js} +3 -3
  27. package/dist/stream-client-H2ES74FF.cjs +22 -0
  28. package/dist/stream-client-H2ES74FF.cjs.map +1 -0
  29. package/package.json +1 -1
  30. package/dist/chunk-7IZHVYO2.cjs.map +0 -1
  31. package/dist/chunk-DEFC7NHQ.js.map +0 -1
  32. package/dist/chunk-EI4AGILN.cjs.map +0 -1
  33. package/dist/stream-client-TDHTS7F4.cjs +0 -22
  34. package/dist/stream-client-TDHTS7F4.cjs.map +0 -1
  35. /package/dist/{chunk-YUCHB2YK.js.map → chunk-RKKTOLXP.js.map} +0 -0
  36. /package/dist/{stream-client-Q2RR5SCS.js.map → stream-client-7A2DQ3H3.js.map} +0 -0
package/dist/index.js CHANGED
@@ -32,6 +32,7 @@ import {
32
32
  PermanentError,
33
33
  RateLimitError,
34
34
  SDKError,
35
+ ScopeLadderError,
35
36
  ServiceUnavailableError,
36
37
  SessionExpiredError,
37
38
  SynapError,
@@ -41,7 +42,7 @@ import {
41
42
  TransientError,
42
43
  isSynapError,
43
44
  newCorrelationId
44
- } from "./chunk-DEFC7NHQ.js";
45
+ } from "./chunk-BMA3HZEX.js";
45
46
 
46
47
  // src/local-mode.ts
47
48
  function isLocalMode(apiKey, baseUrl) {
@@ -83,7 +84,9 @@ var ENDPOINTS = {
83
84
  credits_ledger: { method: "GET", path: "/v1/credits/ledger", idempotent: true },
84
85
  credits_estimate: { method: "POST", path: "/v1/credits/estimate", idempotent: true },
85
86
  credits_redeem: { method: "POST", path: "/v1/credits/redeem", idempotent: false },
86
- telemetry_batch: { method: "POST", path: "/v1/telemetry/batch", idempotent: false }
87
+ telemetry_batch: { method: "POST", path: "/v1/telemetry/batch", idempotent: false },
88
+ maca_generate: { method: "POST", path: "/v1/maca/generate", idempotent: false },
89
+ maca_job: { method: "GET", path: "/v1/maca/jobs/{job_id}", idempotent: true }
87
90
  };
88
91
  function resolvePath(name, params = {}) {
89
92
  return ENDPOINTS[name].path.replace(/\{(\w+)\}/g, (_m, key) => {
@@ -214,6 +217,197 @@ function checkCustomerId(isolation, customerId, where, instanceId) {
214
217
  throw new CustomerIdNotAcceptedError(where, String(customerId), instanceId);
215
218
  }
216
219
 
220
+ // src/scope-ladder.ts
221
+ var ROLE_TENANT = "tenant_of_record";
222
+ var ROLE_IDENTITY = "identity";
223
+ var LADDER_TTL_MS = 3e5;
224
+ var LADDER_RETRY_BACKOFF_MS = 6e4;
225
+ var LADDER_INVALIDATION_MIN_INTERVAL_MS = 5e3;
226
+ var ScopeAddress = class {
227
+ user_id;
228
+ customer_id;
229
+ scope_path;
230
+ constructor(init = {}) {
231
+ this.user_id = init.user_id ?? null;
232
+ this.customer_id = init.customer_id ?? null;
233
+ this.scope_path = init.scope_path ?? null;
234
+ }
235
+ /** Options for reads (`fetch`, `*.context.fetch`, `send_message`, ...): the path is `scope_path`. */
236
+ read_kwargs() {
237
+ const out = {};
238
+ if (this.user_id) out.user_id = this.user_id;
239
+ if (this.customer_id) out.customer_id = this.customer_id;
240
+ if (this.scope_path && Object.keys(this.scope_path).length > 0) {
241
+ out.scope_path = { ...this.scope_path };
242
+ }
243
+ return out;
244
+ }
245
+ /** Options for `memories.create` / `create_from_file` / `forget`: the path is `scope`. */
246
+ write_kwargs() {
247
+ const out = {};
248
+ if (this.user_id) out.user_id = this.user_id;
249
+ if (this.customer_id) out.customer_id = this.customer_id;
250
+ if (this.scope_path && Object.keys(this.scope_path).length > 0) {
251
+ out.scope = { ...this.scope_path };
252
+ }
253
+ return out;
254
+ }
255
+ };
256
+ var REFRESH_HINT = "The account's ladder may not be accepted yet, or nested scoping may be off for this instance. If that changed recently, `await sdk.get_scope_ladder({ refresh: true })` re-reads it.";
257
+ var ScopeLadder = class {
258
+ levels;
259
+ is_default;
260
+ ladder_ratified;
261
+ nested_scoping_enabled;
262
+ /** "server" | "inferred" */
263
+ source;
264
+ /** True when the instance is B2C: the tenant and identity level are one node. */
265
+ b2c;
266
+ constructor(init) {
267
+ this.levels = Object.freeze([...init.levels]);
268
+ this.is_default = init.is_default;
269
+ this.ladder_ratified = init.ladder_ratified;
270
+ this.nested_scoping_enabled = init.nested_scoping_enabled;
271
+ this.source = init.source;
272
+ this.b2c = init.b2c ?? false;
273
+ }
274
+ get keys() {
275
+ return this.levels.map((l) => l.key);
276
+ }
277
+ /**
278
+ * Map `values` (outermost level first) to ids and, on a deeper ladder, the
279
+ * full prefix path. A shorter list addresses a higher level. Throws
280
+ * `ScopeLadderError` before any call when the values cannot be addressed.
281
+ */
282
+ address(values) {
283
+ if (!Array.isArray(values)) {
284
+ throw new ScopeLadderError(
285
+ `address() takes a list of values, outermost level first, got ${typeof values}.`
286
+ );
287
+ }
288
+ const vals = [...values];
289
+ if (vals.length === 0) {
290
+ throw new ScopeLadderError(
291
+ `address() needs at least one value. The client level is addressed explicitly elsewhere (scope='client'), not through the ladder. Levels, outermost first: ${JSON.stringify(this.keys)}.`
292
+ );
293
+ }
294
+ for (const v of vals) {
295
+ if (typeof v !== "string" || v === "") {
296
+ throw new ScopeLadderError(`address() values must be non-empty strings, got ${JSON.stringify(v)}.`);
297
+ }
298
+ }
299
+ const levels = this.levels;
300
+ const expected = this.b2c ? levels.filter((l) => l.role !== ROLE_TENANT) : levels;
301
+ if (vals.length > expected.length) {
302
+ throw new ScopeLadderError(
303
+ `${vals.length} values for ${expected.length} levels (${JSON.stringify(expected.map((l) => l.key))}, outermost first).`
304
+ );
305
+ }
306
+ if (!this.is_default && (!this.nested_scoping_enabled || !this.ladder_ratified)) {
307
+ throw new ScopeLadderError(
308
+ `This account has a deeper scope ladder (${JSON.stringify(this.keys)}), but the server would refuse a scope path (nested_scoping_enabled=${this.nested_scoping_enabled}, ladder_ratified=${this.ladder_ratified}). ` + REFRESH_HINT
309
+ );
310
+ }
311
+ let userId = null;
312
+ let customerId = null;
313
+ const path = {};
314
+ if (this.b2c) {
315
+ const identity = levels.find((l) => l.role === ROLE_IDENTITY);
316
+ if (identity === void 0) {
317
+ throw new ScopeLadderError("This ladder has no identity level, so a B2C address cannot be built.");
318
+ }
319
+ if (vals.length < expected.length) {
320
+ throw new ScopeLadderError(
321
+ `On a B2C instance the tenant level takes the identity's value, so give one value for every level after it (${JSON.stringify(expected.map((l) => l.key))}); got ${vals.length}.`
322
+ );
323
+ }
324
+ const byKey = /* @__PURE__ */ new Map();
325
+ expected.forEach((l, i) => byKey.set(l.key, vals[i]));
326
+ const identityValue = byKey.get(identity.key);
327
+ userId = identityValue;
328
+ if (!this.is_default) {
329
+ for (const l of levels) {
330
+ path[l.key] = l.role === ROLE_TENANT ? identityValue : byKey.get(l.key);
331
+ }
332
+ }
333
+ } else {
334
+ levels.slice(0, vals.length).forEach((l, i) => {
335
+ const v = vals[i];
336
+ if (l.role === ROLE_TENANT) customerId = v;
337
+ else if (l.role === ROLE_IDENTITY) userId = v;
338
+ if (!this.is_default) path[l.key] = v;
339
+ });
340
+ }
341
+ return new ScopeAddress({
342
+ user_id: userId,
343
+ customer_id: customerId,
344
+ scope_path: Object.keys(path).length > 0 ? path : null
345
+ });
346
+ }
347
+ };
348
+ var STRICT_LEVELS = [
349
+ { key: "customer", label: "Customer", position: 1, role: ROLE_TENANT, required: true },
350
+ { key: "user", label: "User", position: 2, role: ROLE_IDENTITY, required: true }
351
+ ];
352
+ var B2C_LEVELS = [
353
+ { key: "user", label: "User", position: 1, role: ROLE_IDENTITY, required: true }
354
+ ];
355
+ function parseLevels(raw) {
356
+ if (!Array.isArray(raw) || raw.length === 0) return null;
357
+ const out = [];
358
+ for (const item of raw) {
359
+ if (typeof item !== "object" || item === null || Array.isArray(item)) return null;
360
+ const o2 = item;
361
+ const key = o2["key"];
362
+ if (typeof key !== "string" || key === "") return null;
363
+ const position = Number(o2["position"]);
364
+ if (!Number.isFinite(position) || o2["position"] === null || o2["position"] === "") return null;
365
+ const label = o2["label"];
366
+ const role = o2["role"];
367
+ out.push({
368
+ key,
369
+ label: typeof label === "string" && label !== "" ? label : key,
370
+ position: Math.trunc(position),
371
+ role: typeof role === "string" && role !== "" ? role : null,
372
+ required: o2["required"] === void 0 ? true : Boolean(o2["required"])
373
+ });
374
+ }
375
+ out.sort((a, b) => a.position - b.position);
376
+ return out;
377
+ }
378
+ function ladderFromWhoami(whoami, fallbackIsolation, warn = () => {
379
+ }) {
380
+ const rawIso = whoami["user_context_isolation"];
381
+ const isolation = (typeof rawIso === "string" && rawIso !== "" ? rawIso : void 0) ?? fallbackIsolation;
382
+ const b2c = isolation === "equals_customer";
383
+ const block = whoami["scope_ladder"];
384
+ if (block !== void 0 && block !== null) {
385
+ const levels = typeof block === "object" && !Array.isArray(block) ? parseLevels(block["levels"]) : null;
386
+ if (levels === null) {
387
+ warn("whoami returned a malformed scope_ladder block; ignoring it and inferring the default ladder.");
388
+ } else {
389
+ const b = block;
390
+ return new ScopeLadder({
391
+ levels,
392
+ is_default: Boolean(b["is_default"]),
393
+ ladder_ratified: Boolean(b["ladder_ratified"]),
394
+ nested_scoping_enabled: Boolean(b["nested_scoping_enabled"]),
395
+ source: "server",
396
+ b2c
397
+ });
398
+ }
399
+ }
400
+ if (isolation === void 0) return null;
401
+ return new ScopeLadder({
402
+ levels: b2c ? B2C_LEVELS : STRICT_LEVELS,
403
+ is_default: true,
404
+ ladder_ratified: false,
405
+ nested_scoping_enabled: false,
406
+ source: "inferred",
407
+ b2c
408
+ });
409
+ }
410
+
217
411
  // src/transport/http.ts
218
412
  var DEFAULT_BASE_URL = "https://synap-cloud-prod.maximem.ai";
219
413
  var GATED_POST_PATHS = [
@@ -327,6 +521,104 @@ var HttpTransport = class {
327
521
  * deployment older than the field, and must mean "enforce nothing".
328
522
  */
329
523
  userContextIsolation = void 0;
524
+ // ── Scope ladder (Python: MaximemSynapSDK.get_scope_ladder) ───────────────
525
+ // Held here, like `userContextIsolation`, so the interface factories that
526
+ // receive the transport can reach it and the client's public surface carries
527
+ // only the method Python has.
528
+ #ladder = null;
529
+ // Loaded is separate from the value: "the server does not say" (null) is an
530
+ // answer too, and is cached for the same 300 s.
531
+ #ladderLoaded = false;
532
+ #ladderExpiresAt = 0;
533
+ #ladderRetryAt = 0;
534
+ // Bumped by every invalidation. A read that started under an older number is
535
+ // not stored when it finishes.
536
+ #ladderGeneration = 0;
537
+ #ladderInvalidated = false;
538
+ #ladderInvalidationReadAt = Number.NEGATIVE_INFINITY;
539
+ // The read in flight, shared by concurrent callers.
540
+ #ladderInflight = void 0;
541
+ /**
542
+ * Called as observer(error, carriedScopePath) for every 400 answer.
543
+ * `carriedScopePath` says whether the refused request named a scope path,
544
+ * which is how the client learns its cached ladder may be stale. Never
545
+ * allowed to throw.
546
+ */
547
+ onInvalidInput = void 0;
548
+ /**
549
+ * A 400 answered a call that carried a scope path: the ladder we hold may be
550
+ * stale. The next read is at most one per LADDER_INVALIDATION_MIN_INTERVAL_MS,
551
+ * the last known ladder stays as the answer if it fails, and a read already
552
+ * in flight will not be stored.
553
+ *
554
+ * The server's refusal wording is deliberately not inspected. The gRPC
555
+ * stream does not surface HTTP 400, so a ladder error on the stream is not
556
+ * observed here.
557
+ */
558
+ invalidateScopeLadder() {
559
+ this.#ladderGeneration += 1;
560
+ this.#ladderInvalidated = true;
561
+ this.#ladderRetryAt = 0;
562
+ }
563
+ /**
564
+ * The account's ladder, from whoami, cached for 300 s (`null` included).
565
+ * Concurrent callers share one read. A failed re-read after expiry keeps the
566
+ * last known ladder (with a warning) and waits 60 s before trying again. A
567
+ * failure on the first read, or with `refresh`, is thrown.
568
+ */
569
+ async getScopeLadder(refresh, warn) {
570
+ const now = this.clock();
571
+ const cached2 = this.#ladder;
572
+ const loaded = this.#ladderLoaded;
573
+ if (!refresh && loaded) {
574
+ if (now < this.#ladderRetryAt) return cached2;
575
+ if (this.#ladderInvalidated) {
576
+ if (now < this.#ladderInvalidationReadAt + LADDER_INVALIDATION_MIN_INTERVAL_MS) return cached2;
577
+ } else if (now < this.#ladderExpiresAt) {
578
+ return cached2;
579
+ }
580
+ }
581
+ const keepOnFailure = loaded && !refresh;
582
+ const inflight = this.#ladderInflight;
583
+ if (inflight !== void 0 && inflight.generation === this.#ladderGeneration && inflight.keepOnFailure === keepOnFailure) {
584
+ return inflight.promise;
585
+ }
586
+ const generation = this.#ladderGeneration;
587
+ if (this.#ladderInvalidated && !refresh) this.#ladderInvalidationReadAt = now;
588
+ const promise = this.#readScopeLadder(now, generation, cached2, keepOnFailure, warn);
589
+ const entry = { promise, generation, keepOnFailure };
590
+ this.#ladderInflight = entry;
591
+ const clear = () => {
592
+ if (this.#ladderInflight === entry) this.#ladderInflight = void 0;
593
+ };
594
+ promise.then(clear, clear);
595
+ return promise;
596
+ }
597
+ async #readScopeLadder(now, generation, cached2, keepOnFailure, warn) {
598
+ let whoami;
599
+ try {
600
+ const raw = await this.request("whoami", {});
601
+ whoami = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
602
+ } catch (error) {
603
+ if (keepOnFailure) {
604
+ warn(
605
+ `Could not re-read the scope ladder (${error?.message ?? String(error)}); keeping the last known one and retrying in ${LADDER_RETRY_BACKOFF_MS / 1e3}s.`
606
+ );
607
+ this.#ladderRetryAt = now + LADDER_RETRY_BACKOFF_MS;
608
+ return cached2;
609
+ }
610
+ throw error;
611
+ }
612
+ const ladder = ladderFromWhoami(whoami, this.userContextIsolation, warn);
613
+ if (generation === this.#ladderGeneration) {
614
+ this.#ladder = ladder;
615
+ this.#ladderLoaded = true;
616
+ this.#ladderExpiresAt = now + LADDER_TTL_MS;
617
+ this.#ladderRetryAt = 0;
618
+ this.#ladderInvalidated = false;
619
+ }
620
+ return ladder;
621
+ }
330
622
  /**
331
623
  * Set by the client to its identity resolution (`initialize()`'s whoami).
332
624
  * Python refuses every call before `initialize()`; here the first request
@@ -457,6 +749,12 @@ var HttpTransport = class {
457
749
  }
458
750
  if (!response.ok) {
459
751
  const error = await toHttpError(response, correlationId);
752
+ if (response.status === 400 && error instanceof InvalidInputError) {
753
+ try {
754
+ this.onInvalidInput?.(error, carriesScopePath(options.body));
755
+ } catch {
756
+ }
757
+ }
460
758
  throw options.mapError?.(response.status, error) ?? error;
461
759
  }
462
760
  if (response.status === 204) return void 0;
@@ -554,6 +852,38 @@ function creditReason(payload) {
554
852
  const error = stringOrNull(payload["error"]);
555
853
  return error !== null && CREDIT_ERRORS.has(error) ? error : null;
556
854
  }
855
+ function isScopePath(value) {
856
+ let v = value;
857
+ if (typeof v === "string" && v.trimStart().startsWith("{")) {
858
+ try {
859
+ v = JSON.parse(v);
860
+ } catch {
861
+ return false;
862
+ }
863
+ }
864
+ return typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length > 0;
865
+ }
866
+ function carriesScopePath(body) {
867
+ if (typeof FormData !== "undefined" && body instanceof FormData) {
868
+ if (isScopePath(body.get("scope"))) return true;
869
+ const manifest = body.get("manifest");
870
+ if (typeof manifest === "string") {
871
+ try {
872
+ const parsed = JSON.parse(manifest);
873
+ return typeof parsed === "object" && parsed !== null && isScopePath(parsed["scope"]);
874
+ } catch {
875
+ return false;
876
+ }
877
+ }
878
+ return false;
879
+ }
880
+ if (typeof body !== "object" || body === null || Array.isArray(body)) return false;
881
+ const o2 = body;
882
+ if (isScopePath(o2["scope"])) return true;
883
+ return Object.values(o2).some(
884
+ (v) => Array.isArray(v) && v.some((i) => typeof i === "object" && i !== null && isScopePath(i["scope"]))
885
+ );
886
+ }
557
887
  async function toHttpError(response, correlationId) {
558
888
  const body = await response.text().catch(() => "");
559
889
  let parsed = {};
@@ -2455,6 +2785,68 @@ function createCreditsNamespace(transport) {
2455
2785
  };
2456
2786
  }
2457
2787
 
2788
+ // src/maca/interface.ts
2789
+ var MACA_FINAL_STATUSES = ["succeeded", "invalid", "failed"];
2790
+ var MACA_MAX_FILE_BYTES = 256 * 1024;
2791
+ function toJob(raw) {
2792
+ return {
2793
+ job_id: String(raw["job_id"]),
2794
+ status: String(raw["status"]),
2795
+ message: typeof raw["message"] === "string" ? raw["message"] : "",
2796
+ created_at: typeof raw["created_at"] === "string" ? raw["created_at"] : null,
2797
+ updated_at: typeof raw["updated_at"] === "string" ? raw["updated_at"] : null,
2798
+ removed_fields: Array.isArray(raw["removed_fields"]) ? raw["removed_fields"] : [],
2799
+ problems: Array.isArray(raw["problems"]) ? raw["problems"] : [],
2800
+ config_file: typeof raw["config_file"] === "string" ? raw["config_file"] : null,
2801
+ yaml: typeof raw["yaml"] === "string" ? raw["yaml"] : null
2802
+ };
2803
+ }
2804
+ function createMacaNamespace(transport) {
2805
+ const namespace = {
2806
+ async generate(options) {
2807
+ const filePath = options.file_path ?? options.filePath;
2808
+ const relationship = options.user_relationship ?? options.userRelationship;
2809
+ if (relationship !== "b2c" && relationship !== "b2b") {
2810
+ throw new InvalidInputError("user_relationship must be 'b2c' or 'b2b'");
2811
+ }
2812
+ if (typeof filePath !== "string" || !filePath) throw new InvalidInputError("file_path is required");
2813
+ const { readFile, stat } = await import("fs/promises");
2814
+ const { basename } = await import("path");
2815
+ let size;
2816
+ try {
2817
+ size = (await stat(filePath)).size;
2818
+ } catch {
2819
+ throw new InvalidInputError(`file_path does not point to a readable file: ${filePath}`);
2820
+ }
2821
+ if (size === 0) throw new InvalidInputError("The use-case file is empty");
2822
+ if (size > MACA_MAX_FILE_BYTES) {
2823
+ throw new InvalidInputError(`The use-case file is larger than ${MACA_MAX_FILE_BYTES / 1024} KB`);
2824
+ }
2825
+ const bytes = await readFile(filePath);
2826
+ const form = new FormData();
2827
+ form.set("user_relationship", relationship);
2828
+ form.set("file", new Blob([bytes]), basename(filePath));
2829
+ return toJob(await transport.request("maca_generate", { body: form, rawBody: true }));
2830
+ },
2831
+ async get_job(jobId) {
2832
+ if (!jobId) throw new InvalidInputError("job_id is required");
2833
+ return toJob(await transport.request("maca_job", { pathParams: { job_id: jobId } }));
2834
+ },
2835
+ async wait_for_completion(jobId, options = {}) {
2836
+ const timeout = (options.timeout_seconds ?? options.timeoutSeconds ?? 3e3) * 1e3;
2837
+ const interval = (options.poll_interval_seconds ?? options.pollIntervalSeconds ?? 15) * 1e3;
2838
+ const start = Date.now();
2839
+ while (Date.now() - start < timeout) {
2840
+ const job = await namespace.get_job(jobId);
2841
+ if (MACA_FINAL_STATUSES.includes(job.status)) return job;
2842
+ await new Promise((resolve) => setTimeout(resolve, interval));
2843
+ }
2844
+ throw new Error(`MACA job ${jobId} did not finish within ${timeout / 1e3}s`);
2845
+ }
2846
+ };
2847
+ return namespace;
2848
+ }
2849
+
2458
2850
  // src/cache/interface.ts
2459
2851
  function createCacheNamespace(cache) {
2460
2852
  return {
@@ -2619,7 +3011,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2619
3011
  onListen?.();
2620
3012
  } catch {
2621
3013
  }
2622
- const { GrpcStreamClient } = await import("./stream-client-Q2RR5SCS.js");
3014
+ const { GrpcStreamClient } = await import("./stream-client-7A2DQ3H3.js");
2623
3015
  const onContext = options.on_context ?? options.onContext;
2624
3016
  const onDisconnect = options.on_disconnect ?? options.onDisconnect;
2625
3017
  const onReconnect = options.on_reconnect ?? options.onReconnect;
@@ -2835,7 +3227,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2835
3227
  }
2836
3228
 
2837
3229
  // src/version.ts
2838
- var SDK_VERSION = "0.6.8";
3230
+ var SDK_VERSION = "0.7.0";
2839
3231
 
2840
3232
  // src/registry.ts
2841
3233
  var instances = /* @__PURE__ */ new Map();
@@ -4437,7 +4829,8 @@ function toolInputSchema(scope, options) {
4437
4829
  }
4438
4830
  var RESULT_COLLECTIONS = ["facts", "preferences", "episodes", "emotions", "temporal_events"];
4439
4831
  async function invokeScopeFetch(params) {
4440
- const { target, scope, userId, customerId, conversationId, callArgs } = params;
4832
+ const { target, scope, userId, customerId, conversationId, callArgs, scopePath } = params;
4833
+ const pathOpt = scopePath !== void 0 && scopePath !== null && Object.keys(scopePath).length > 0 ? { scope_path: scopePath } : {};
4441
4834
  const searchQuery = callArgs["search_query"];
4442
4835
  const rawMax = callArgs["max_results"];
4443
4836
  const maxResults = typeof rawMax === "number" && rawMax !== 0 ? Math.trunc(rawMax) : 10;
@@ -4450,7 +4843,8 @@ async function invokeScopeFetch(params) {
4450
4843
  max_results: maxResults,
4451
4844
  types,
4452
4845
  mode,
4453
- precision_level: precisionLevel
4846
+ precision_level: precisionLevel,
4847
+ ...pathOpt
4454
4848
  };
4455
4849
  if (scope === "unified") {
4456
4850
  const response2 = await target.fetch({
@@ -4530,7 +4924,15 @@ function buildTool(target, options = {}, onWarning = () => {
4530
4924
  const toolName = options.name ?? `synap_fetch_${scope}_context`;
4531
4925
  const toolDesc = options.description ?? defaultToolDescription(scope);
4532
4926
  const schema = toolInputSchema(scope, { hasConversationId: conversationId !== void 0 });
4533
- const handler = (callArgs = {}) => invokeScopeFetch({ target, scope, userId, customerId, conversationId, callArgs });
4927
+ const handler = (callArgs = {}) => invokeScopeFetch({
4928
+ target,
4929
+ scope,
4930
+ userId,
4931
+ customerId,
4932
+ conversationId,
4933
+ callArgs,
4934
+ scopePath: options.scope_path
4935
+ });
4534
4936
  if (style === "openai") {
4535
4937
  return {
4536
4938
  type: "function",
@@ -4565,6 +4967,7 @@ var SynapClient = class _SynapClient {
4565
4967
  memories;
4566
4968
  data;
4567
4969
  credits;
4970
+ maca;
4568
4971
  cache;
4569
4972
  instance;
4570
4973
  #closed = false;
@@ -4620,10 +5023,14 @@ var SynapClient = class _SynapClient {
4620
5023
  ...options.retryPolicy !== void 0 ? { retryPolicy: options.retryPolicy } : {},
4621
5024
  ...options.keepAlive !== void 0 ? { keepAlive: options.keepAlive } : {},
4622
5025
  ...options.fetchImpl !== void 0 ? { fetchImpl: options.fetchImpl } : {},
5026
+ ...options._clock !== void 0 ? { clock: options._clock } : {},
4623
5027
  userAgent: `@maximem/synap-js-sdk/${SDK_VERSION}`
4624
5028
  });
4625
5029
  if (options.heartbeat) this.#transport.startHeartbeat();
4626
5030
  this.#transport.identityResolver = () => this.#resolveIdentity();
5031
+ this.#transport.onInvalidInput = (_error, carriedScopePath) => {
5032
+ if (carriedScopePath) this.#transport.invalidateScopeLadder();
5033
+ };
4627
5034
  this.#anticipationCache = new AnticipationCache();
4628
5035
  this.#fetchHooks = {
4629
5036
  beforeFetch: async (scope, options2) => {
@@ -4793,6 +5200,7 @@ var SynapClient = class _SynapClient {
4793
5200
  return cleared;
4794
5201
  });
4795
5202
  this.credits = createCreditsNamespace(this.#transport);
5203
+ this.maca = createMacaNamespace(this.#transport);
4796
5204
  this.cache = createCacheNamespace(this.#anticipationCache);
4797
5205
  this.instance = createInstanceNamespace(
4798
5206
  () => this.#transport.currentCredentials(),
@@ -4923,6 +5331,25 @@ var SynapClient = class _SynapClient {
4923
5331
  this.#initialized = true;
4924
5332
  await this.#resolveIdentity();
4925
5333
  }
5334
+ /**
5335
+ * The account's scope ladder, or `null` when it cannot be known.
5336
+ *
5337
+ * Mirrors Python's `get_scope_ladder()`. Read lazily from
5338
+ * `GET /api/v1/auth/whoami` (even when the client and instance ids are
5339
+ * already known), cached for 300 s (`null` included), re-read on `refresh: true`. Concurrent
5340
+ * callers share one read. If a re-read
5341
+ * after expiry fails, the last known ladder is returned with a warning and
5342
+ * the next try waits 60 s. A failure on the very first read, or with
5343
+ * `refresh`, is thrown. With no `scope_ladder` block the default ladder is
5344
+ * inferred from `user_context_isolation` (`source: "inferred"`).
5345
+ *
5346
+ * const ladder = await client.get_scope_ladder();
5347
+ * const addr = ladder!.address(['acme', 'payments', 'dana']);
5348
+ * await client.fetch({ search_query: ['...'], ...addr.read_kwargs() });
5349
+ */
5350
+ async get_scope_ladder(options = {}) {
5351
+ return this.#transport.getScopeLadder(options.refresh === true, (m) => this.#warn(m));
5352
+ }
4926
5353
  /** Runs whoami at most once, however many calls arrive together. */
4927
5354
  #resolveIdentity() {
4928
5355
  this.#identity ??= this.#whoami().catch((error) => {
@@ -5049,7 +5476,8 @@ var SynapClient = class _SynapClient {
5049
5476
  context_mode: contextMode = "in-conversation",
5050
5477
  include_profile: includeProfile = true,
5051
5478
  last_n_conversations: lastNConversations = 1,
5052
- response_shape: responseShape = "by_type"
5479
+ response_shape: responseShape = "by_type",
5480
+ scope_path: scopePath
5053
5481
  } = options;
5054
5482
  await this.#transport.checkCustomerId(customerId, "sdk.fetch");
5055
5483
  validateConversationId(conversationId);
@@ -5066,7 +5494,10 @@ var SynapClient = class _SynapClient {
5066
5494
  // sits one indent deeper; spreading removes that whole class of miss.
5067
5495
  query_date: queryDate,
5068
5496
  max_results_per_query: maxResultsPerQuery,
5069
- response_shape: responseShape
5497
+ response_shape: responseShape,
5498
+ // Forwarded only when set (Python: `if scope_path`), so a call without
5499
+ // one hands every scope fetch exactly the options it always got.
5500
+ ...scopePath !== void 0 && scopePath !== null && Object.keys(scopePath).length > 0 ? { scope_path: scopePath } : {}
5070
5501
  };
5071
5502
  const labels = [];
5072
5503
  const tasks = [];
@@ -5483,6 +5914,9 @@ export {
5483
5914
  RateLimitError,
5484
5915
  SDKError,
5485
5916
  SDK_VERSION,
5917
+ ScopeAddress,
5918
+ ScopeLadder,
5919
+ ScopeLadderError,
5486
5920
  ServiceUnavailableError,
5487
5921
  SessionExpiredError,
5488
5922
  SynapClient,