@maximem/synap-js-sdk 0.6.6 → 0.6.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -43,6 +43,15 @@ var _chunkZKOJDUN4cjs = require('./chunk-ZKOJDUN4.cjs');
43
43
 
44
44
  var _chunk7IZHVYO2cjs = require('./chunk-7IZHVYO2.cjs');
45
45
 
46
+ // src/local-mode.ts
47
+ function isLocalMode(apiKey, baseUrl) {
48
+ if (apiKey || _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_KEY")) return false;
49
+ return baseUrl !== void 0 && baseUrl.trim() !== "";
50
+ }
51
+ function localToken() {
52
+ return _nullishCoalesce(_optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_TOKEN"), 'optionalAccess', _2 => _2.trim, 'call', _3 => _3()]), () => ( ""));
53
+ }
54
+
46
55
  // src/transport/endpoints.ts
47
56
  var ENDPOINTS = {
48
57
  whoami: { method: "GET", path: "/api/v1/auth/whoami", idempotent: true },
@@ -143,7 +152,7 @@ var HEARTBEAT_INTERVAL_MS = 24e4;
143
152
  var MAX_CONNECTIONS = 20;
144
153
  var cached;
145
154
  function supportsDispatcher() {
146
- return typeof process !== "undefined" && _optionalChain([process, 'access', _2 => _2.versions, 'optionalAccess', _3 => _3.node]) !== void 0 && // Edge builds of Next expose a partial `process` shim, but no real Node.
155
+ return typeof process !== "undefined" && _optionalChain([process, 'access', _4 => _4.versions, 'optionalAccess', _5 => _5.node]) !== void 0 && // Edge builds of Next expose a partial `process` shim, but no real Node.
147
156
  typeof globalThis.EdgeRuntime === "undefined";
148
157
  }
149
158
  async function getKeepAliveDispatcher(options = {}) {
@@ -184,7 +193,7 @@ var Heartbeat = (_class = class {
184
193
  void Promise.resolve(this.ping()).catch(() => {
185
194
  });
186
195
  }, this.intervalMs);
187
- _optionalChain([this, 'access', _4 => _4.timer, 'access', _5 => _5.unref, 'optionalCall', _6 => _6()]);
196
+ _optionalChain([this, 'access', _6 => _6.timer, 'access', _7 => _7.unref, 'optionalCall', _8 => _8()]);
188
197
  }
189
198
  stop() {
190
199
  if (this.timer !== null) {
@@ -270,7 +279,7 @@ var HttpTransport = (_class2 = class {
270
279
  this.keepAliveOptions = _nullishCoalesce(options.keepAlive, () => ( {}));
271
280
  this.heartbeat = new Heartbeat(
272
281
  () => this.pingHealth(),
273
- _nullishCoalesce(_optionalChain([options, 'access', _7 => _7.keepAlive, 'optionalAccess', _8 => _8.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
282
+ _nullishCoalesce(_optionalChain([options, 'access', _9 => _9.keepAlive, 'optionalAccess', _10 => _10.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
274
283
  );
275
284
  }
276
285
  /**
@@ -422,7 +431,7 @@ var HttpTransport = (_class2 = class {
422
431
  await sleep(decision.delaySeconds * 1e3, options.signal);
423
432
  }
424
433
  }
425
- throw _nullishCoalesce(_optionalChain([last, 'optionalAccess', _9 => _9.error]), () => ( new (0, _chunk7IZHVYO2cjs.SynapError)("Request failed with no recorded error")));
434
+ throw _nullishCoalesce(_optionalChain([last, 'optionalAccess', _11 => _11.error]), () => ( new (0, _chunk7IZHVYO2cjs.SynapError)("Request failed with no recorded error")));
426
435
  }
427
436
  async attempt(name, options, correlationId) {
428
437
  const spec = ENDPOINTS[name];
@@ -448,7 +457,7 @@ var HttpTransport = (_class2 = class {
448
457
  }
449
458
  if (!response.ok) {
450
459
  const error = await toHttpError(response, correlationId);
451
- throw _nullishCoalesce(_optionalChain([options, 'access', _10 => _10.mapError, 'optionalCall', _11 => _11(response.status, error)]), () => ( error));
460
+ throw _nullishCoalesce(_optionalChain([options, 'access', _12 => _12.mapError, 'optionalCall', _13 => _13(response.status, error)]), () => ( error));
452
461
  }
453
462
  if (response.status === 204) return void 0;
454
463
  const text = await response.text();
@@ -468,7 +477,8 @@ var HttpTransport = (_class2 = class {
468
477
  }
469
478
  buildHeaders(correlationId, options = {}) {
470
479
  return {
471
- Authorization: `Bearer ${this.#credentials.apiKey}`,
480
+ // Empty only in local mode with no SYNAP_API_TOKEN: send no header at all.
481
+ ...this.#credentials.apiKey !== "" ? { Authorization: `Bearer ${this.#credentials.apiKey}` } : {},
472
482
  "X-Client-ID": this.#credentials.clientId,
473
483
  "X-Instance-ID": this.#credentials.instanceId,
474
484
  "X-Correlation-ID": correlationId,
@@ -519,18 +529,18 @@ function isConnectionRefusal(error) {
519
529
  }
520
530
  function toTransportError(error, correlationId) {
521
531
  if (error instanceof _chunk7IZHVYO2cjs.SynapError) return error;
522
- const name = _optionalChain([error, 'optionalAccess', _12 => _12.name]);
532
+ const name = _optionalChain([error, 'optionalAccess', _14 => _14.name]);
523
533
  if (name === "AbortError" || name === "TimeoutError") {
524
534
  return new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)("Request timed out", { correlationId, cause: error });
525
535
  }
526
536
  if (isConnectionRefusal(error)) {
527
537
  return new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)(
528
- `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _13 => _13.message]), () => ( String(error)))}`,
538
+ `Connection failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _15 => _15.message]), () => ( String(error)))}`,
529
539
  { correlationId, cause: error }
530
540
  );
531
541
  }
532
542
  return new (0, _chunk7IZHVYO2cjs.ServiceUnavailableError)(
533
- `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _14 => _14.message]), () => ( String(error)))}`,
543
+ `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _16 => _16.message]), () => ( String(error)))}`,
534
544
  { correlationId, cause: error }
535
545
  );
536
546
  }
@@ -583,8 +593,8 @@ async function toHttpError(response, correlationId) {
583
593
  });
584
594
  }
585
595
  case 409:
586
- if (parsed["error"] === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _15 => _15["code"]]) === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _16 => _16["error"]]) === "instance_build_failed") {
587
- const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _17 => _17[key]])));
596
+ if (parsed["error"] === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _17 => _17["code"]]) === "instance_build_failed" || _optionalChain([detailObject, 'optionalAccess', _18 => _18["error"]]) === "instance_build_failed") {
597
+ const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _19 => _19[key]])));
588
598
  const msg = pick4("message");
589
599
  const attempts = Number(pick4("attempts"));
590
600
  return new (0, _chunk7IZHVYO2cjs.InstanceBuildFailedError)(
@@ -597,8 +607,8 @@ async function toHttpError(response, correlationId) {
597
607
  }
598
608
  );
599
609
  }
600
- if (parsed["error"] === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _18 => _18["code"]]) === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _19 => _19["error"]]) === "instance_not_ready") {
601
- const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _20 => _20[key]])));
610
+ if (parsed["error"] === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _20 => _20["code"]]) === "instance_not_ready" || _optionalChain([detailObject, 'optionalAccess', _21 => _21["error"]]) === "instance_not_ready") {
611
+ const pick4 = (key) => _nullishCoalesce(parsed[key], () => ( _optionalChain([detailObject, 'optionalAccess', _22 => _22[key]])));
602
612
  const rawWait = _nullishCoalesce(pick4("retry_after_seconds"), () => ( response.headers.get("retry-after")));
603
613
  const wait = rawWait !== null && rawWait !== void 0 && String(rawWait).trim() !== "" ? Number(rawWait) : NaN;
604
614
  const msg = pick4("message");
@@ -646,11 +656,11 @@ function stringOrNull(v) {
646
656
  }
647
657
  function withTimeout(ms, external) {
648
658
  const controller = new AbortController();
649
- const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _21 => _21.reason]));
659
+ const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _23 => _23.reason]));
650
660
  const timer = setTimeout(() => {
651
661
  controller.abort(new (0, _chunk7IZHVYO2cjs.NetworkTimeoutError)(`Timed out after ${ms}ms`));
652
662
  }, ms);
653
- _optionalChain([timer, 'access', _22 => _22.unref, 'optionalCall', _23 => _23()]);
663
+ _optionalChain([timer, 'access', _24 => _24.unref, 'optionalCall', _25 => _25()]);
654
664
  if (external) {
655
665
  if (external.aborted) onExternalAbort();
656
666
  else external.addEventListener("abort", onExternalAbort, { once: true });
@@ -659,7 +669,7 @@ function withTimeout(ms, external) {
659
669
  signal: controller.signal,
660
670
  dispose() {
661
671
  clearTimeout(timer);
662
- _optionalChain([external, 'optionalAccess', _24 => _24.removeEventListener, 'call', _25 => _25("abort", onExternalAbort)]);
672
+ _optionalChain([external, 'optionalAccess', _26 => _26.removeEventListener, 'call', _27 => _27("abort", onExternalAbort)]);
663
673
  }
664
674
  };
665
675
  }
@@ -667,14 +677,14 @@ function sleep(ms, signal) {
667
677
  if (ms <= 0) return Promise.resolve();
668
678
  return new Promise((resolve, reject) => {
669
679
  const timer = setTimeout(() => {
670
- _optionalChain([signal, 'optionalAccess', _26 => _26.removeEventListener, 'call', _27 => _27("abort", onAbort)]);
680
+ _optionalChain([signal, 'optionalAccess', _28 => _28.removeEventListener, 'call', _29 => _29("abort", onAbort)]);
671
681
  resolve();
672
682
  }, ms);
673
683
  function onAbort() {
674
684
  clearTimeout(timer);
675
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _28 => _28.reason]), () => ( new Error("Aborted"))));
685
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _30 => _30.reason]), () => ( new Error("Aborted"))));
676
686
  }
677
- _optionalChain([signal, 'optionalAccess', _29 => _29.addEventListener, 'call', _30 => _30("abort", onAbort, { once: true })]);
687
+ _optionalChain([signal, 'optionalAccess', _31 => _31.addEventListener, 'call', _32 => _32("abort", onAbort, { once: true })]);
678
688
  });
679
689
  }
680
690
 
@@ -928,7 +938,7 @@ function validateSearchQuery(searchQuery) {
928
938
  }
929
939
  async function fetchContext(transport, scope, options = {}, hooks = {}) {
930
940
  const startedAt = Date.now();
931
- await _optionalChain([transport, 'access', _31 => _31.ready, 'optionalCall', _32 => _32()]);
941
+ await _optionalChain([transport, 'access', _33 => _33.ready, 'optionalCall', _34 => _34()]);
932
942
  await transport.checkCustomerId(
933
943
  opt(options, "customer_id", "customerId"),
934
944
  `${scope}.context.fetch`
@@ -944,20 +954,20 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
944
954
  if (answer !== null) return applyResponseShape(answer, responseShape);
945
955
  }
946
956
  const finish = (response2) => {
947
- _optionalChain([hooks, 'access', _33 => _33.onResponse, 'optionalCall', _34 => _34(scope, options, response2)]);
957
+ _optionalChain([hooks, 'access', _35 => _35.onResponse, 'optionalCall', _36 => _36(scope, options, response2)]);
948
958
  return response2;
949
959
  };
950
960
  const conversationId = opt(options, "conversation_id", "conversationId");
951
- const skipServerSt = conversationId ? _optionalChain([hooks, 'access', _35 => _35.skipServerShortTerm, 'optionalCall', _36 => _36(conversationId)]) === true : false;
961
+ const skipServerSt = conversationId ? _optionalChain([hooks, 'access', _37 => _37.skipServerShortTerm, 'optionalCall', _38 => _38(conversationId)]) === true : false;
952
962
  const network = async () => {
953
963
  const { endpoint, body } = buildFetchRequest(
954
964
  scope,
955
965
  skipServerSt ? { ...options, include_conversation_context: false } : options
956
966
  );
957
967
  const result = await transport.request(endpoint, { body });
958
- return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _37 => _37["context"]]), () => ( {})), responseShape);
968
+ return applyResponseShape(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _39 => _39["context"]]), () => ( {})), responseShape);
959
969
  };
960
- const anticipated = summaryMode ? null : await _asyncNullishCoalesce(await _optionalChain([hooks, 'access', _38 => _38.beforeFetch, 'optionalCall', _39 => _39(scope, options)]), async () => ( null));
970
+ const anticipated = summaryMode ? null : await _asyncNullishCoalesce(await _optionalChain([hooks, 'access', _40 => _40.beforeFetch, 'optionalCall', _41 => _41(scope, options)]), async () => ( null));
961
971
  if (anticipated !== null && anticipated.borderline) {
962
972
  const pending = network();
963
973
  pending.catch(() => void 0);
@@ -968,17 +978,17 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
968
978
  const won = await Promise.race([pending.then((r) => r, () => null), late]);
969
979
  if (timer !== void 0) clearTimeout(timer);
970
980
  if (won !== null) {
971
- _optionalChain([hooks, 'access', _40 => _40.onAssembled, 'optionalCall', _41 => _41(scope, options, won, startedAt)]);
981
+ _optionalChain([hooks, 'access', _42 => _42.onAssembled, 'optionalCall', _43 => _43(scope, options, won, startedAt)]);
972
982
  return finish(won);
973
983
  }
974
984
  }
975
985
  if (anticipated !== null) {
976
- _optionalChain([hooks, 'access', _42 => _42.onServedFromCache, 'optionalCall', _43 => _43(scope, options, anticipated)]);
977
- _optionalChain([hooks, 'access', _44 => _44.onAssembled, 'optionalCall', _45 => _45(scope, options, anticipated.response, startedAt)]);
986
+ _optionalChain([hooks, 'access', _44 => _44.onServedFromCache, 'optionalCall', _45 => _45(scope, options, anticipated)]);
987
+ _optionalChain([hooks, 'access', _46 => _46.onAssembled, 'optionalCall', _47 => _47(scope, options, anticipated.response, startedAt)]);
978
988
  return finish(applyResponseShape(anticipated.response, responseShape));
979
989
  }
980
990
  const response = await network();
981
- _optionalChain([hooks, 'access', _46 => _46.onAssembled, 'optionalCall', _47 => _47(scope, options, response, startedAt)]);
991
+ _optionalChain([hooks, 'access', _48 => _48.onAssembled, 'optionalCall', _49 => _49(scope, options, response, startedAt)]);
982
992
  return finish(response);
983
993
  }
984
994
 
@@ -1280,7 +1290,7 @@ function defaultFilename(p, source) {
1280
1290
  }
1281
1291
  return lastSegment(pathname) || "file";
1282
1292
  }
1283
- const named = _optionalChain([p, 'access', _48 => _48.data, 'optionalAccess', _49 => _49.name]);
1293
+ const named = _optionalChain([p, 'access', _50 => _50.data, 'optionalAccess', _51 => _51.name]);
1284
1294
  return typeof named === "string" && named ? named : "file";
1285
1295
  }
1286
1296
  var MEDIA_TYPES = {
@@ -1317,7 +1327,7 @@ function guessMediaType(filename) {
1317
1327
  function defaultMediaType(filename, data) {
1318
1328
  const guessed = guessMediaType(filename);
1319
1329
  if (guessed !== null) return guessed;
1320
- const blobType = _optionalChain([data, 'optionalAccess', _50 => _50.type]);
1330
+ const blobType = _optionalChain([data, 'optionalAccess', _52 => _52.type]);
1321
1331
  return typeof blobType === "string" && blobType ? blobType : DEFAULT_MEDIA_TYPE;
1322
1332
  }
1323
1333
  function normaliseContent(value, field) {
@@ -1343,7 +1353,7 @@ function typeName(value) {
1343
1353
  if (value === null) return "null";
1344
1354
  if (Array.isArray(value)) return "array";
1345
1355
  if (typeof value === "object") {
1346
- return _nullishCoalesce(_optionalChain([value, 'access', _51 => _51.constructor, 'optionalAccess', _52 => _52.name]), () => ( "object"));
1356
+ return _nullishCoalesce(_optionalChain([value, 'access', _53 => _53.constructor, 'optionalAccess', _54 => _54.name]), () => ( "object"));
1347
1357
  }
1348
1358
  return typeof value;
1349
1359
  }
@@ -1360,7 +1370,7 @@ async function resolveFile(part, fetchImpl) {
1360
1370
  bytes = new Uint8Array(await readFile(part.path));
1361
1371
  } catch (error) {
1362
1372
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1363
- `Could not read FilePart path '${part.path}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _53 => _53.message]), () => ( String(error)))}`,
1373
+ `Could not read FilePart path '${part.path}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _55 => _55.message]), () => ( String(error)))}`,
1364
1374
  { cause: error }
1365
1375
  );
1366
1376
  }
@@ -1430,7 +1440,7 @@ async function fetchUrl(url, fetchImpl) {
1430
1440
  );
1431
1441
  }
1432
1442
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1433
- `Could not fetch FilePart url '${url}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _54 => _54.message]), () => ( String(error)))}`,
1443
+ `Could not fetch FilePart url '${url}': ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _56 => _56.message]), () => ( String(error)))}`,
1434
1444
  { cause: error }
1435
1445
  );
1436
1446
  } finally {
@@ -1774,7 +1784,7 @@ function createMemoriesInterface(transport, onForgotten) {
1774
1784
  await transport.checkCustomerId(_nullishCoalesce(o2["customer_id"], () => ( o2["customerId"])), "memories.forget");
1775
1785
  const body = buildForgetBody(options);
1776
1786
  const result = await transport.request("memories_forget", { body });
1777
- const removed = !!_optionalChain([result, 'optionalAccess', _55 => _55.deleted_ids, 'optionalAccess', _56 => _56.length]) || _optionalChain([result, 'optionalAccess', _57 => _57.status]) === "deleted" || _optionalChain([result, 'optionalAccess', _58 => _58.status]) === "partial";
1787
+ const removed = !!_optionalChain([result, 'optionalAccess', _57 => _57.deleted_ids, 'optionalAccess', _58 => _58.length]) || _optionalChain([result, 'optionalAccess', _59 => _59.status]) === "deleted" || _optionalChain([result, 'optionalAccess', _60 => _60.status]) === "partial";
1778
1788
  if (removed && onForgotten) {
1779
1789
  try {
1780
1790
  onForgotten({
@@ -1814,14 +1824,14 @@ function sleep2(ms, signal) {
1814
1824
  if (ms <= 0) return Promise.resolve();
1815
1825
  return new Promise((resolve, reject) => {
1816
1826
  const timer = setTimeout(() => {
1817
- _optionalChain([signal, 'optionalAccess', _59 => _59.removeEventListener, 'call', _60 => _60("abort", onAbort)]);
1827
+ _optionalChain([signal, 'optionalAccess', _61 => _61.removeEventListener, 'call', _62 => _62("abort", onAbort)]);
1818
1828
  resolve();
1819
1829
  }, ms);
1820
1830
  function onAbort() {
1821
1831
  clearTimeout(timer);
1822
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _61 => _61.reason]), () => ( new Error("Aborted"))));
1832
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _63 => _63.reason]), () => ( new Error("Aborted"))));
1823
1833
  }
1824
- _optionalChain([signal, 'optionalAccess', _62 => _62.addEventListener, 'call', _63 => _63("abort", onAbort, { once: true })]);
1834
+ _optionalChain([signal, 'optionalAccess', _64 => _64.addEventListener, 'call', _65 => _65("abort", onAbort, { once: true })]);
1825
1835
  });
1826
1836
  }
1827
1837
 
@@ -1902,7 +1912,7 @@ function buildRecordMessageBody(options, resolvedContent, field = "content") {
1902
1912
  content = resolvedContent;
1903
1913
  } else {
1904
1914
  const n2 = normaliseContent(options.content, field);
1905
- if (_optionalChain([n2, 'optionalAccess', _64 => _64.kind]) === "parts") {
1915
+ if (_optionalChain([n2, 'optionalAccess', _66 => _66.kind]) === "parts") {
1906
1916
  throw new (0, _chunk7IZHVYO2cjs.InvalidInputError)(
1907
1917
  "content holds a FilePart, whose bytes have to be read first. Send it with conversation.record_message."
1908
1918
  );
@@ -2013,7 +2023,7 @@ function storedBatchRows(bodies, result) {
2013
2023
  const r = _nullishCoalesce(result, () => ( {}));
2014
2024
  const results = Array.isArray(r["results"]) ? r["results"] : [];
2015
2025
  const errors = Array.isArray(r["errors"]) ? r["errors"] : [];
2016
- const failed = new Set(errors.map((e) => _optionalChain([e, 'optionalAccess', _65 => _65["index"]])));
2026
+ const failed = new Set(errors.map((e) => _optionalChain([e, 'optionalAccess', _67 => _67["index"]])));
2017
2027
  const stored = bodies.filter((_, index) => !failed.has(index));
2018
2028
  if (stored.length !== results.length) return [];
2019
2029
  const pairs = [];
@@ -2057,7 +2067,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
2057
2067
  };
2058
2068
  const fetchImpl = ((url, init) => transport.fetchExternal(url, init));
2059
2069
  const validateMessage = (options, field = "content") => {
2060
- if (_optionalChain([normaliseContent, 'call', _66 => _66(options.content, field), 'optionalAccess', _67 => _67.kind]) === "parts") {
2070
+ if (_optionalChain([normaliseContent, 'call', _68 => _68(options.content, field), 'optionalAccess', _69 => _69.kind]) === "parts") {
2061
2071
  buildRecordMessageBody(options, "", field);
2062
2072
  } else {
2063
2073
  buildRecordMessageBody(options, void 0, field);
@@ -2065,7 +2075,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
2065
2075
  };
2066
2076
  const prepareMessage = async (options, field = "content") => {
2067
2077
  const n2 = normaliseContent(options.content, field);
2068
- if (_optionalChain([n2, 'optionalAccess', _68 => _68.kind]) !== "parts") {
2078
+ if (_optionalChain([n2, 'optionalAccess', _70 => _70.kind]) !== "parts") {
2069
2079
  const body = buildRecordMessageBody(options, void 0, field);
2070
2080
  return { body, mirror: String(_nullishCoalesce(body["content"], () => ( ""))) };
2071
2081
  }
@@ -2156,7 +2166,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
2156
2166
  const raw = await transport.request("conversations_ingest", { body });
2157
2167
  const result = {
2158
2168
  ...raw,
2159
- warnings: Array.isArray(_optionalChain([raw, 'optionalAccess', _69 => _69.warnings])) ? raw.warnings.map(String) : []
2169
+ warnings: Array.isArray(_optionalChain([raw, 'optionalAccess', _71 => _71.warnings])) ? raw.warnings.map(String) : []
2160
2170
  };
2161
2171
  onWrite({
2162
2172
  userId: body["user_id"],
@@ -2200,8 +2210,8 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
2200
2210
  pathParams: { conversation_id: id },
2201
2211
  query: { style }
2202
2212
  });
2203
- const response = _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _70 => _70["context_for_prompt"]]), () => ( result)), () => ( {}));
2204
- _optionalChain([localShortTerm, 'access', _71 => _71.reseed, 'optionalCall', _72 => _72(id, response)]);
2213
+ const response = _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _72 => _72["context_for_prompt"]]), () => ( result)), () => ( {}));
2214
+ _optionalChain([localShortTerm, 'access', _73 => _73.reseed, 'optionalCall', _74 => _74(id, response)]);
2205
2215
  return withHistory(response);
2206
2216
  },
2207
2217
  async compact(options) {
@@ -2532,11 +2542,12 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2532
2542
  let dispatchCompaction = null;
2533
2543
  let applyCompaction = null;
2534
2544
  let onListen = null;
2545
+ let listenBlockedBy = null;
2535
2546
  let onConversationState = null;
2536
2547
  const internals = {
2537
2548
  onCompactionUpdate(conversationId, bundle) {
2538
- _optionalChain([applyCompaction, 'optionalCall', _73 => _73(bundle)]);
2539
- _optionalChain([dispatchCompaction, 'optionalCall', _74 => _74(conversationId, bundle)]);
2549
+ _optionalChain([applyCompaction, 'optionalCall', _75 => _75(bundle)]);
2550
+ _optionalChain([dispatchCompaction, 'optionalCall', _76 => _76(conversationId, bundle)]);
2540
2551
  },
2541
2552
  setCompactionApplier(apply) {
2542
2553
  applyCompaction = apply;
@@ -2544,14 +2555,17 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2544
2555
  setOnListen(handle) {
2545
2556
  onListen = handle;
2546
2557
  },
2558
+ blockListen(message) {
2559
+ listenBlockedBy = message;
2560
+ },
2547
2561
  setConversationStateHandler(handle) {
2548
2562
  onConversationState = handle;
2549
2563
  },
2550
2564
  sendContextUsed(event) {
2551
- _optionalChain([client, 'optionalAccess', _75 => _75.sendContextUsed, 'call', _76 => _76(event)]);
2565
+ _optionalChain([client, 'optionalAccess', _77 => _77.sendContextUsed, 'call', _78 => _78(event)]);
2552
2566
  },
2553
2567
  sendContextAssembled(event) {
2554
- _optionalChain([client, 'optionalAccess', _77 => _77.sendContextAssembled, 'call', _78 => _78(event)]);
2568
+ _optionalChain([client, 'optionalAccess', _79 => _79.sendContextAssembled, 'call', _80 => _80(event)]);
2555
2569
  },
2556
2570
  setCompactionDispatcher(dispatch) {
2557
2571
  dispatchCompaction = dispatch;
@@ -2583,7 +2597,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2583
2597
  send(sync);
2584
2598
  return Promise.resolve();
2585
2599
  }
2586
- _optionalChain([prepared, 'optionalAccess', _79 => _79.catch, 'call', _80 => _80(() => {
2600
+ _optionalChain([prepared, 'optionalAccess', _81 => _81.catch, 'call', _82 => _82(() => {
2587
2601
  })]);
2588
2602
  queued += 1;
2589
2603
  const run = tail.then(async () => {
@@ -2597,14 +2611,15 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2597
2611
  }
2598
2612
  const namespace = {
2599
2613
  async listen(options = {}) {
2614
+ if (listenBlockedBy !== null) throw new (0, _chunk7IZHVYO2cjs.SynapPermanentError)(listenBlockedBy);
2600
2615
  if (client !== null) {
2601
2616
  throw new (0, _chunk7IZHVYO2cjs.ListeningAlreadyActiveError)("Listening is already active on this instance");
2602
2617
  }
2603
2618
  try {
2604
- _optionalChain([onListen, 'optionalCall', _81 => _81()]);
2619
+ _optionalChain([onListen, 'optionalCall', _83 => _83()]);
2605
2620
  } catch (e13) {
2606
2621
  }
2607
- const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-BY5LNLVB.cjs")));
2622
+ const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-TDHTS7F4.cjs")));
2608
2623
  const onContext = _nullishCoalesce(options.on_context, () => ( options.onContext));
2609
2624
  const onDisconnect = _nullishCoalesce(options.on_disconnect, () => ( options.onDisconnect));
2610
2625
  const onReconnect = _nullishCoalesce(options.on_reconnect, () => ( options.onReconnect));
@@ -2619,17 +2634,17 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2619
2634
  internals.onCompactionUpdate(conversationId, bundle);
2620
2635
  },
2621
2636
  onConversationState: (conversationId, messageCount) => {
2622
- _optionalChain([onConversationState, 'optionalCall', _82 => _82(conversationId, messageCount)]);
2637
+ _optionalChain([onConversationState, 'optionalCall', _84 => _84(conversationId, messageCount)]);
2623
2638
  },
2624
2639
  onStateChange: (state) => {
2625
2640
  if (state !== "connected") openSessions.clear();
2626
2641
  if (state === "reconnecting") {
2627
2642
  reconnectAttempts += 1;
2628
- _optionalChain([onReconnect, 'optionalCall', _83 => _83(reconnectAttempts)]);
2643
+ _optionalChain([onReconnect, 'optionalCall', _85 => _85(reconnectAttempts)]);
2629
2644
  } else if (state === "disconnected") {
2630
- const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _84 => _84.lastError]), () => ( null));
2645
+ const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _86 => _86.lastError]), () => ( null));
2631
2646
  const reason = stopped === null ? "stream disconnected" : `credit_stop:${_nullishCoalesce(stopped.reason, () => ( "unknown"))}`;
2632
- _optionalChain([onDisconnect, 'optionalCall', _85 => _85(reason)]);
2647
+ _optionalChain([onDisconnect, 'optionalCall', _87 => _87(reason)]);
2633
2648
  }
2634
2649
  }
2635
2650
  });
@@ -2639,7 +2654,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2639
2654
  } catch (error) {
2640
2655
  if (error instanceof _chunk7IZHVYO2cjs.SynapError) throw error;
2641
2656
  throw new (0, _chunk7IZHVYO2cjs.SynapError)(
2642
- `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _86 => _86.message]), () => ( String(error)))}`,
2657
+ `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _88 => _88.message]), () => ( String(error)))}`,
2643
2658
  { cause: error }
2644
2659
  );
2645
2660
  }
@@ -2694,7 +2709,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2694
2709
  _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
2695
2710
  );
2696
2711
  if (eventType === "user_message" || eventType === "assistant_message") {
2697
- _optionalChain([onTurn, 'optionalCall', _87 => _87({
2712
+ _optionalChain([onTurn, 'optionalCall', _89 => _89({
2698
2713
  conversationId,
2699
2714
  role: _nullishCoalesce(options.role, () => ( "user")),
2700
2715
  content
@@ -2726,8 +2741,8 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2726
2741
  })()
2727
2742
  });
2728
2743
  };
2729
- if (_optionalChain([parts, 'optionalAccess', _88 => _88.kind]) !== "parts") {
2730
- const content = _optionalChain([parts, 'optionalAccess', _89 => _89.kind]) === "text" ? parts.text : options.content;
2744
+ if (_optionalChain([parts, 'optionalAccess', _90 => _90.kind]) !== "parts") {
2745
+ const content = _optionalChain([parts, 'optionalAccess', _91 => _91.kind]) === "text" ? parts.text : options.content;
2731
2746
  return inOrder(null, emit, { content, metadata: _nullishCoalesce(options.metadata, () => ( {})) });
2732
2747
  }
2733
2748
  const prepared = (async () => {
@@ -2765,7 +2780,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2765
2780
  async record_tool_result(options) {
2766
2781
  const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
2767
2782
  if (conversationId) {
2768
- _optionalChain([onToolResult, 'optionalCall', _90 => _90({ conversationId, result: options.result, toolName: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")) })]);
2783
+ _optionalChain([onToolResult, 'optionalCall', _92 => _92({ conversationId, result: options.result, toolName: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")) })]);
2769
2784
  }
2770
2785
  await namespace.send_message({
2771
2786
  content: "",
@@ -2820,7 +2835,7 @@ function createInstanceNamespace(credentials, cache, onTurn, fetchOrAgentModel,
2820
2835
  }
2821
2836
 
2822
2837
  // src/version.ts
2823
- var SDK_VERSION = "0.6.6";
2838
+ var SDK_VERSION = "0.6.7";
2824
2839
 
2825
2840
  // src/registry.ts
2826
2841
  var instances = /* @__PURE__ */ new Map();
@@ -3288,7 +3303,7 @@ var TurnStore = (_class3 = class {
3288
3303
  }
3289
3304
  /** Turns the server also holds: archived tool results are local only. Python: `count`. */
3290
3305
  count(conversationId) {
3291
- return (_nullishCoalesce(_optionalChain([this, 'access', _91 => _91.#conversations, 'access', _92 => _92.get, 'call', _93 => _93(conversationId), 'optionalAccess', _94 => _94.turns]), () => ( []))).filter((t) => t.role !== "tool").length;
3306
+ return (_nullishCoalesce(_optionalChain([this, 'access', _93 => _93.#conversations, 'access', _94 => _94.get, 'call', _95 => _95(conversationId), 'optionalAccess', _96 => _96.turns]), () => ( []))).filter((t) => t.role !== "tool").length;
3292
3307
  }
3293
3308
  sizeBytes() {
3294
3309
  let n2 = 0;
@@ -3467,7 +3482,7 @@ function askedKinds(query) {
3467
3482
  }
3468
3483
  function asksHowItStarted(query) {
3469
3484
  const spec = _chunkBYUGILQIcjs.HISTORY_SEARCH.early_query;
3470
- if (!_optionalChain([spec, 'optionalAccess', _95 => _95.pattern])) return false;
3485
+ if (!_optionalChain([spec, 'optionalAccess', _97 => _97.pattern])) return false;
3471
3486
  return new RegExp(spec.pattern, (_nullishCoalesce(spec.flags, () => ( ""))).includes("i") ? "i" : "").test(_nullishCoalesce(query, () => ( "")));
3472
3487
  }
3473
3488
  async function searchTurns(turns, query, options = {}) {
@@ -4549,6 +4564,7 @@ var SynapClient = (_class4 = class _SynapClient {
4549
4564
  #closed = false;
4550
4565
  #initialized = false;
4551
4566
  #identity;
4567
+ #localMode = false;
4552
4568
  #registryKeys;
4553
4569
  #compactionSubscribers;
4554
4570
  #shortTerm;
@@ -4567,8 +4583,9 @@ var SynapClient = (_class4 = class _SynapClient {
4567
4583
  #turns;
4568
4584
  #fetchHooks;
4569
4585
  constructor(options = {}) {
4570
- const credentials = resolveCredentials(options);
4571
4586
  const resolvedBaseUrl = resolveBaseUrl(options);
4587
+ const localMode = isLocalMode(options.apiKey, resolvedBaseUrl);
4588
+ const credentials = resolveCredentials(options, localMode);
4572
4589
  validateInstanceId(credentials.instanceId);
4573
4590
  const registryKey = buildRegistryKey(credentials.instanceId, credentials.apiKey);
4574
4591
  if (options._force_new !== true) {
@@ -4584,6 +4601,7 @@ var SynapClient = (_class4 = class _SynapClient {
4584
4601
  }
4585
4602
  }
4586
4603
  this.#registryKeys = options._force_new === true ? [] : [registryKey];
4604
+ this.#localMode = localMode;
4587
4605
  this.#transport = new HttpTransport({
4588
4606
  credentials,
4589
4607
  // SYNAP_BASE_URL is honoured, as Python does (sdk.py) and as the 0.3.x
@@ -4706,7 +4724,7 @@ var SynapClient = (_class4 = class _SynapClient {
4706
4724
  this.#localEncoder = _nullishCoalesce(_nullishCoalesce(options.history_search_encoder, () => ( options.historySearchEncoder)), () => ( null));
4707
4725
  const modelOption = options.history_search_model !== void 0 ? options.history_search_model : options.historySearchModel;
4708
4726
  this.#localModelName = modelOption === void 0 ? "auto" : modelOption;
4709
- if (_optionalChain([this, 'access', _96 => _96.#localEncoder, 'optionalAccess', _97 => _97.model]) === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
4727
+ if (_optionalChain([this, 'access', _98 => _98.#localEncoder, 'optionalAccess', _99 => _99.model]) === _chunkBYUGILQIcjs.SEMANTIC_MATCH.model) this.#anticipationCache.setEncoder(this.#localEncoder);
4710
4728
  this.#turns = new TurnCounter();
4711
4729
  this.conversation = createConversationNamespace(
4712
4730
  this.#transport,
@@ -4783,6 +4801,11 @@ var SynapClient = (_class4 = class _SynapClient {
4783
4801
  (customerId, where) => this.#transport.checkCustomerId(customerId, where)
4784
4802
  );
4785
4803
  this.instance._internal.setOnListen(() => this.#startLocalModel());
4804
+ if (localMode) {
4805
+ this.instance._internal.blockListen(
4806
+ "Not available in the open-source server: listen() needs the gRPC stream and anticipation, which it does not have."
4807
+ );
4808
+ }
4786
4809
  this.instance._internal.setCompactionApplier((bundle) => {
4787
4810
  this.#shortTerm.applyCompaction(bundle);
4788
4811
  });
@@ -4896,12 +4919,15 @@ var SynapClient = (_class4 = class _SynapClient {
4896
4919
  }
4897
4920
  /** Runs whoami at most once, however many calls arrive together. */
4898
4921
  #resolveIdentity() {
4899
- this.#identity ??= this.#whoami();
4922
+ this.#identity ??= this.#whoami().catch((error) => {
4923
+ this.#identity = void 0;
4924
+ throw error;
4925
+ });
4900
4926
  return this.#identity;
4901
4927
  }
4902
4928
  async #whoami() {
4903
4929
  const credentials = this.#transport.currentCredentials();
4904
- if (credentials.clientId !== "" && credentials.instanceId !== "") return;
4930
+ if (!this.#localMode && credentials.clientId !== "" && credentials.instanceId !== "") return;
4905
4931
  try {
4906
4932
  const whoami = await this.#transport.request("whoami", {});
4907
4933
  const resolvedClientId = String(_nullishCoalesce(whoami["client_id"], () => ( "")));
@@ -4917,7 +4943,21 @@ var SynapClient = (_class4 = class _SynapClient {
4917
4943
  this.#registryKeys.push(resolvedInstanceId);
4918
4944
  }
4919
4945
  }
4920
- } catch (e20) {
4946
+ } catch (error) {
4947
+ if (this.#localMode) {
4948
+ throw new (0, _chunk7IZHVYO2cjs.AuthenticationError)(
4949
+ `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', _100 => _100.message]), () => ( String(error)))}).`,
4950
+ { cause: error }
4951
+ );
4952
+ }
4953
+ }
4954
+ if (this.#localMode) {
4955
+ const known = this.#transport.currentCredentials();
4956
+ if (known.clientId === "" || known.instanceId === "") {
4957
+ throw new (0, _chunk7IZHVYO2cjs.AuthenticationError)(
4958
+ `The Synap server at ${this.#transport.baseUrl} did not identify itself: GET /api/v1/auth/whoami returned no client_id or instance_id.`
4959
+ );
4960
+ }
4921
4961
  }
4922
4962
  }
4923
4963
  /**
@@ -5090,7 +5130,7 @@ var SynapClient = (_class4 = class _SynapClient {
5090
5130
  if (conversationState && !merged.scopes_queried.includes("conversation")) {
5091
5131
  merged.scopes_queried.unshift("conversation");
5092
5132
  }
5093
- } catch (e21) {
5133
+ } catch (e20) {
5094
5134
  }
5095
5135
  }
5096
5136
  merged.formatted_context = formatForPrompt(merged, {
@@ -5142,7 +5182,7 @@ var SynapClient = (_class4 = class _SynapClient {
5142
5182
  // not carry the caller's words.
5143
5183
  query_count: distinctQueryCount(_nullishCoalesce(options["search_query"], () => ( options["searchQuery"])))
5144
5184
  });
5145
- } catch (e22) {
5185
+ } catch (e21) {
5146
5186
  }
5147
5187
  }
5148
5188
  /**
@@ -5167,7 +5207,7 @@ var SynapClient = (_class4 = class _SynapClient {
5167
5207
  }),
5168
5208
  scope
5169
5209
  });
5170
- } catch (e23) {
5210
+ } catch (e22) {
5171
5211
  }
5172
5212
  }
5173
5213
  /**
@@ -5228,14 +5268,14 @@ var SynapClient = (_class4 = class _SynapClient {
5228
5268
  }))
5229
5269
  );
5230
5270
  const entry = this.#shortTerm.get(conversationId);
5231
- const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _98 => _98.serverMessageCount]), () => ( 0))) || 0);
5271
+ const total = Math.max(Number(_nullishCoalesce(r["total_message_count"], () => ( 0))) || 0, Number(_nullishCoalesce(_optionalChain([entry, 'optionalAccess', _101 => _101.serverMessageCount]), () => ( 0))) || 0);
5232
5272
  this.#maybeBackfillTurns(conversationId, total);
5233
5273
  if (!r["context_block"]) return response;
5234
5274
  const turns = store.turns(conversationId);
5235
5275
  let q = query;
5236
5276
  if (!q) {
5237
5277
  const latest = [...recent].reverse().find((m) => m["role"] === "user");
5238
- q = latest ? String(_nullishCoalesce(latest["content"], () => ( ""))) : _nullishCoalesce(_optionalChain([[...turns], 'access', _99 => _99.reverse, 'call', _100 => _100(), 'access', _101 => _101.find, 'call', _102 => _102((t) => t.role === "user"), 'optionalAccess', _103 => _103.content]), () => ( ""));
5278
+ q = latest ? String(_nullishCoalesce(latest["content"], () => ( ""))) : _nullishCoalesce(_optionalChain([[...turns], 'access', _102 => _102.reverse, 'call', _103 => _103(), 'access', _104 => _104.find, 'call', _105 => _105((t) => t.role === "user"), 'optionalAccess', _106 => _106.content]), () => ( ""));
5239
5279
  }
5240
5280
  if (!q) return response;
5241
5281
  const exclude = /* @__PURE__ */ new Set();
@@ -5269,7 +5309,7 @@ var SynapClient = (_class4 = class _SynapClient {
5269
5309
  toolResultText(result, _nullishCoalesce(options.tool_name, () => ( options.toolName))),
5270
5310
  _nullishCoalesce(options.timestamp, () => ( (/* @__PURE__ */ new Date()).toISOString()))
5271
5311
  );
5272
- } catch (e24) {
5312
+ } catch (e23) {
5273
5313
  }
5274
5314
  }
5275
5315
  static __initStatic() {this.BACKFILL_COOLDOWN_MS = 6e4}
@@ -5379,18 +5419,19 @@ function pick3(o2, snake, camel) {
5379
5419
  function resolveBaseUrl(options) {
5380
5420
  const explicit = _nullishCoalesce(options.baseUrl, () => ( options.api_base_url));
5381
5421
  if (explicit !== void 0) return explicit;
5382
- const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _104 => _104.trim, 'call', _105 => _105()]);
5422
+ const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _107 => _107.trim, 'call', _108 => _108()]);
5383
5423
  return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
5384
5424
  }
5385
- function resolveCredentials(options) {
5425
+ function resolveCredentials(options, localMode) {
5386
5426
  const apiKey = options.apiKey || _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_KEY");
5387
- if (!apiKey) {
5427
+ if (!apiKey && !localMode) {
5388
5428
  throw new (0, _chunk7IZHVYO2cjs.AuthenticationError)(
5389
5429
  "No Synap API key found. Set SYNAP_API_KEY in your environment, or pass apiKey to the SynapClient constructor."
5390
5430
  );
5391
5431
  }
5392
5432
  return {
5393
- apiKey,
5433
+ // In local mode the credential is the optional token, '' when there is none.
5434
+ apiKey: apiKey || localToken(),
5394
5435
  clientId: _nullishCoalesce(_nullishCoalesce(options.clientId, () => ( _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_CLIENT_ID"))), () => ( "")),
5395
5436
  instanceId: _nullishCoalesce(_nullishCoalesce(options.instanceId, () => ( _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_INSTANCE_ID"))), () => ( ""))
5396
5437
  };