@maximem/synap-js-sdk 0.6.8 → 0.7.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/anticipation-cache-Q7IYC3ID.cjs.map +1 -1
- package/dist/{chunk-DEFC7NHQ.js → chunk-BMA3HZEX.js} +6 -1
- package/dist/chunk-BMA3HZEX.js.map +1 -0
- package/dist/chunk-BYUGILQI.cjs.map +1 -1
- package/dist/{chunk-7IZHVYO2.cjs → chunk-JPDEKN5M.cjs} +28 -23
- package/dist/chunk-JPDEKN5M.cjs.map +1 -0
- package/dist/{chunk-YUCHB2YK.js → chunk-RKKTOLXP.js} +2 -2
- package/dist/{chunk-EI4AGILN.cjs → chunk-SAKMZI7G.cjs} +6 -6
- package/dist/chunk-SAKMZI7G.cjs.map +1 -0
- package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
- package/dist/env-55ULHNJZ.cjs.map +1 -1
- package/dist/{errors-x5bpgxmC.d.ts → errors-DEJFTN6v.d.cts} +9 -2
- package/dist/{errors-x5bpgxmC.d.cts → errors-DEJFTN6v.d.ts} +9 -2
- package/dist/grpc/index.cjs +7 -7
- package/dist/grpc/index.cjs.map +1 -1
- package/dist/grpc/index.d.cts +1 -1
- package/dist/grpc/index.d.ts +1 -1
- package/dist/grpc/index.js +3 -3
- package/dist/index.cjs +710 -235
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +200 -4
- package/dist/index.d.ts +200 -4
- package/dist/index.js +486 -11
- package/dist/index.js.map +1 -1
- package/dist/onnx-encoder-4RSL6ID4.cjs.map +1 -1
- package/dist/{stream-client-Q2RR5SCS.js → stream-client-7A2DQ3H3.js} +3 -3
- package/dist/stream-client-H2ES74FF.cjs +22 -0
- package/dist/stream-client-H2ES74FF.cjs.map +1 -0
- package/package.json +1 -1
- package/dist/chunk-7IZHVYO2.cjs.map +0 -1
- package/dist/chunk-DEFC7NHQ.js.map +0 -1
- package/dist/chunk-EI4AGILN.cjs.map +0 -1
- package/dist/stream-client-TDHTS7F4.cjs +0 -22
- package/dist/stream-client-TDHTS7F4.cjs.map +0 -1
- /package/dist/{chunk-YUCHB2YK.js.map → chunk-RKKTOLXP.js.map} +0 -0
- /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-
|
|
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,221 @@ 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
|
+
/**
|
|
236
|
+
* Options for reads: `fetch`, `send_message`, `record_message`,
|
|
237
|
+
* `user.context.fetch`, `conversation.context.fetch` and
|
|
238
|
+
* `client.context.fetch`. The path is `scope_path`.
|
|
239
|
+
*
|
|
240
|
+
* Not for `customer.context.fetch`: that route refuses a path that names the
|
|
241
|
+
* identity rung (HTTP 400, it reads shared material only) and takes no
|
|
242
|
+
* `user_id`. Call `client.fetch(addr.read_kwargs())`, which sends the
|
|
243
|
+
* customer route the path cut above the identity rung.
|
|
244
|
+
*/
|
|
245
|
+
read_kwargs() {
|
|
246
|
+
const out = {};
|
|
247
|
+
if (this.user_id) out.user_id = this.user_id;
|
|
248
|
+
if (this.customer_id) out.customer_id = this.customer_id;
|
|
249
|
+
if (this.scope_path && Object.keys(this.scope_path).length > 0) {
|
|
250
|
+
out.scope_path = { ...this.scope_path };
|
|
251
|
+
}
|
|
252
|
+
return out;
|
|
253
|
+
}
|
|
254
|
+
/** Options for `memories.create` / `create_from_file` / `forget`: the path is `scope`. */
|
|
255
|
+
write_kwargs() {
|
|
256
|
+
const out = {};
|
|
257
|
+
if (this.user_id) out.user_id = this.user_id;
|
|
258
|
+
if (this.customer_id) out.customer_id = this.customer_id;
|
|
259
|
+
if (this.scope_path && Object.keys(this.scope_path).length > 0) {
|
|
260
|
+
out.scope = { ...this.scope_path };
|
|
261
|
+
}
|
|
262
|
+
return out;
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
var RESERVED_IDENTITY_KEY = "user";
|
|
266
|
+
function pathAboveIdentity(scopePath, ladder) {
|
|
267
|
+
if (!scopePath || Object.keys(scopePath).length === 0) return void 0;
|
|
268
|
+
const identity = ladder?.levels.find((lv) => lv.role === ROLE_IDENTITY);
|
|
269
|
+
const out = {};
|
|
270
|
+
if (!ladder || !identity) {
|
|
271
|
+
for (const [k, v] of Object.entries(scopePath)) if (k !== RESERVED_IDENTITY_KEY) out[k] = v;
|
|
272
|
+
} else {
|
|
273
|
+
const position = new Map(ladder.levels.map((lv) => [lv.key, lv.position]));
|
|
274
|
+
for (const [k, v] of Object.entries(scopePath)) {
|
|
275
|
+
if ((position.get(k) ?? -1) < identity.position) out[k] = v;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
return Object.keys(out).length > 0 ? out : void 0;
|
|
279
|
+
}
|
|
280
|
+
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.";
|
|
281
|
+
var ScopeLadder = class {
|
|
282
|
+
levels;
|
|
283
|
+
is_default;
|
|
284
|
+
ladder_ratified;
|
|
285
|
+
nested_scoping_enabled;
|
|
286
|
+
/** "server" | "inferred" */
|
|
287
|
+
source;
|
|
288
|
+
/** True when the instance is B2C: the tenant and identity level are one node. */
|
|
289
|
+
b2c;
|
|
290
|
+
constructor(init) {
|
|
291
|
+
this.levels = Object.freeze([...init.levels]);
|
|
292
|
+
this.is_default = init.is_default;
|
|
293
|
+
this.ladder_ratified = init.ladder_ratified;
|
|
294
|
+
this.nested_scoping_enabled = init.nested_scoping_enabled;
|
|
295
|
+
this.source = init.source;
|
|
296
|
+
this.b2c = init.b2c ?? false;
|
|
297
|
+
}
|
|
298
|
+
get keys() {
|
|
299
|
+
return this.levels.map((l) => l.key);
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Map `values` (outermost level first) to ids and, on a deeper ladder, the
|
|
303
|
+
* full prefix path. A shorter list addresses a higher level. Throws
|
|
304
|
+
* `ScopeLadderError` before any call when the values cannot be addressed.
|
|
305
|
+
*/
|
|
306
|
+
address(values) {
|
|
307
|
+
if (!Array.isArray(values)) {
|
|
308
|
+
throw new ScopeLadderError(
|
|
309
|
+
`address() takes a list of values, outermost level first, got ${typeof values}.`
|
|
310
|
+
);
|
|
311
|
+
}
|
|
312
|
+
const vals = [...values];
|
|
313
|
+
if (vals.length === 0) {
|
|
314
|
+
throw new ScopeLadderError(
|
|
315
|
+
`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)}.`
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
for (const v of vals) {
|
|
319
|
+
if (typeof v !== "string" || v === "") {
|
|
320
|
+
throw new ScopeLadderError(`address() values must be non-empty strings, got ${JSON.stringify(v)}.`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
const levels = this.levels;
|
|
324
|
+
const expected = this.b2c ? levels.filter((l) => l.role !== ROLE_TENANT) : levels;
|
|
325
|
+
if (vals.length > expected.length) {
|
|
326
|
+
throw new ScopeLadderError(
|
|
327
|
+
`${vals.length} values for ${expected.length} levels (${JSON.stringify(expected.map((l) => l.key))}, outermost first).`
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
if (!this.is_default && (!this.nested_scoping_enabled || !this.ladder_ratified)) {
|
|
331
|
+
throw new ScopeLadderError(
|
|
332
|
+
`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
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
let userId = null;
|
|
336
|
+
let customerId = null;
|
|
337
|
+
const path = {};
|
|
338
|
+
if (this.b2c) {
|
|
339
|
+
const identity = levels.find((l) => l.role === ROLE_IDENTITY);
|
|
340
|
+
if (identity === void 0) {
|
|
341
|
+
throw new ScopeLadderError("This ladder has no identity level, so a B2C address cannot be built.");
|
|
342
|
+
}
|
|
343
|
+
if (vals.length < expected.length) {
|
|
344
|
+
throw new ScopeLadderError(
|
|
345
|
+
`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}.`
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
349
|
+
expected.forEach((l, i) => byKey.set(l.key, vals[i]));
|
|
350
|
+
const identityValue = byKey.get(identity.key);
|
|
351
|
+
userId = identityValue;
|
|
352
|
+
if (!this.is_default) {
|
|
353
|
+
for (const l of levels) {
|
|
354
|
+
path[l.key] = l.role === ROLE_TENANT ? identityValue : byKey.get(l.key);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
} else {
|
|
358
|
+
levels.slice(0, vals.length).forEach((l, i) => {
|
|
359
|
+
const v = vals[i];
|
|
360
|
+
if (l.role === ROLE_TENANT) customerId = v;
|
|
361
|
+
else if (l.role === ROLE_IDENTITY) userId = v;
|
|
362
|
+
if (!this.is_default) path[l.key] = v;
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
return new ScopeAddress({
|
|
366
|
+
user_id: userId,
|
|
367
|
+
customer_id: customerId,
|
|
368
|
+
scope_path: Object.keys(path).length > 0 ? path : null
|
|
369
|
+
});
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
var STRICT_LEVELS = [
|
|
373
|
+
{ key: "customer", label: "Customer", position: 1, role: ROLE_TENANT, required: true },
|
|
374
|
+
{ key: "user", label: "User", position: 2, role: ROLE_IDENTITY, required: true }
|
|
375
|
+
];
|
|
376
|
+
var B2C_LEVELS = [
|
|
377
|
+
{ key: "user", label: "User", position: 1, role: ROLE_IDENTITY, required: true }
|
|
378
|
+
];
|
|
379
|
+
function parseLevels(raw) {
|
|
380
|
+
if (!Array.isArray(raw) || raw.length === 0) return null;
|
|
381
|
+
const out = [];
|
|
382
|
+
for (const item of raw) {
|
|
383
|
+
if (typeof item !== "object" || item === null || Array.isArray(item)) return null;
|
|
384
|
+
const o2 = item;
|
|
385
|
+
const key = o2["key"];
|
|
386
|
+
if (typeof key !== "string" || key === "") return null;
|
|
387
|
+
const position = Number(o2["position"]);
|
|
388
|
+
if (!Number.isFinite(position) || o2["position"] === null || o2["position"] === "") return null;
|
|
389
|
+
const label = o2["label"];
|
|
390
|
+
const role = o2["role"];
|
|
391
|
+
out.push({
|
|
392
|
+
key,
|
|
393
|
+
label: typeof label === "string" && label !== "" ? label : key,
|
|
394
|
+
position: Math.trunc(position),
|
|
395
|
+
role: typeof role === "string" && role !== "" ? role : null,
|
|
396
|
+
required: o2["required"] === void 0 ? true : Boolean(o2["required"])
|
|
397
|
+
});
|
|
398
|
+
}
|
|
399
|
+
out.sort((a, b) => a.position - b.position);
|
|
400
|
+
return out;
|
|
401
|
+
}
|
|
402
|
+
function ladderFromWhoami(whoami, fallbackIsolation, warn = () => {
|
|
403
|
+
}) {
|
|
404
|
+
const rawIso = whoami["user_context_isolation"];
|
|
405
|
+
const isolation = (typeof rawIso === "string" && rawIso !== "" ? rawIso : void 0) ?? fallbackIsolation;
|
|
406
|
+
const b2c = isolation === "equals_customer";
|
|
407
|
+
const block = whoami["scope_ladder"];
|
|
408
|
+
if (block !== void 0 && block !== null) {
|
|
409
|
+
const levels = typeof block === "object" && !Array.isArray(block) ? parseLevels(block["levels"]) : null;
|
|
410
|
+
if (levels === null) {
|
|
411
|
+
warn("whoami returned a malformed scope_ladder block; ignoring it and inferring the default ladder.");
|
|
412
|
+
} else {
|
|
413
|
+
const b = block;
|
|
414
|
+
return new ScopeLadder({
|
|
415
|
+
levels,
|
|
416
|
+
is_default: Boolean(b["is_default"]),
|
|
417
|
+
ladder_ratified: Boolean(b["ladder_ratified"]),
|
|
418
|
+
nested_scoping_enabled: Boolean(b["nested_scoping_enabled"]),
|
|
419
|
+
source: "server",
|
|
420
|
+
b2c
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
if (isolation === void 0) return null;
|
|
425
|
+
return new ScopeLadder({
|
|
426
|
+
levels: b2c ? B2C_LEVELS : STRICT_LEVELS,
|
|
427
|
+
is_default: true,
|
|
428
|
+
ladder_ratified: false,
|
|
429
|
+
nested_scoping_enabled: false,
|
|
430
|
+
source: "inferred",
|
|
431
|
+
b2c
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
|
|
217
435
|
// src/transport/http.ts
|
|
218
436
|
var DEFAULT_BASE_URL = "https://synap-cloud-prod.maximem.ai";
|
|
219
437
|
var GATED_POST_PATHS = [
|
|
@@ -327,6 +545,108 @@ var HttpTransport = class {
|
|
|
327
545
|
* deployment older than the field, and must mean "enforce nothing".
|
|
328
546
|
*/
|
|
329
547
|
userContextIsolation = void 0;
|
|
548
|
+
// ── Scope ladder (Python: MaximemSynapSDK.get_scope_ladder) ───────────────
|
|
549
|
+
// Held here, like `userContextIsolation`, so the interface factories that
|
|
550
|
+
// receive the transport can reach it and the client's public surface carries
|
|
551
|
+
// only the method Python has.
|
|
552
|
+
#ladder = null;
|
|
553
|
+
// Loaded is separate from the value: "the server does not say" (null) is an
|
|
554
|
+
// answer too, and is cached for the same 300 s.
|
|
555
|
+
#ladderLoaded = false;
|
|
556
|
+
#ladderExpiresAt = 0;
|
|
557
|
+
#ladderRetryAt = 0;
|
|
558
|
+
// Bumped by every invalidation. A read that started under an older number is
|
|
559
|
+
// not stored when it finishes.
|
|
560
|
+
#ladderGeneration = 0;
|
|
561
|
+
#ladderInvalidated = false;
|
|
562
|
+
#ladderInvalidationReadAt = Number.NEGATIVE_INFINITY;
|
|
563
|
+
// The read in flight, shared by concurrent callers.
|
|
564
|
+
#ladderInflight = void 0;
|
|
565
|
+
/**
|
|
566
|
+
* Called as observer(error, carriedScopePath) for every 400 answer.
|
|
567
|
+
* `carriedScopePath` says whether the refused request named a scope path,
|
|
568
|
+
* which is how the client learns its cached ladder may be stale. Never
|
|
569
|
+
* allowed to throw.
|
|
570
|
+
*/
|
|
571
|
+
onInvalidInput = void 0;
|
|
572
|
+
/**
|
|
573
|
+
* A 400 answered a call that carried a scope path: the ladder we hold may be
|
|
574
|
+
* stale. The next read is at most one per LADDER_INVALIDATION_MIN_INTERVAL_MS,
|
|
575
|
+
* the last known ladder stays as the answer if it fails, and a read already
|
|
576
|
+
* in flight will not be stored.
|
|
577
|
+
*
|
|
578
|
+
* The server's refusal wording is deliberately not inspected. The gRPC
|
|
579
|
+
* stream does not surface HTTP 400, so a ladder error on the stream is not
|
|
580
|
+
* observed here.
|
|
581
|
+
*/
|
|
582
|
+
invalidateScopeLadder() {
|
|
583
|
+
this.#ladderGeneration += 1;
|
|
584
|
+
this.#ladderInvalidated = true;
|
|
585
|
+
this.#ladderRetryAt = 0;
|
|
586
|
+
}
|
|
587
|
+
/** The ladder already held, or null when none has been read. Makes no request. */
|
|
588
|
+
cachedScopeLadder() {
|
|
589
|
+
return this.#ladderLoaded ? this.#ladder : null;
|
|
590
|
+
}
|
|
591
|
+
/**
|
|
592
|
+
* The account's ladder, from whoami, cached for 300 s (`null` included).
|
|
593
|
+
* Concurrent callers share one read. A failed re-read after expiry keeps the
|
|
594
|
+
* last known ladder (with a warning) and waits 60 s before trying again. A
|
|
595
|
+
* failure on the first read, or with `refresh`, is thrown.
|
|
596
|
+
*/
|
|
597
|
+
async getScopeLadder(refresh, warn) {
|
|
598
|
+
const now = this.clock();
|
|
599
|
+
const cached2 = this.#ladder;
|
|
600
|
+
const loaded = this.#ladderLoaded;
|
|
601
|
+
if (!refresh && loaded) {
|
|
602
|
+
if (now < this.#ladderRetryAt) return cached2;
|
|
603
|
+
if (this.#ladderInvalidated) {
|
|
604
|
+
if (now < this.#ladderInvalidationReadAt + LADDER_INVALIDATION_MIN_INTERVAL_MS) return cached2;
|
|
605
|
+
} else if (now < this.#ladderExpiresAt) {
|
|
606
|
+
return cached2;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
const keepOnFailure = loaded && !refresh;
|
|
610
|
+
const inflight = this.#ladderInflight;
|
|
611
|
+
if (inflight !== void 0 && inflight.generation === this.#ladderGeneration && inflight.keepOnFailure === keepOnFailure) {
|
|
612
|
+
return inflight.promise;
|
|
613
|
+
}
|
|
614
|
+
const generation = this.#ladderGeneration;
|
|
615
|
+
if (this.#ladderInvalidated && !refresh) this.#ladderInvalidationReadAt = now;
|
|
616
|
+
const promise = this.#readScopeLadder(now, generation, cached2, keepOnFailure, warn);
|
|
617
|
+
const entry = { promise, generation, keepOnFailure };
|
|
618
|
+
this.#ladderInflight = entry;
|
|
619
|
+
const clear = () => {
|
|
620
|
+
if (this.#ladderInflight === entry) this.#ladderInflight = void 0;
|
|
621
|
+
};
|
|
622
|
+
promise.then(clear, clear);
|
|
623
|
+
return promise;
|
|
624
|
+
}
|
|
625
|
+
async #readScopeLadder(now, generation, cached2, keepOnFailure, warn) {
|
|
626
|
+
let whoami;
|
|
627
|
+
try {
|
|
628
|
+
const raw = await this.request("whoami", {});
|
|
629
|
+
whoami = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
|
|
630
|
+
} catch (error) {
|
|
631
|
+
if (keepOnFailure) {
|
|
632
|
+
warn(
|
|
633
|
+
`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.`
|
|
634
|
+
);
|
|
635
|
+
this.#ladderRetryAt = now + LADDER_RETRY_BACKOFF_MS;
|
|
636
|
+
return cached2;
|
|
637
|
+
}
|
|
638
|
+
throw error;
|
|
639
|
+
}
|
|
640
|
+
const ladder = ladderFromWhoami(whoami, this.userContextIsolation, warn);
|
|
641
|
+
if (generation === this.#ladderGeneration) {
|
|
642
|
+
this.#ladder = ladder;
|
|
643
|
+
this.#ladderLoaded = true;
|
|
644
|
+
this.#ladderExpiresAt = now + LADDER_TTL_MS;
|
|
645
|
+
this.#ladderRetryAt = 0;
|
|
646
|
+
this.#ladderInvalidated = false;
|
|
647
|
+
}
|
|
648
|
+
return ladder;
|
|
649
|
+
}
|
|
330
650
|
/**
|
|
331
651
|
* Set by the client to its identity resolution (`initialize()`'s whoami).
|
|
332
652
|
* Python refuses every call before `initialize()`; here the first request
|
|
@@ -457,6 +777,12 @@ var HttpTransport = class {
|
|
|
457
777
|
}
|
|
458
778
|
if (!response.ok) {
|
|
459
779
|
const error = await toHttpError(response, correlationId);
|
|
780
|
+
if (response.status === 400 && error instanceof InvalidInputError) {
|
|
781
|
+
try {
|
|
782
|
+
this.onInvalidInput?.(error, carriesScopePath(options.body));
|
|
783
|
+
} catch {
|
|
784
|
+
}
|
|
785
|
+
}
|
|
460
786
|
throw options.mapError?.(response.status, error) ?? error;
|
|
461
787
|
}
|
|
462
788
|
if (response.status === 204) return void 0;
|
|
@@ -554,6 +880,38 @@ function creditReason(payload) {
|
|
|
554
880
|
const error = stringOrNull(payload["error"]);
|
|
555
881
|
return error !== null && CREDIT_ERRORS.has(error) ? error : null;
|
|
556
882
|
}
|
|
883
|
+
function isScopePath(value) {
|
|
884
|
+
let v = value;
|
|
885
|
+
if (typeof v === "string" && v.trimStart().startsWith("{")) {
|
|
886
|
+
try {
|
|
887
|
+
v = JSON.parse(v);
|
|
888
|
+
} catch {
|
|
889
|
+
return false;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
return typeof v === "object" && v !== null && !Array.isArray(v) && Object.keys(v).length > 0;
|
|
893
|
+
}
|
|
894
|
+
function carriesScopePath(body) {
|
|
895
|
+
if (typeof FormData !== "undefined" && body instanceof FormData) {
|
|
896
|
+
if (isScopePath(body.get("scope"))) return true;
|
|
897
|
+
const manifest = body.get("manifest");
|
|
898
|
+
if (typeof manifest === "string") {
|
|
899
|
+
try {
|
|
900
|
+
const parsed = JSON.parse(manifest);
|
|
901
|
+
return typeof parsed === "object" && parsed !== null && isScopePath(parsed["scope"]);
|
|
902
|
+
} catch {
|
|
903
|
+
return false;
|
|
904
|
+
}
|
|
905
|
+
}
|
|
906
|
+
return false;
|
|
907
|
+
}
|
|
908
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) return false;
|
|
909
|
+
const o2 = body;
|
|
910
|
+
if (isScopePath(o2["scope"])) return true;
|
|
911
|
+
return Object.values(o2).some(
|
|
912
|
+
(v) => Array.isArray(v) && v.some((i) => typeof i === "object" && i !== null && isScopePath(i["scope"]))
|
|
913
|
+
);
|
|
914
|
+
}
|
|
557
915
|
async function toHttpError(response, correlationId) {
|
|
558
916
|
const body = await response.text().catch(() => "");
|
|
559
917
|
let parsed = {};
|
|
@@ -2455,6 +2813,68 @@ function createCreditsNamespace(transport) {
|
|
|
2455
2813
|
};
|
|
2456
2814
|
}
|
|
2457
2815
|
|
|
2816
|
+
// src/maca/interface.ts
|
|
2817
|
+
var MACA_FINAL_STATUSES = ["succeeded", "invalid", "failed"];
|
|
2818
|
+
var MACA_MAX_FILE_BYTES = 256 * 1024;
|
|
2819
|
+
function toJob(raw) {
|
|
2820
|
+
return {
|
|
2821
|
+
job_id: String(raw["job_id"]),
|
|
2822
|
+
status: String(raw["status"]),
|
|
2823
|
+
message: typeof raw["message"] === "string" ? raw["message"] : "",
|
|
2824
|
+
created_at: typeof raw["created_at"] === "string" ? raw["created_at"] : null,
|
|
2825
|
+
updated_at: typeof raw["updated_at"] === "string" ? raw["updated_at"] : null,
|
|
2826
|
+
removed_fields: Array.isArray(raw["removed_fields"]) ? raw["removed_fields"] : [],
|
|
2827
|
+
problems: Array.isArray(raw["problems"]) ? raw["problems"] : [],
|
|
2828
|
+
config_file: typeof raw["config_file"] === "string" ? raw["config_file"] : null,
|
|
2829
|
+
yaml: typeof raw["yaml"] === "string" ? raw["yaml"] : null
|
|
2830
|
+
};
|
|
2831
|
+
}
|
|
2832
|
+
function createMacaNamespace(transport) {
|
|
2833
|
+
const namespace = {
|
|
2834
|
+
async generate(options) {
|
|
2835
|
+
const filePath = options.file_path ?? options.filePath;
|
|
2836
|
+
const relationship = options.user_relationship ?? options.userRelationship;
|
|
2837
|
+
if (relationship !== "b2c" && relationship !== "b2b") {
|
|
2838
|
+
throw new InvalidInputError("user_relationship must be 'b2c' or 'b2b'");
|
|
2839
|
+
}
|
|
2840
|
+
if (typeof filePath !== "string" || !filePath) throw new InvalidInputError("file_path is required");
|
|
2841
|
+
const { readFile, stat } = await import("fs/promises");
|
|
2842
|
+
const { basename } = await import("path");
|
|
2843
|
+
let size;
|
|
2844
|
+
try {
|
|
2845
|
+
size = (await stat(filePath)).size;
|
|
2846
|
+
} catch {
|
|
2847
|
+
throw new InvalidInputError(`file_path does not point to a readable file: ${filePath}`);
|
|
2848
|
+
}
|
|
2849
|
+
if (size === 0) throw new InvalidInputError("The use-case file is empty");
|
|
2850
|
+
if (size > MACA_MAX_FILE_BYTES) {
|
|
2851
|
+
throw new InvalidInputError(`The use-case file is larger than ${MACA_MAX_FILE_BYTES / 1024} KB`);
|
|
2852
|
+
}
|
|
2853
|
+
const bytes = await readFile(filePath);
|
|
2854
|
+
const form = new FormData();
|
|
2855
|
+
form.set("user_relationship", relationship);
|
|
2856
|
+
form.set("file", new Blob([bytes]), basename(filePath));
|
|
2857
|
+
return toJob(await transport.request("maca_generate", { body: form, rawBody: true }));
|
|
2858
|
+
},
|
|
2859
|
+
async get_job(jobId) {
|
|
2860
|
+
if (!jobId) throw new InvalidInputError("job_id is required");
|
|
2861
|
+
return toJob(await transport.request("maca_job", { pathParams: { job_id: jobId } }));
|
|
2862
|
+
},
|
|
2863
|
+
async wait_for_completion(jobId, options = {}) {
|
|
2864
|
+
const timeout = (options.timeout_seconds ?? options.timeoutSeconds ?? 3e3) * 1e3;
|
|
2865
|
+
const interval = (options.poll_interval_seconds ?? options.pollIntervalSeconds ?? 15) * 1e3;
|
|
2866
|
+
const start = Date.now();
|
|
2867
|
+
while (Date.now() - start < timeout) {
|
|
2868
|
+
const job = await namespace.get_job(jobId);
|
|
2869
|
+
if (MACA_FINAL_STATUSES.includes(job.status)) return job;
|
|
2870
|
+
await new Promise((resolve) => setTimeout(resolve, interval));
|
|
2871
|
+
}
|
|
2872
|
+
throw new Error(`MACA job ${jobId} did not finish within ${timeout / 1e3}s`);
|
|
2873
|
+
}
|
|
2874
|
+
};
|
|
2875
|
+
return namespace;
|
|
2876
|
+
}
|
|
2877
|
+
|
|
2458
2878
|
// src/cache/interface.ts
|
|
2459
2879
|
function createCacheNamespace(cache) {
|
|
2460
2880
|
return {
|
|
@@ -2619,7 +3039,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
|
|
|
2619
3039
|
onListen?.();
|
|
2620
3040
|
} catch {
|
|
2621
3041
|
}
|
|
2622
|
-
const { GrpcStreamClient } = await import("./stream-client-
|
|
3042
|
+
const { GrpcStreamClient } = await import("./stream-client-7A2DQ3H3.js");
|
|
2623
3043
|
const onContext = options.on_context ?? options.onContext;
|
|
2624
3044
|
const onDisconnect = options.on_disconnect ?? options.onDisconnect;
|
|
2625
3045
|
const onReconnect = options.on_reconnect ?? options.onReconnect;
|
|
@@ -2835,7 +3255,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
|
|
|
2835
3255
|
}
|
|
2836
3256
|
|
|
2837
3257
|
// src/version.ts
|
|
2838
|
-
var SDK_VERSION = "0.
|
|
3258
|
+
var SDK_VERSION = "0.7.1";
|
|
2839
3259
|
|
|
2840
3260
|
// src/registry.ts
|
|
2841
3261
|
var instances = /* @__PURE__ */ new Map();
|
|
@@ -4437,7 +4857,8 @@ function toolInputSchema(scope, options) {
|
|
|
4437
4857
|
}
|
|
4438
4858
|
var RESULT_COLLECTIONS = ["facts", "preferences", "episodes", "emotions", "temporal_events"];
|
|
4439
4859
|
async function invokeScopeFetch(params) {
|
|
4440
|
-
const { target, scope, userId, customerId, conversationId, callArgs } = params;
|
|
4860
|
+
const { target, scope, userId, customerId, conversationId, callArgs, scopePath } = params;
|
|
4861
|
+
const pathOpt = scopePath !== void 0 && scopePath !== null && Object.keys(scopePath).length > 0 ? { scope_path: scopePath } : {};
|
|
4441
4862
|
const searchQuery = callArgs["search_query"];
|
|
4442
4863
|
const rawMax = callArgs["max_results"];
|
|
4443
4864
|
const maxResults = typeof rawMax === "number" && rawMax !== 0 ? Math.trunc(rawMax) : 10;
|
|
@@ -4450,7 +4871,8 @@ async function invokeScopeFetch(params) {
|
|
|
4450
4871
|
max_results: maxResults,
|
|
4451
4872
|
types,
|
|
4452
4873
|
mode,
|
|
4453
|
-
precision_level: precisionLevel
|
|
4874
|
+
precision_level: precisionLevel,
|
|
4875
|
+
...pathOpt
|
|
4454
4876
|
};
|
|
4455
4877
|
if (scope === "unified") {
|
|
4456
4878
|
const response2 = await target.fetch({
|
|
@@ -4530,7 +4952,15 @@ function buildTool(target, options = {}, onWarning = () => {
|
|
|
4530
4952
|
const toolName = options.name ?? `synap_fetch_${scope}_context`;
|
|
4531
4953
|
const toolDesc = options.description ?? defaultToolDescription(scope);
|
|
4532
4954
|
const schema = toolInputSchema(scope, { hasConversationId: conversationId !== void 0 });
|
|
4533
|
-
const handler = (callArgs = {}) => invokeScopeFetch({
|
|
4955
|
+
const handler = (callArgs = {}) => invokeScopeFetch({
|
|
4956
|
+
target,
|
|
4957
|
+
scope,
|
|
4958
|
+
userId,
|
|
4959
|
+
customerId,
|
|
4960
|
+
conversationId,
|
|
4961
|
+
callArgs,
|
|
4962
|
+
scopePath: options.scope_path
|
|
4963
|
+
});
|
|
4534
4964
|
if (style === "openai") {
|
|
4535
4965
|
return {
|
|
4536
4966
|
type: "function",
|
|
@@ -4565,6 +4995,7 @@ var SynapClient = class _SynapClient {
|
|
|
4565
4995
|
memories;
|
|
4566
4996
|
data;
|
|
4567
4997
|
credits;
|
|
4998
|
+
maca;
|
|
4568
4999
|
cache;
|
|
4569
5000
|
instance;
|
|
4570
5001
|
#closed = false;
|
|
@@ -4620,10 +5051,14 @@ var SynapClient = class _SynapClient {
|
|
|
4620
5051
|
...options.retryPolicy !== void 0 ? { retryPolicy: options.retryPolicy } : {},
|
|
4621
5052
|
...options.keepAlive !== void 0 ? { keepAlive: options.keepAlive } : {},
|
|
4622
5053
|
...options.fetchImpl !== void 0 ? { fetchImpl: options.fetchImpl } : {},
|
|
5054
|
+
...options._clock !== void 0 ? { clock: options._clock } : {},
|
|
4623
5055
|
userAgent: `@maximem/synap-js-sdk/${SDK_VERSION}`
|
|
4624
5056
|
});
|
|
4625
5057
|
if (options.heartbeat) this.#transport.startHeartbeat();
|
|
4626
5058
|
this.#transport.identityResolver = () => this.#resolveIdentity();
|
|
5059
|
+
this.#transport.onInvalidInput = (_error, carriedScopePath) => {
|
|
5060
|
+
if (carriedScopePath) this.#transport.invalidateScopeLadder();
|
|
5061
|
+
};
|
|
4627
5062
|
this.#anticipationCache = new AnticipationCache();
|
|
4628
5063
|
this.#fetchHooks = {
|
|
4629
5064
|
beforeFetch: async (scope, options2) => {
|
|
@@ -4793,6 +5228,7 @@ var SynapClient = class _SynapClient {
|
|
|
4793
5228
|
return cleared;
|
|
4794
5229
|
});
|
|
4795
5230
|
this.credits = createCreditsNamespace(this.#transport);
|
|
5231
|
+
this.maca = createMacaNamespace(this.#transport);
|
|
4796
5232
|
this.cache = createCacheNamespace(this.#anticipationCache);
|
|
4797
5233
|
this.instance = createInstanceNamespace(
|
|
4798
5234
|
() => this.#transport.currentCredentials(),
|
|
@@ -4923,6 +5359,25 @@ var SynapClient = class _SynapClient {
|
|
|
4923
5359
|
this.#initialized = true;
|
|
4924
5360
|
await this.#resolveIdentity();
|
|
4925
5361
|
}
|
|
5362
|
+
/**
|
|
5363
|
+
* The account's scope ladder, or `null` when it cannot be known.
|
|
5364
|
+
*
|
|
5365
|
+
* Mirrors Python's `get_scope_ladder()`. Read lazily from
|
|
5366
|
+
* `GET /api/v1/auth/whoami` (even when the client and instance ids are
|
|
5367
|
+
* already known), cached for 300 s (`null` included), re-read on `refresh: true`. Concurrent
|
|
5368
|
+
* callers share one read. If a re-read
|
|
5369
|
+
* after expiry fails, the last known ladder is returned with a warning and
|
|
5370
|
+
* the next try waits 60 s. A failure on the very first read, or with
|
|
5371
|
+
* `refresh`, is thrown. With no `scope_ladder` block the default ladder is
|
|
5372
|
+
* inferred from `user_context_isolation` (`source: "inferred"`).
|
|
5373
|
+
*
|
|
5374
|
+
* const ladder = await client.get_scope_ladder();
|
|
5375
|
+
* const addr = ladder!.address(['acme', 'payments', 'dana']);
|
|
5376
|
+
* await client.fetch({ search_query: ['...'], ...addr.read_kwargs() });
|
|
5377
|
+
*/
|
|
5378
|
+
async get_scope_ladder(options = {}) {
|
|
5379
|
+
return this.#transport.getScopeLadder(options.refresh === true, (m) => this.#warn(m));
|
|
5380
|
+
}
|
|
4926
5381
|
/** Runs whoami at most once, however many calls arrive together. */
|
|
4927
5382
|
#resolveIdentity() {
|
|
4928
5383
|
this.#identity ??= this.#whoami().catch((error) => {
|
|
@@ -5049,7 +5504,8 @@ var SynapClient = class _SynapClient {
|
|
|
5049
5504
|
context_mode: contextMode = "in-conversation",
|
|
5050
5505
|
include_profile: includeProfile = true,
|
|
5051
5506
|
last_n_conversations: lastNConversations = 1,
|
|
5052
|
-
response_shape: responseShape = "by_type"
|
|
5507
|
+
response_shape: responseShape = "by_type",
|
|
5508
|
+
scope_path: scopePath
|
|
5053
5509
|
} = options;
|
|
5054
5510
|
await this.#transport.checkCustomerId(customerId, "sdk.fetch");
|
|
5055
5511
|
validateConversationId(conversationId);
|
|
@@ -5066,8 +5522,24 @@ var SynapClient = class _SynapClient {
|
|
|
5066
5522
|
// sits one indent deeper; spreading removes that whole class of miss.
|
|
5067
5523
|
query_date: queryDate,
|
|
5068
5524
|
max_results_per_query: maxResultsPerQuery,
|
|
5069
|
-
response_shape: responseShape
|
|
5525
|
+
response_shape: responseShape,
|
|
5526
|
+
// Forwarded only when set (Python: `if scope_path`), so a call without
|
|
5527
|
+
// one hands every scope fetch exactly the options it always got.
|
|
5528
|
+
...scopePath !== void 0 && scopePath !== null && Object.keys(scopePath).length > 0 ? { scope_path: scopePath } : {}
|
|
5070
5529
|
};
|
|
5530
|
+
const { scope_path: _fullPath, ...sharedNoPath } = shared;
|
|
5531
|
+
void _fullPath;
|
|
5532
|
+
let customerPath;
|
|
5533
|
+
if (scopePath && Object.keys(scopePath).length > 0 && customerId !== void 0 && customerId !== null && customerId !== "" && wants("customer")) {
|
|
5534
|
+
let ladder = null;
|
|
5535
|
+
try {
|
|
5536
|
+
ladder = await this.get_scope_ladder();
|
|
5537
|
+
} catch (e) {
|
|
5538
|
+
this.#warn(`Could not read the scope ladder (${e instanceof Error ? e.message : String(e)}); cutting the customer scope's path at the reserved key 'user'.`);
|
|
5539
|
+
}
|
|
5540
|
+
customerPath = pathAboveIdentity(scopePath, ladder);
|
|
5541
|
+
}
|
|
5542
|
+
const customerShared = customerPath ? { ...sharedNoPath, scope_path: customerPath } : sharedNoPath;
|
|
5071
5543
|
const labels = [];
|
|
5072
5544
|
const tasks = [];
|
|
5073
5545
|
const present = (v) => v !== void 0 && v !== null && v !== "";
|
|
@@ -5099,14 +5571,14 @@ var SynapClient = class _SynapClient {
|
|
|
5099
5571
|
tasks.push(this.customer.context.fetch({
|
|
5100
5572
|
customer_id: customerId,
|
|
5101
5573
|
conversation_id: conversationId,
|
|
5102
|
-
...
|
|
5574
|
+
...customerShared
|
|
5103
5575
|
}));
|
|
5104
5576
|
}
|
|
5105
5577
|
if (scopes !== void 0 && scopes.includes("client")) {
|
|
5106
5578
|
labels.push("client");
|
|
5107
5579
|
tasks.push(this.client.context.fetch({
|
|
5108
5580
|
conversation_id: conversationId,
|
|
5109
|
-
...
|
|
5581
|
+
...sharedNoPath
|
|
5110
5582
|
}));
|
|
5111
5583
|
}
|
|
5112
5584
|
if (tasks.length === 0 && !(conversationState && includeConversationContext)) {
|
|
@@ -5483,6 +5955,9 @@ export {
|
|
|
5483
5955
|
RateLimitError,
|
|
5484
5956
|
SDKError,
|
|
5485
5957
|
SDK_VERSION,
|
|
5958
|
+
ScopeAddress,
|
|
5959
|
+
ScopeLadder,
|
|
5960
|
+
ScopeLadderError,
|
|
5486
5961
|
ServiceUnavailableError,
|
|
5487
5962
|
SessionExpiredError,
|
|
5488
5963
|
SynapClient,
|