@maximem/synap-js-sdk 0.7.0 → 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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/Users/scaler/wt_sl_publish/synap/sdk/js/dist/grpc/index.cjs","../../src/grpc/index.ts"],"names":[],"mappings":"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","file":"/Users/scaler/wt_sl_publish/synap/sdk/js/dist/grpc/index.cjs","sourcesContent":[null,"/**\n * gRPC anticipation stream: availability and loading.\n *\n * This is a SUBPATH export (`@maximem/synap-js-sdk/grpc`) and is never\n * imported by the main entry point. Three reasons, all of which have bitten\n * someone already:\n *\n * 1. `@grpc/grpc-js` plus its protos is roughly 5MB. HTTP-only and Edge users\n * should not pay for it (gotcha G-Q).\n * 2. grpc-js is built on `node:http2`, `node:net` and `node:tls`. Merely\n * importing it on Edge or Workers fails the *build*, not the call. Keeping\n * it behind a subpath plus a lazy `import()` means importing the SDK on\n * Edge stays safe.\n * 3. It is an `optionalDependency`, so it may legitimately be absent.\n *\n * ## Proto loading\n *\n * The stream is live. The proto ships as an INLINED JSON descriptor\n * (./descriptor.ts) loaded through `proto-loader.fromJSON`, not through\n * `loadSync(path)`. proto-loader's file-based path reads the `.proto` off disk\n * at runtime, which breaks under webpack/turbopack bundling and Vercel's `nft`\n * file tracing: at deploy time rather than at test time (gotcha G-P). Inlining\n * gets the same result as ts-proto codegen without a codegen toolchain.\n */\n\nimport { ListeningNotActiveError } from '../errors.js';\nexport { GrpcStreamClient } from './stream-client.js';\nexport type {\n StreamState, StreamCredentials, StreamClientOptions, ConversationEventInput,\n} from './stream-client.js';\nexport { PROTO_SHA } from './descriptor.js';\n\nexport type GrpcAvailability =\n | { available: true }\n | { available: false; reason: 'not-node' | 'module-missing'; detail: string };\n\n/**\n * Whether a gRPC stream could run here.\n *\n * Deliberately does not throw: callers use this to decide whether to offer the\n * stream at all, and a hard failure at that point is unhelpful.\n */\nexport async function checkGrpcAvailability(): Promise<GrpcAvailability> {\n const isNode =\n typeof process !== 'undefined' &&\n process.versions?.node !== undefined &&\n typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime === 'undefined';\n\n if (!isNode) {\n return {\n available: false,\n reason: 'not-node',\n detail:\n 'gRPC needs raw TCP and node:http2, which Edge runtimes and Workers do ' +\n 'not provide. HTTP context fetching works normally here; only the ' +\n 'anticipation stream is unavailable. Reaching Edge would require a ' +\n 'gRPC-Web or Connect endpoint on the server, which does not exist yet.',\n };\n }\n\n try {\n await import(/* @vite-ignore */ '@grpc/grpc-js');\n return { available: true };\n } catch (error) {\n return {\n available: false,\n reason: 'module-missing',\n detail:\n '@grpc/grpc-js is an optional dependency and is not installed. Run ' +\n '`npm install @grpc/grpc-js` to enable the anticipation stream. ' +\n `(${(error as Error)?.message ?? String(error)})`,\n };\n }\n}\n\nexport interface ListenOptions {\n conversationId: string;\n userId?: string;\n customerId?: string;\n onBundle?: (bundle: unknown) => void;\n}\n\nexport interface ListeningSession {\n stop(): Promise<void>;\n readonly active: boolean;\n}\n\n/**\n * Start the anticipation stream directly, without a SynapClient.\n *\n * Most callers want `client.instance.listen()` instead, which shares the\n * client's credentials and anticipation cache. This exists for the case where\n * only the stream is wanted.\n *\n * **Opt-in, and off by default.** The removed wrapper called `listen()`\n * unconditionally during init, so every user had a stream whether they asked\n * for one or not. Making it opt-in is the right default, but it is not a\n * neutral change: fewer streams means fewer anticipation hits and therefore\n * MORE billed cloud fetches for existing users. That has to be announced\n * rather than discovered (gotcha G-Y).\n */\nexport async function listen(\n options: ListenOptions & {\n apiKey?: string;\n clientId?: string;\n instanceId?: string;\n host?: string;\n port?: number;\n useTls?: boolean;\n },\n): Promise<ListeningSession> {\n if (!options.conversationId) {\n // conversation_id is not a scope tier, but the stream genuinely requires\n // one: it is what the server keys the anticipation session on.\n throw new ListeningNotActiveError('conversation_id is required to start a listening stream');\n }\n\n const availability = await checkGrpcAvailability();\n if (!availability.available) {\n throw new ListeningNotActiveError(availability.detail);\n }\n\n const [{ GrpcStreamClient: StreamClient }, { AnticipationCache }, { getEnv }] = await Promise.all([\n import('./stream-client.js'),\n import('../context/anticipation-cache.js'),\n import('../util/env.js'),\n ]);\n\n const apiKey = options.apiKey ?? getEnv('SYNAP_API_KEY') ?? '';\n if (apiKey === '') {\n throw new ListeningNotActiveError(\n 'No Synap API key found. Set SYNAP_API_KEY or pass apiKey.',\n );\n }\n\n const cache = new AnticipationCache();\n const client = new StreamClient(\n {\n apiKey,\n clientId: options.clientId ?? getEnv('SYNAP_CLIENT_ID') ?? '',\n instanceId: options.instanceId ?? getEnv('SYNAP_INSTANCE_ID') ?? '',\n },\n cache,\n {\n ...(options.host !== undefined ? { host: options.host } : {}),\n ...(options.port !== undefined ? { port: options.port } : {}),\n ...(options.useTls !== undefined ? { useTls: options.useTls } : {}),\n ...(options.onBundle !== undefined ? { onContext: options.onBundle } : {}),\n },\n );\n await client.connect();\n client.sendSessionControl({\n action: 'start',\n conversation_id: options.conversationId,\n ...(options.userId !== undefined ? { user_id: options.userId } : {}),\n ...(options.customerId !== undefined ? { customer_id: options.customerId } : {}),\n });\n\n return {\n stop: () => client.disconnect(),\n get active() { return client.isConnected; },\n };\n}\n"]}
1
+ {"version":3,"sources":["/Users/scaler/wt_sl_wave2/synap/sdk/js/dist/grpc/index.cjs","../../src/grpc/index.ts"],"names":[],"mappings":"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","file":"/Users/scaler/wt_sl_wave2/synap/sdk/js/dist/grpc/index.cjs","sourcesContent":[null,"/**\n * gRPC anticipation stream: availability and loading.\n *\n * This is a SUBPATH export (`@maximem/synap-js-sdk/grpc`) and is never\n * imported by the main entry point. Three reasons, all of which have bitten\n * someone already:\n *\n * 1. `@grpc/grpc-js` plus its protos is roughly 5MB. HTTP-only and Edge users\n * should not pay for it (gotcha G-Q).\n * 2. grpc-js is built on `node:http2`, `node:net` and `node:tls`. Merely\n * importing it on Edge or Workers fails the *build*, not the call. Keeping\n * it behind a subpath plus a lazy `import()` means importing the SDK on\n * Edge stays safe.\n * 3. It is an `optionalDependency`, so it may legitimately be absent.\n *\n * ## Proto loading\n *\n * The stream is live. The proto ships as an INLINED JSON descriptor\n * (./descriptor.ts) loaded through `proto-loader.fromJSON`, not through\n * `loadSync(path)`. proto-loader's file-based path reads the `.proto` off disk\n * at runtime, which breaks under webpack/turbopack bundling and Vercel's `nft`\n * file tracing: at deploy time rather than at test time (gotcha G-P). Inlining\n * gets the same result as ts-proto codegen without a codegen toolchain.\n */\n\nimport { ListeningNotActiveError } from '../errors.js';\nexport { GrpcStreamClient } from './stream-client.js';\nexport type {\n StreamState, StreamCredentials, StreamClientOptions, ConversationEventInput,\n} from './stream-client.js';\nexport { PROTO_SHA } from './descriptor.js';\n\nexport type GrpcAvailability =\n | { available: true }\n | { available: false; reason: 'not-node' | 'module-missing'; detail: string };\n\n/**\n * Whether a gRPC stream could run here.\n *\n * Deliberately does not throw: callers use this to decide whether to offer the\n * stream at all, and a hard failure at that point is unhelpful.\n */\nexport async function checkGrpcAvailability(): Promise<GrpcAvailability> {\n const isNode =\n typeof process !== 'undefined' &&\n process.versions?.node !== undefined &&\n typeof (globalThis as { EdgeRuntime?: unknown }).EdgeRuntime === 'undefined';\n\n if (!isNode) {\n return {\n available: false,\n reason: 'not-node',\n detail:\n 'gRPC needs raw TCP and node:http2, which Edge runtimes and Workers do ' +\n 'not provide. HTTP context fetching works normally here; only the ' +\n 'anticipation stream is unavailable. Reaching Edge would require a ' +\n 'gRPC-Web or Connect endpoint on the server, which does not exist yet.',\n };\n }\n\n try {\n await import(/* @vite-ignore */ '@grpc/grpc-js');\n return { available: true };\n } catch (error) {\n return {\n available: false,\n reason: 'module-missing',\n detail:\n '@grpc/grpc-js is an optional dependency and is not installed. Run ' +\n '`npm install @grpc/grpc-js` to enable the anticipation stream. ' +\n `(${(error as Error)?.message ?? String(error)})`,\n };\n }\n}\n\nexport interface ListenOptions {\n conversationId: string;\n userId?: string;\n customerId?: string;\n onBundle?: (bundle: unknown) => void;\n}\n\nexport interface ListeningSession {\n stop(): Promise<void>;\n readonly active: boolean;\n}\n\n/**\n * Start the anticipation stream directly, without a SynapClient.\n *\n * Most callers want `client.instance.listen()` instead, which shares the\n * client's credentials and anticipation cache. This exists for the case where\n * only the stream is wanted.\n *\n * **Opt-in, and off by default.** The removed wrapper called `listen()`\n * unconditionally during init, so every user had a stream whether they asked\n * for one or not. Making it opt-in is the right default, but it is not a\n * neutral change: fewer streams means fewer anticipation hits and therefore\n * MORE billed cloud fetches for existing users. That has to be announced\n * rather than discovered (gotcha G-Y).\n */\nexport async function listen(\n options: ListenOptions & {\n apiKey?: string;\n clientId?: string;\n instanceId?: string;\n host?: string;\n port?: number;\n useTls?: boolean;\n },\n): Promise<ListeningSession> {\n if (!options.conversationId) {\n // conversation_id is not a scope tier, but the stream genuinely requires\n // one: it is what the server keys the anticipation session on.\n throw new ListeningNotActiveError('conversation_id is required to start a listening stream');\n }\n\n const availability = await checkGrpcAvailability();\n if (!availability.available) {\n throw new ListeningNotActiveError(availability.detail);\n }\n\n const [{ GrpcStreamClient: StreamClient }, { AnticipationCache }, { getEnv }] = await Promise.all([\n import('./stream-client.js'),\n import('../context/anticipation-cache.js'),\n import('../util/env.js'),\n ]);\n\n const apiKey = options.apiKey ?? getEnv('SYNAP_API_KEY') ?? '';\n if (apiKey === '') {\n throw new ListeningNotActiveError(\n 'No Synap API key found. Set SYNAP_API_KEY or pass apiKey.',\n );\n }\n\n const cache = new AnticipationCache();\n const client = new StreamClient(\n {\n apiKey,\n clientId: options.clientId ?? getEnv('SYNAP_CLIENT_ID') ?? '',\n instanceId: options.instanceId ?? getEnv('SYNAP_INSTANCE_ID') ?? '',\n },\n cache,\n {\n ...(options.host !== undefined ? { host: options.host } : {}),\n ...(options.port !== undefined ? { port: options.port } : {}),\n ...(options.useTls !== undefined ? { useTls: options.useTls } : {}),\n ...(options.onBundle !== undefined ? { onContext: options.onBundle } : {}),\n },\n );\n await client.connect();\n client.sendSessionControl({\n action: 'start',\n conversation_id: options.conversationId,\n ...(options.userId !== undefined ? { user_id: options.userId } : {}),\n ...(options.customerId !== undefined ? { customer_id: options.customerId } : {}),\n });\n\n return {\n stop: () => client.disconnect(),\n get active() { return client.isConnected; },\n };\n}\n"]}
package/dist/index.cjs CHANGED
@@ -232,7 +232,16 @@ var ScopeAddress = class {
232
232
  this.customer_id = _nullishCoalesce(init.customer_id, () => ( null));
233
233
  this.scope_path = _nullishCoalesce(init.scope_path, () => ( null));
234
234
  }
235
- /** Options for reads (`fetch`, `*.context.fetch`, `send_message`, ...): the path is `scope_path`. */
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
+ */
236
245
  read_kwargs() {
237
246
  const out = {};
238
247
  if (this.user_id) out.user_id = this.user_id;
@@ -253,6 +262,21 @@ var ScopeAddress = class {
253
262
  return out;
254
263
  }
255
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 = _optionalChain([ladder, 'optionalAccess', _9 => _9.levels, 'access', _10 => _10.find, 'call', _11 => _11((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 ((_nullishCoalesce(position.get(k), () => ( -1))) < identity.position) out[k] = v;
276
+ }
277
+ }
278
+ return Object.keys(out).length > 0 ? out : void 0;
279
+ }
256
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.";
257
281
  var ScopeLadder = class {
258
282
 
@@ -473,7 +497,7 @@ var HttpTransport = (_class2 = class {
473
497
  this.keepAliveOptions = _nullishCoalesce(options.keepAlive, () => ( {}));
474
498
  this.heartbeat = new Heartbeat(
475
499
  () => this.pingHealth(),
476
- _nullishCoalesce(_optionalChain([options, 'access', _9 => _9.keepAlive, 'optionalAccess', _10 => _10.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
500
+ _nullishCoalesce(_optionalChain([options, 'access', _12 => _12.keepAlive, 'optionalAccess', _13 => _13.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
477
501
  );
478
502
  }
479
503
  /**
@@ -560,6 +584,10 @@ var HttpTransport = (_class2 = class {
560
584
  this.#ladderInvalidated = true;
561
585
  this.#ladderRetryAt = 0;
562
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
+ }
563
591
  /**
564
592
  * The account's ladder, from whoami, cached for 300 s (`null` included).
565
593
  * Concurrent callers share one read. A failed re-read after expiry keeps the
@@ -602,7 +630,7 @@ var HttpTransport = (_class2 = class {
602
630
  } catch (error) {
603
631
  if (keepOnFailure) {
604
632
  warn(
605
- `Could not re-read the scope ladder (${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _11 => _11.message]), () => ( String(error)))}); keeping the last known one and retrying in ${LADDER_RETRY_BACKOFF_MS / 1e3}s.`
633
+ `Could not re-read the scope ladder (${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _14 => _14.message]), () => ( String(error)))}); keeping the last known one and retrying in ${LADDER_RETRY_BACKOFF_MS / 1e3}s.`
606
634
  );
607
635
  this.#ladderRetryAt = now + LADDER_RETRY_BACKOFF_MS;
608
636
  return cached2;
@@ -723,7 +751,7 @@ var HttpTransport = (_class2 = class {
723
751
  await sleep(decision.delaySeconds * 1e3, options.signal);
724
752
  }
725
753
  }
726
- throw _nullishCoalesce(_optionalChain([last, 'optionalAccess', _12 => _12.error]), () => ( new (0, _chunkJPDEKN5Mcjs.SynapError)("Request failed with no recorded error")));
754
+ throw _nullishCoalesce(_optionalChain([last, 'optionalAccess', _15 => _15.error]), () => ( new (0, _chunkJPDEKN5Mcjs.SynapError)("Request failed with no recorded error")));
727
755
  }
728
756
  async attempt(name, options, correlationId) {
729
757
  const spec = ENDPOINTS[name];
@@ -751,11 +779,11 @@ var HttpTransport = (_class2 = class {
751
779
  const error = await toHttpError(response, correlationId);
752
780
  if (response.status === 400 && error instanceof _chunkJPDEKN5Mcjs.InvalidInputError) {
753
781
  try {
754
- _optionalChain([this, 'access', _13 => _13.onInvalidInput, 'optionalCall', _14 => _14(error, carriesScopePath(options.body))]);
782
+ _optionalChain([this, 'access', _16 => _16.onInvalidInput, 'optionalCall', _17 => _17(error, carriesScopePath(options.body))]);
755
783
  } catch (e3) {
756
784
  }
757
785
  }
758
- throw _nullishCoalesce(_optionalChain([options, 'access', _15 => _15.mapError, 'optionalCall', _16 => _16(response.status, error)]), () => ( error));
786
+ throw _nullishCoalesce(_optionalChain([options, 'access', _18 => _18.mapError, 'optionalCall', _19 => _19(response.status, error)]), () => ( error));
759
787
  }
760
788
  if (response.status === 204) return void 0;
761
789
  const text = await response.text();
@@ -827,18 +855,18 @@ function isConnectionRefusal(error) {
827
855
  }
828
856
  function toTransportError(error, correlationId) {
829
857
  if (error instanceof _chunkJPDEKN5Mcjs.SynapError) return error;
830
- const name = _optionalChain([error, 'optionalAccess', _17 => _17.name]);
858
+ const name = _optionalChain([error, 'optionalAccess', _20 => _20.name]);
831
859
  if (name === "AbortError" || name === "TimeoutError") {
832
860
  return new (0, _chunkJPDEKN5Mcjs.NetworkTimeoutError)("Request timed out", { correlationId, cause: error });
833
861
  }
834
862
  if (isConnectionRefusal(error)) {
835
863
  return new (0, _chunkJPDEKN5Mcjs.NetworkTimeoutError)(
836
- `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _18 => _18.message]), () => ( String(error)))}`,
864
+ `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _21 => _21.message]), () => ( String(error)))}`,
837
865
  { correlationId, cause: error }
838
866
  );
839
867
  }
840
868
  return new (0, _chunkJPDEKN5Mcjs.ServiceUnavailableError)(
841
- `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _19 => _19.message]), () => ( String(error)))}`,
869
+ `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _22 => _22.message]), () => ( String(error)))}`,
842
870
  { correlationId, cause: error }
843
871
  );
844
872
  }
@@ -923,8 +951,8 @@ async function toHttpError(response, correlationId) {
923
951
  });
924
952
  }
925
953
  case 409:
926
- if (parsed["error"] === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _20 => _20["code"]]) === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _21 => _21["error"]]) === "instance_build_failed") {
927
- const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _22 => _22[key]])));
954
+ if (parsed["error"] === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _23 => _23["code"]]) === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _24 => _24["error"]]) === "instance_build_failed") {
955
+ const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _25 => _25[key]])));
928
956
  const msg = pick4("message");
929
957
  const attempts = Number(pick4("attempts"));
930
958
  return new (0, _chunkJPDEKN5Mcjs.InstanceBuildFailedError)(
@@ -937,8 +965,8 @@ async function toHttpError(response, correlationId) {
937
965
  }
938
966
  );
939
967
  }
940
- if (parsed["error"] === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _23 => _23["code"]]) === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _24 => _24["error"]]) === "instance_not_ready") {
941
- const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _25 => _25[key]])));
968
+ if (parsed["error"] === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _26 => _26["code"]]) === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _27 => _27["error"]]) === "instance_not_ready") {
969
+ const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _28 => _28[key]])));
942
970
  const rawWait = _nullishCoalesce(pick4("retry_after_seconds"), () => ( response.headers.get("retry-after")));
943
971
  const wait = rawWait !== null && rawWait !== void 0 && String(rawWait).trim() !== "" ? Number(rawWait) : NaN;
944
972
  const msg = pick4("message");
@@ -986,11 +1014,11 @@ function stringOrNull(v) {
986
1014
  }
987
1015
  function withTimeout(ms, external) {
988
1016
  const controller = new AbortController();
989
- const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _26 => _26.reason]));
1017
+ const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _29 => _29.reason]));
990
1018
  const timer = setTimeout(() => {
991
1019
  controller.abort(new (0, _chunkJPDEKN5Mcjs.NetworkTimeoutError)(`Timed out after ${ms}ms`));
992
1020
  }, ms);
993
- _optionalChain([timer, 'access', _27 => _27.unref, 'optionalCall', _28 => _28()]);
1021
+ _optionalChain([timer, 'access', _30 => _30.unref, 'optionalCall', _31 => _31()]);
994
1022
  if (external) {
995
1023
  if (external.aborted) onExternalAbort();
996
1024
  else external.addEventListener("abort", onExternalAbort, { once: true });
@@ -999,7 +1027,7 @@ function withTimeout(ms, external) {
999
1027
  signal: controller.signal,
1000
1028
  dispose() {
1001
1029
  clearTimeout(timer);
1002
- _optionalChain([external, 'optionalAccess', _29 => _29.removeEventListener, 'call', _30 => _30("abort", onExternalAbort)]);
1030
+ _optionalChain([external, 'optionalAccess', _32 => _32.removeEventListener, 'call', _33 => _33("abort", onExternalAbort)]);
1003
1031
  }
1004
1032
  };
1005
1033
  }
@@ -1007,14 +1035,14 @@ function sleep(ms, signal) {
1007
1035
  if (ms <= 0) return Promise.resolve();
1008
1036
  return new Promise((resolve, reject) => {
1009
1037
  const timer = setTimeout(() => {
1010
- _optionalChain([signal, 'optionalAccess', _31 => _31.removeEventListener, 'call', _32 => _32("abort", onAbort)]);
1038
+ _optionalChain([signal, 'optionalAccess', _34 => _34.removeEventListener, 'call', _35 => _35("abort", onAbort)]);
1011
1039
  resolve();
1012
1040
  }, ms);
1013
1041
  function onAbort() {
1014
1042
  clearTimeout(timer);
1015
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _33 => _33.reason]), () => ( new Error("Aborted"))));
1043
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _36 => _36.reason]), () => ( new Error("Aborted"))));
1016
1044
  }
1017
- _optionalChain([signal, 'optionalAccess', _34 => _34.addEventListener, 'call', _35 => _35("abort", onAbort, { once: true })]);
1045
+ _optionalChain([signal, 'optionalAccess', _37 => _37.addEventListener, 'call', _38 => _38("abort", onAbort, { once: true })]);
1018
1046
  });
1019
1047
  }
1020
1048
 
@@ -1268,7 +1296,7 @@ function validateSearchQuery(searchQuery) {
1268
1296
  }
1269
1297
  async function fetchContext(transport, scope, options = {}, hooks = {}) {
1270
1298
  const startedAt = Date.now();
1271
- await _optionalChain([transport, 'access', _36 => _36.ready, 'optionalCall', _37 => _37()]);
1299
+ await _optionalChain([transport, 'access', _39 => _39.ready, 'optionalCall', _40 => _40()]);
1272
1300
  await transport.checkCustomerId(
1273
1301
  opt(options, "customer_id", "customerId"),
1274
1302
  `${scope}.context.fetch`
@@ -1284,20 +1312,20 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
1284
1312
  if (answer !== null) return applyResponseShape(answer, responseShape);
1285
1313
  }
1286
1314
  const finish = (response2) => {
1287
- _optionalChain([hooks, 'access', _38 => _38.onResponse, 'optionalCall', _39 => _39(scope, options, response2)]);
1315
+ _optionalChain([hooks, 'access', _41 => _41.onResponse, 'optionalCall', _42 => _42(scope, options, response2)]);
1288
1316
  return response2;
1289
1317
  };
1290
1318
  const conversationId = opt(options, "conversation_id", "conversationId");
1291
- const skipServerSt = conversationId ? _optionalChain([hooks, 'access', _40 => _40.skipServerShortTerm, 'optionalCall', _41 => _41(conversationId)]) === true : false;
1319
+ const skipServerSt = conversationId ? _optionalChain([hooks, 'access', _43 => _43.skipServerShortTerm, 'optionalCall', _44 => _44(conversationId)]) === true : false;
1292
1320
  const network = async () => {
1293
1321
  const { endpoint, body } = buildFetchRequest(
1294
1322
  scope,
1295
1323
  skipServerSt ? { ...options, include_conversation_context: false } : options
1296
1324
  );
1297
1325
  const result = await transport.request(endpoint, { body });
1298
- return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _42 => _42["context"]]), () => ( {})), responseShape);
1326
+ return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _45 => _45["context"]]), () => ( {})), responseShape);
1299
1327
  };
1300
- const anticipated = summaryMode ? null : await _asyncNullishCoalesce(await _optionalChain([hooks, 'access', _43 => _43.beforeFetch, 'optionalCall', _44 => _44(scope, options)]), async () => ( null));
1328
+ const anticipated = summaryMode ? null : await _asyncNullishCoalesce(await _optionalChain([hooks, 'access', _46 => _46.beforeFetch, 'optionalCall', _47 => _47(scope, options)]), async () => ( null));
1301
1329
  if (anticipated !== null && anticipated.borderline) {
1302
1330
  const pending = network();
1303
1331
  pending.catch(() => void 0);
@@ -1308,17 +1336,17 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
1308
1336
  const won = await Promise.race([pending.then((r) => r, () => null), late]);
1309
1337
  if (timer !== void 0) clearTimeout(timer);
1310
1338
  if (won !== null) {
1311
- _optionalChain([hooks, 'access', _45 => _45.onAssembled, 'optionalCall', _46 => _46(scope, options, won, startedAt)]);
1339
+ _optionalChain([hooks, 'access', _48 => _48.onAssembled, 'optionalCall', _49 => _49(scope, options, won, startedAt)]);
1312
1340
  return finish(won);
1313
1341
  }
1314
1342
  }
1315
1343
  if (anticipated !== null) {
1316
- _optionalChain([hooks, 'access', _47 => _47.onServedFromCache, 'optionalCall', _48 => _48(scope, options, anticipated)]);
1317
- _optionalChain([hooks, 'access', _49 => _49.onAssembled, 'optionalCall', _50 => _50(scope, options, anticipated.response, startedAt)]);
1344
+ _optionalChain([hooks, 'access', _50 => _50.onServedFromCache, 'optionalCall', _51 => _51(scope, options, anticipated)]);
1345
+ _optionalChain([hooks, 'access', _52 => _52.onAssembled, 'optionalCall', _53 => _53(scope, options, anticipated.response, startedAt)]);
1318
1346
  return finish(applyResponseShape(anticipated.response, responseShape));
1319
1347
  }
1320
1348
  const response = await network();
1321
- _optionalChain([hooks, 'access', _51 => _51.onAssembled, 'optionalCall', _52 => _52(scope, options, response, startedAt)]);
1349
+ _optionalChain([hooks, 'access', _54 => _54.onAssembled, 'optionalCall', _55 => _55(scope, options, response, startedAt)]);
1322
1350
  return finish(response);
1323
1351
  }
1324
1352
 
@@ -1620,7 +1648,7 @@ function defaultFilename(p, source) {
1620
1648
  }
1621
1649
  return lastSegment(pathname) || "file";
1622
1650
  }
1623
- const named = _optionalChain([p, 'access', _53 => _53.data, 'optionalAccess', _54 => _54.name]);
1651
+ const named = _optionalChain([p, 'access', _56 => _56.data, 'optionalAccess', _57 => _57.name]);
1624
1652
  return typeof named === "string" && named ? named : "file";
1625
1653
  }
1626
1654
  var MEDIA_TYPES = {
@@ -1657,7 +1685,7 @@ function guessMediaType(filename) {
1657
1685
  function defaultMediaType(filename, data) {
1658
1686
  const guessed = guessMediaType(filename);
1659
1687
  if (guessed !== null) return guessed;
1660
- const blobType = _optionalChain([data, 'optionalAccess', _55 => _55.type]);
1688
+ const blobType = _optionalChain([data, 'optionalAccess', _58 => _58.type]);
1661
1689
  return typeof blobType === "string" && blobType ? blobType : DEFAULT_MEDIA_TYPE;
1662
1690
  }
1663
1691
  function normaliseContent(value, field) {
@@ -1683,7 +1711,7 @@ function typeName(value) {
1683
1711
  if (value === null) return "null";
1684
1712
  if (Array.isArray(value)) return "array";
1685
1713
  if (typeof value === "object") {
1686
- return _nullishCoalesce(_optionalChain([value, 'access', _56 => _56.constructor, 'optionalAccess', _57 => _57.name]), () => ( "object"));
1714
+ return _nullishCoalesce(_optionalChain([value, 'access', _59 => _59.constructor, 'optionalAccess', _60 => _60.name]), () => ( "object"));
1687
1715
  }
1688
1716
  return typeof value;
1689
1717
  }
@@ -1700,7 +1728,7 @@ async function resolveFile(part, fetchImpl) {
1700
1728
  bytes = new Uint8Array(await readFile(part.path));
1701
1729
  } catch (error) {
1702
1730
  throw new (0, _chunkJPDEKN5Mcjs.InvalidInputError)(
1703
- `Could not read FilePart path '${part.path}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _58 => _58.message]), () => ( String(error)))}`,
1731
+ `Could not read FilePart path '${part.path}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _61 => _61.message]), () => ( String(error)))}`,
1704
1732
  { cause: error }
1705
1733
  );
1706
1734
  }
@@ -1770,7 +1798,7 @@ async function fetchUrl(url, fetchImpl) {
1770
1798
  );
1771
1799
  }
1772
1800
  throw new (0, _chunkJPDEKN5Mcjs.InvalidInputError)(
1773
- `Could not fetch FilePart url '${url}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _59 => _59.message]), () => ( String(error)))}`,
1801
+ `Could not fetch FilePart url '${url}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _62 => _62.message]), () => ( String(error)))}`,
1774
1802
  { cause: error }
1775
1803
  );
1776
1804
  } finally {
@@ -2114,7 +2142,7 @@ function createMemoriesInterface(transport, onForgotten) {
2114
2142
  await transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.forget");
2115
2143
  const body = buildForgetBody(options);
2116
2144
  const result = await transport.request("memories_forget", { body });
2117
- const removed = !!_optionalChain([result, 'optionalAccess', _60 => _60.deleted_ids, 'optionalAccess', _61 => _61.length]) || _optionalChain([result, 'optionalAccess', _62 => _62.status]) === "deleted" || _optionalChain([result, 'optionalAccess', _63 => _63.status]) === "partial";
2145
+ const removed = !!_optionalChain([result, 'optionalAccess', _63 => _63.deleted_ids, 'optionalAccess', _64 => _64.length]) || _optionalChain([result, 'optionalAccess', _65 => _65.status]) === "deleted" || _optionalChain([result, 'optionalAccess', _66 => _66.status]) === "partial";
2118
2146
  if (removed && onForgotten) {
2119
2147
  try {
2120
2148
  onForgotten({
@@ -2154,14 +2182,14 @@ function sleep2(ms, signal) {
2154
2182
  if (ms <= 0) return Promise.resolve();
2155
2183
  return new Promise((resolve, reject) => {
2156
2184
  const timer = setTimeout(() => {
2157
- _optionalChain([signal, 'optionalAccess', _64 => _64.removeEventListener, 'call', _65 => _65("abort", onAbort)]);
2185
+ _optionalChain([signal, 'optionalAccess', _67 => _67.removeEventListener, 'call', _68 => _68("abort", onAbort)]);
2158
2186
  resolve();
2159
2187
  }, ms);
2160
2188
  function onAbort() {
2161
2189
  clearTimeout(timer);
2162
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _66 => _66.reason]), () => ( new Error("Aborted"))));
2190
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _69 => _69.reason]), () => ( new Error("Aborted"))));
2163
2191
  }
2164
- _optionalChain([signal, 'optionalAccess', _67 => _67.addEventListener, 'call', _68 => _68("abort", onAbort, { once: true })]);
2192
+ _optionalChain([signal, 'optionalAccess', _70 => _70.addEventListener, 'call', _71 => _71("abort", onAbort, { once: true })]);
2165
2193
  });
2166
2194
  }
2167
2195
 
@@ -2242,7 +2270,7 @@ function buildRecordMessageBody(options, resolvedContent, field = "content") {
2242
2270
  content = resolvedContent;
2243
2271
  } else {
2244
2272
  const n2 = normaliseContent(options.content, field);
2245
- if (_optionalChain([n2, 'optionalAccess', _69 => _69.kind]) === "parts") {
2273
+ if (_optionalChain([n2, 'optionalAccess', _72 => _72.kind]) === "parts") {
2246
2274
  throw new (0, _chunkJPDEKN5Mcjs.InvalidInputError)(
2247
2275
  "content holds a FilePart, whose bytes have to be read first. Send it with conversation.record_message."
2248
2276
  );
@@ -2353,7 +2381,7 @@ function storedBatchRows(bodies, result) {
2353
2381
  const r = _nullishCoalesce(result, () => ( {}));
2354
2382
  const results = Array.isArray(r["results"]) ? r["results"] : [];
2355
2383
  const errors = Array.isArray(r["errors"]) ? r["errors"] : [];
2356
- const failed = new Set(errors.map((e) => _optionalChain([e, 'optionalAccess', _70 => _70["index"]])));
2384
+ const failed = new Set(errors.map((e) => _optionalChain([e, 'optionalAccess', _73 => _73["index"]])));
2357
2385
  const stored = bodies.filter((_, index) => !failed.has(index));
2358
2386
  if (stored.length !== results.length) return [];
2359
2387
  const pairs = [];
@@ -2397,7 +2425,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
2397
2425
  };
2398
2426
  const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
2399
2427
  const validateMessage = (options, field = "content") => {
2400
- if (_optionalChain([normaliseContent, 'call', _71 => _71(options.content, field), 'optionalAccess', _72 => _72.kind]) === "parts") {
2428
+ if (_optionalChain([normaliseContent, 'call', _74 => _74(options.content, field), 'optionalAccess', _75 => _75.kind]) === "parts") {
2401
2429
  buildRecordMessageBody(options, "", field);
2402
2430
  } else {
2403
2431
  buildRecordMessageBody(options, void 0, field);
@@ -2405,7 +2433,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
2405
2433
  };
2406
2434
  const prepareMessage = async (options, field = "content") => {
2407
2435
  const n2 = normaliseContent(options.content, field);
2408
- if (_optionalChain([n2, 'optionalAccess', _73 => _73.kind]) !== "parts") {
2436
+ if (_optionalChain([n2, 'optionalAccess', _76 => _76.kind]) !== "parts") {
2409
2437
  const body = buildRecordMessageBody(options, void 0, field);
2410
2438
  return { body, mirror: String(_nullishCoalesce(body["content"], () => ( ""))) };
2411
2439
  }
@@ -2496,7 +2524,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
2496
2524
  const raw = await transport.request("conversations_ingest", { body });
2497
2525
  const result = {
2498
2526
  ...raw,
2499
- warnings: Array.isArray(_optionalChain([raw, 'optionalAccess', _74 => _74.warnings])) ? raw.warnings.map(String) : []
2527
+ warnings: Array.isArray(_optionalChain([raw, 'optionalAccess', _77 => _77.warnings])) ? raw.warnings.map(String) : []
2500
2528
  };
2501
2529
  onWrite({
2502
2530
  userId: body["user_id"],
@@ -2540,8 +2568,8 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
2540
2568
  pathParams: { conversation_id: id },
2541
2569
  query: { style }
2542
2570
  });
2543
- const response = _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _75 => _75["context_for_prompt"]]), () => ( result)), () => ( {}));
2544
- _optionalChain([localShortTerm, 'access', _76 => _76.reseed, 'optionalCall', _77 => _77(id, response)]);
2571
+ const response = _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _78 => _78["context_for_prompt"]]), () => ( result)), () => ( {}));
2572
+ _optionalChain([localShortTerm, 'access', _79 => _79.reseed, 'optionalCall', _80 => _80(id, response)]);
2545
2573
  return withHistory(response);
2546
2574
  },
2547
2575
  async compact(options) {
@@ -2938,8 +2966,8 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2938
2966
  let onConversationState = null;
2939
2967
  const internals = {
2940
2968
  onCompactionUpdate(conversationId, bundle) {
2941
- _optionalChain([applyCompaction, 'optionalCall', _78 => _78(bundle)]);
2942
- _optionalChain([dispatchCompaction, 'optionalCall', _79 => _79(conversationId, bundle)]);
2969
+ _optionalChain([applyCompaction, 'optionalCall', _81 => _81(bundle)]);
2970
+ _optionalChain([dispatchCompaction, 'optionalCall', _82 => _82(conversationId, bundle)]);
2943
2971
  },
2944
2972
  setCompactionApplier(apply) {
2945
2973
  applyCompaction = apply;
@@ -2954,10 +2982,10 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2954
2982
  onConversationState = handle;
2955
2983
  },
2956
2984
  sendContextUsed(event) {
2957
- _optionalChain([client, 'optionalAccess', _80 => _80.sendContextUsed, 'call', _81 => _81(event)]);
2985
+ _optionalChain([client, 'optionalAccess', _83 => _83.sendContextUsed, 'call', _84 => _84(event)]);
2958
2986
  },
2959
2987
  sendContextAssembled(event) {
2960
- _optionalChain([client, 'optionalAccess', _82 => _82.sendContextAssembled, 'call', _83 => _83(event)]);
2988
+ _optionalChain([client, 'optionalAccess', _85 => _85.sendContextAssembled, 'call', _86 => _86(event)]);
2961
2989
  },
2962
2990
  setCompactionDispatcher(dispatch) {
2963
2991
  dispatchCompaction = dispatch;
@@ -2989,7 +3017,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2989
3017
  send(sync);
2990
3018
  return Promise.resolve();
2991
3019
  }
2992
- _optionalChain([prepared, 'optionalAccess', _84 => _84.catch, 'call', _85 => _85(() => {
3020
+ _optionalChain([prepared, 'optionalAccess', _87 => _87.catch, 'call', _88 => _88(() => {
2993
3021
  })]);
2994
3022
  queued += 1;
2995
3023
  const run = tail.then(async () => {
@@ -3008,7 +3036,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3008
3036
  throw new (0, _chunkJPDEKN5Mcjs.ListeningAlreadyActiveError)("Listening is already active on this instance");
3009
3037
  }
3010
3038
  try {
3011
- _optionalChain([onListen, 'optionalCall', _86 => _86()]);
3039
+ _optionalChain([onListen, 'optionalCall', _89 => _89()]);
3012
3040
  } catch (e17) {
3013
3041
  }
3014
3042
  const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-H2ES74FF.cjs")));
@@ -3026,17 +3054,17 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3026
3054
  internals.onCompactionUpdate(conversationId, bundle);
3027
3055
  },
3028
3056
  onConversationState: (conversationId, messageCount) => {
3029
- _optionalChain([onConversationState, 'optionalCall', _87 => _87(conversationId, messageCount)]);
3057
+ _optionalChain([onConversationState, 'optionalCall', _90 => _90(conversationId, messageCount)]);
3030
3058
  },
3031
3059
  onStateChange: (state) => {
3032
3060
  if (state !== "connected") openSessions.clear();
3033
3061
  if (state === "reconnecting") {
3034
3062
  reconnectAttempts += 1;
3035
- _optionalChain([onReconnect, 'optionalCall', _88 => _88(reconnectAttempts)]);
3063
+ _optionalChain([onReconnect, 'optionalCall', _91 => _91(reconnectAttempts)]);
3036
3064
  } else if (state === "disconnected") {
3037
- const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _89 => _89.lastError]), () => ( null));
3065
+ const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _92 => _92.lastError]), () => ( null));
3038
3066
  const reason = stopped === null ? "stream disconnected" : `credit_stop:${_nullishCoalesce(stopped.reason, () => ( "unknown"))}`;
3039
- _optionalChain([onDisconnect, 'optionalCall', _90 => _90(reason)]);
3067
+ _optionalChain([onDisconnect, 'optionalCall', _93 => _93(reason)]);
3040
3068
  }
3041
3069
  }
3042
3070
  });
@@ -3046,7 +3074,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3046
3074
  } catch (error) {
3047
3075
  if (error instanceof _chunkJPDEKN5Mcjs.SynapError) throw error;
3048
3076
  throw new (0, _chunkJPDEKN5Mcjs.SynapError)(
3049
- `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _91 => _91.message]), () => ( String(error)))}`,
3077
+ `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _94 => _94.message]), () => ( String(error)))}`,
3050
3078
  { cause: error }
3051
3079
  );
3052
3080
  }
@@ -3101,7 +3129,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3101
3129
  _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
3102
3130
  );
3103
3131
  if (eventType === "user_message" || eventType === "assistant_message") {
3104
- _optionalChain([onTurn, 'optionalCall', _92 => _92({
3132
+ _optionalChain([onTurn, 'optionalCall', _95 => _95({
3105
3133
  conversationId,
3106
3134
  role: _nullishCoalesce(options.role, () => ( "user")),
3107
3135
  content
@@ -3133,8 +3161,8 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3133
3161
  })()
3134
3162
  });
3135
3163
  };
3136
- if (_optionalChain([parts, 'optionalAccess', _93 => _93.kind]) !== "parts") {
3137
- const content = _optionalChain([parts, 'optionalAccess', _94 => _94.kind]) === "text" ? parts.text : options.content;
3164
+ if (_optionalChain([parts, 'optionalAccess', _96 => _96.kind]) !== "parts") {
3165
+ const content = _optionalChain([parts, 'optionalAccess', _97 => _97.kind]) === "text" ? parts.text : options.content;
3138
3166
  return inOrder(null, emit, { content, metadata: _nullishCoalesce(options.metadata, () => ( {})) });
3139
3167
  }
3140
3168
  const prepared = (async () => {
@@ -3172,7 +3200,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3172
3200
  async record_tool_result(options) {
3173
3201
  const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
3174
3202
  if (conversationId) {
3175
- _optionalChain([onToolResult, 'optionalCall', _95 => _95({ conversationId, result: options.result, toolName: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")) })]);
3203
+ _optionalChain([onToolResult, 'optionalCall', _98 => _98({ conversationId, result: options.result, toolName: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")) })]);
3176
3204
  }
3177
3205
  await namespace.send_message({
3178
3206
  content: "",
@@ -3227,7 +3255,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
3227
3255
  }
3228
3256
 
3229
3257
  // src/version.ts
3230
- var SDK_VERSION = "0.7.0";
3258
+ var SDK_VERSION = "0.7.1";
3231
3259
 
3232
3260
  // src/registry.ts
3233
3261
  var instances = /* @__PURE__ */ new Map();
@@ -3695,7 +3723,7 @@ var TurnStore = (_class3 = class {
3695
3723
  }
3696
3724
  /** Turns the server also holds: archived tool results are local only. Python: `count`. */
3697
3725
  count(conversationId) {
3698
- return (_nullishCoalesce(_optionalChain([this, 'access', _96 => _96.#conversations, 'access', _97 => _97.get, 'call', _98 => _98(conversationId), 'optionalAccess', _99 => _99.turns]), () => ( []))).filter((t) => t.role !== "tool").length;
3726
+ return (_nullishCoalesce(_optionalChain([this, 'access', _99 => _99.#conversations, 'access', _100 => _100.get, 'call', _101 => _101(conversationId), 'optionalAccess', _102 => _102.turns]), () => ( []))).filter((t) => t.role !== "tool").length;
3699
3727
  }
3700
3728
  sizeBytes() {
3701
3729
  let n2 = 0;
@@ -3874,7 +3902,7 @@ function askedKinds(query) {
3874
3902
  }
3875
3903
  function asksHowItStarted(query) {
3876
3904
  const spec = _chunkBYUGILQIcjs.HISTORY_SEARCH.early_query;
3877
- if (!_optionalChain([spec, 'optionalAccess', _100 => _100.pattern])) return false;
3905
+ if (!_optionalChain([spec, 'optionalAccess', _103 => _103.pattern])) return false;
3878
3906
  return new RegExp(spec.pattern, (_nullishCoalesce(spec.flags, () => ( ""))).includes("i") ? "i" : "").test(_nullishCoalesce(query, () => ( "")));
3879
3907
  }
3880
3908
  async function searchTurns(turns, query, options = {}) {
@@ -5137,7 +5165,7 @@ var SynapClient = (_class4 = class _SynapClient {
5137
5165
  this.#localEncoder = _nullishCoalesce(_nullishCoalesce(options.history_search_encoder, () => ( options.historySearchEncoder)), () => ( null));
5138
5166
  const modelOption = options.history_search_model !== void 0 ? options.history_search_model : options.historySearchModel;
5139
5167
  this.#localModelName = modelOption === void 0 ? "auto" : modelOption;
5140
- if (_optionalChain([this, 'access', _101 => _101.#localEncoder, 'optionalAccess', _102 => _102.model]) === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
5168
+ if (_optionalChain([this, 'access', _104 => _104.#localEncoder, 'optionalAccess', _105 => _105.model]) === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
5141
5169
  this.#turns = new TurnCounter();
5142
5170
  this.conversation = createConversationNamespace(
5143
5171
  this.#transport,
@@ -5379,7 +5407,7 @@ var SynapClient = (_class4 = class _SynapClient {
5379
5407
  } catch (error) {
5380
5408
  if (this.#localMode) {
5381
5409
  throw new (0, _chunkJPDEKN5Mcjs.AuthenticationError)(
5382
- `Could not reach the Synap server at ${this.#transport.baseUrl}, or it did not identify itself: GET /api/v1/auth/whoami failed (${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _103 => _103.message]), () => ( String(error)))}).`,
5410
+ `Could not reach the Synap server at ${this.#transport.baseUrl}, or it did not identify itself: GET /api/v1/auth/whoami failed (${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _106 => _106.message]), () => ( String(error)))}).`,
5383
5411
  { cause: error }
5384
5412
  );
5385
5413
  }
@@ -5499,6 +5527,19 @@ var SynapClient = (_class4 = class _SynapClient {
5499
5527
  // one hands every scope fetch exactly the options it always got.
5500
5528
  ...scopePath !== void 0 && scopePath !== null && Object.keys(scopePath).length > 0 ? { scope_path: scopePath } : {}
5501
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;
5502
5543
  const labels = [];
5503
5544
  const tasks = [];
5504
5545
  const present = (v) => v !== void 0 && v !== null && v !== "";
@@ -5530,14 +5571,14 @@ var SynapClient = (_class4 = class _SynapClient {
5530
5571
  tasks.push(this.customer.context.fetch({
5531
5572
  customer_id: customerId,
5532
5573
  conversation_id: conversationId,
5533
- ...shared
5574
+ ...customerShared
5534
5575
  }));
5535
5576
  }
5536
5577
  if (scopes !== void 0 && scopes.includes("client")) {
5537
5578
  labels.push("client");
5538
5579
  tasks.push(this.client.context.fetch({
5539
5580
  conversation_id: conversationId,
5540
- ...shared
5581
+ ...sharedNoPath
5541
5582
  }));
5542
5583
  }
5543
5584
  if (tasks.length === 0 && !(conversationState && includeConversationContext)) {
@@ -5705,14 +5746,14 @@ var SynapClient = (_class4 = class _SynapClient {
5705
5746
  }))
5706
5747
  );
5707
5748
  const entry = this.#shortTerm.get(conversationId);
5708
- const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _104 => _104.serverMessageCount]), () => ( 0))) || 0);
5749
+ const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _107 => _107.serverMessageCount]), () => ( 0))) || 0);
5709
5750
  this.#maybeBackfillTurns(conversationId, total);
5710
5751
  if (!r["context_block"]) return response;
5711
5752
  const turns = store.turns(conversationId);
5712
5753
  let q = query;
5713
5754
  if (!q) {
5714
5755
  const latest = [...recent].reverse().find((m) => m["role"] === "user");
5715
- q = latest ? String(_nullishCoalesce(latest["content"], () => ( ""))) : _nullishCoalesce(_optionalChain([[...turns], 'access', _105 => _105.reverse, 'call', _106 => _106(), 'access', _107 => _107.find, 'call', _108 => _108((t) => t.role === "user"), 'optionalAccess', _109 => _109.content]), () => ( ""));
5756
+ q = latest ? String(_nullishCoalesce(latest["content"], () => ( ""))) : _nullishCoalesce(_optionalChain([[...turns], 'access', _108 => _108.reverse, 'call', _109 => _109(), 'access', _110 => _110.find, 'call', _111 => _111((t) => t.role === "user"), 'optionalAccess', _112 => _112.content]), () => ( ""));
5716
5757
  }
5717
5758
  if (!q) return response;
5718
5759
  const exclude = /* @__PURE__ */ new Set();
@@ -5856,7 +5897,7 @@ function pick3(o2, snake, camel) {
5856
5897
  function resolveBaseUrl(options) {
5857
5898
  const explicit = _nullishCoalesce(options.baseUrl, () => ( options.api_base_url));
5858
5899
  if (explicit !== void 0) return explicit;
5859
- const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _110 => _110.trim, 'call', _111 => _111()]);
5900
+ const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _113 => _113.trim, 'call', _114 => _114()]);
5860
5901
  return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
5861
5902
  }
5862
5903
  function resolveCredentials(options, localMode) {