@maximem/synap-js-sdk 0.4.8 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/anticipation-cache-LRE3TLK4.cjs.map +1 -1
  2. package/dist/{chunk-OCMM2Z5P.js → chunk-BWMPKLFG.js} +40 -2
  3. package/dist/chunk-BWMPKLFG.js.map +1 -0
  4. package/dist/{chunk-T5QQBJ6T.js → chunk-DJPYUPSV.js} +530 -7
  5. package/dist/chunk-DJPYUPSV.js.map +1 -0
  6. package/dist/{chunk-2TVL5IPQ.cjs → chunk-T372OL3Q.cjs} +41 -3
  7. package/dist/chunk-T372OL3Q.cjs.map +1 -0
  8. package/dist/chunk-T6U5PVAD.cjs.map +1 -1
  9. package/dist/{chunk-7CWBRHUO.cjs → chunk-WWTGJZA7.cjs} +542 -19
  10. package/dist/chunk-WWTGJZA7.cjs.map +1 -0
  11. package/dist/chunk-ZKOJDUN4.cjs.map +1 -1
  12. package/dist/env-55ULHNJZ.cjs.map +1 -1
  13. package/dist/errors-Bl3vY1eb.d.cts +382 -0
  14. package/dist/errors-Bl3vY1eb.d.ts +382 -0
  15. package/dist/grpc/index.cjs +7 -7
  16. package/dist/grpc/index.cjs.map +1 -1
  17. package/dist/grpc/index.d.cts +50 -4
  18. package/dist/grpc/index.d.ts +50 -4
  19. package/dist/grpc/index.js +5 -5
  20. package/dist/index.cjs +278 -161
  21. package/dist/index.cjs.map +1 -1
  22. package/dist/index.d.cts +97 -148
  23. package/dist/index.d.ts +97 -148
  24. package/dist/index.js +171 -54
  25. package/dist/index.js.map +1 -1
  26. package/dist/stream-client-5CGJNTH4.js +16 -0
  27. package/dist/stream-client-GJM4YSXW.cjs +16 -0
  28. package/dist/stream-client-GJM4YSXW.cjs.map +1 -0
  29. package/package.json +1 -1
  30. package/dist/anticipation-cache-C1rUEpaW.d.cts +0 -211
  31. package/dist/anticipation-cache-C1rUEpaW.d.ts +0 -211
  32. package/dist/chunk-2TVL5IPQ.cjs.map +0 -1
  33. package/dist/chunk-7CWBRHUO.cjs.map +0 -1
  34. package/dist/chunk-OCMM2Z5P.js.map +0 -1
  35. package/dist/chunk-T5QQBJ6T.js.map +0 -1
  36. package/dist/stream-client-2C5KIOWP.js +0 -7
  37. package/dist/stream-client-GPU37E6F.cjs +0 -7
  38. package/dist/stream-client-GPU37E6F.cjs.map +0 -1
  39. /package/dist/{stream-client-2C5KIOWP.js.map → stream-client-5CGJNTH4.js.map} +0 -0
package/dist/index.cjs CHANGED
@@ -8,8 +8,10 @@
8
8
 
9
9
 
10
10
 
11
+ var _chunkT6U5PVADcjs = require('./chunk-T6U5PVAD.cjs');
11
12
 
12
13
 
14
+ var _chunkZKOJDUN4cjs = require('./chunk-ZKOJDUN4.cjs');
13
15
 
14
16
 
15
17
 
@@ -22,7 +24,6 @@
22
24
 
23
25
 
24
26
 
25
- var _chunk2TVL5IPQcjs = require('./chunk-2TVL5IPQ.cjs');
26
27
 
27
28
 
28
29
 
@@ -33,27 +34,10 @@ var _chunk2TVL5IPQcjs = require('./chunk-2TVL5IPQ.cjs');
33
34
 
34
35
 
35
36
 
36
- var _chunkT6U5PVADcjs = require('./chunk-T6U5PVAD.cjs');
37
37
 
38
38
 
39
- var _chunkZKOJDUN4cjs = require('./chunk-ZKOJDUN4.cjs');
40
39
 
41
- // src/util/correlation.ts
42
- function newCorrelationId() {
43
- const c = globalThis.crypto;
44
- if (typeof _optionalChain([c, 'optionalAccess', _ => _.randomUUID]) === "function") return c.randomUUID();
45
- if (typeof _optionalChain([c, 'optionalAccess', _2 => _2.getRandomValues]) === "function") {
46
- const b = c.getRandomValues(new Uint8Array(16));
47
- b[6] = (_nullishCoalesce(b[6], () => ( 0))) & 15 | 64;
48
- b[8] = (_nullishCoalesce(b[8], () => ( 0))) & 63 | 128;
49
- const h = Array.from(b, (x) => x.toString(16).padStart(2, "0")).join("");
50
- return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;
51
- }
52
- return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
53
- const r = Math.random() * 16 | 0;
54
- return (ch === "x" ? r : r & 3 | 8).toString(16);
55
- });
56
- }
40
+ var _chunkT372OL3Qcjs = require('./chunk-T372OL3Q.cjs');
57
41
 
58
42
  // src/transport/endpoints.ts
59
43
  var ENDPOINTS = {
@@ -114,7 +98,7 @@ function shouldRetry(input) {
114
98
  if (attempt >= policy.maxAttempts) {
115
99
  return { retry: false, delaySeconds: 0, reason: "max_attempts_exhausted" };
116
100
  }
117
- if (!_chunk2TVL5IPQcjs.isSynapError.call(void 0, error) || !error.transient) {
101
+ if (!_chunkT372OL3Qcjs.isSynapError.call(void 0, error) || !error.transient) {
118
102
  return { retry: false, delaySeconds: 0, reason: "not_transient" };
119
103
  }
120
104
  const idempotent = _nullishCoalesce(input.idempotent, () => ( IDEMPOTENT_METHODS.has(method.toUpperCase())));
@@ -132,7 +116,7 @@ function shouldRetry(input) {
132
116
  };
133
117
  }
134
118
  function backoffDelay(error, attempt, policy) {
135
- if (error instanceof _chunk2TVL5IPQcjs.RateLimitError && error.retryAfterSeconds != null) {
119
+ if (error instanceof _chunkT372OL3Qcjs.RateLimitError && error.retryAfterSeconds != null) {
136
120
  return Math.min(error.retryAfterSeconds, policy.backoffMax);
137
121
  }
138
122
  const exponential = policy.backoffBase * 2 ** (attempt - 1);
@@ -147,7 +131,7 @@ var HEARTBEAT_INTERVAL_MS = 24e4;
147
131
  var MAX_CONNECTIONS = 20;
148
132
  var cached;
149
133
  function supportsDispatcher() {
150
- return typeof process !== "undefined" && _optionalChain([process, 'access', _3 => _3.versions, 'optionalAccess', _4 => _4.node]) !== void 0 && // Edge builds of Next expose a partial `process` shim, but no real Node.
134
+ return typeof process !== "undefined" && _optionalChain([process, 'access', _ => _.versions, 'optionalAccess', _2 => _2.node]) !== void 0 && // Edge builds of Next expose a partial `process` shim, but no real Node.
151
135
  typeof globalThis.EdgeRuntime === "undefined";
152
136
  }
153
137
  async function getKeepAliveDispatcher(options = {}) {
@@ -188,7 +172,7 @@ var Heartbeat = (_class = class {
188
172
  void Promise.resolve(this.ping()).catch(() => {
189
173
  });
190
174
  }, this.intervalMs);
191
- _optionalChain([this, 'access', _5 => _5.timer, 'access', _6 => _6.unref, 'optionalCall', _7 => _7()]);
175
+ _optionalChain([this, 'access', _3 => _3.timer, 'access', _4 => _4.unref, 'optionalCall', _5 => _5()]);
192
176
  }
193
177
  stop() {
194
178
  if (this.timer !== null) {
@@ -206,7 +190,7 @@ var B2C_ISOLATION = "equals_customer";
206
190
  function checkCustomerId(isolation, customerId, where, instanceId) {
207
191
  if (customerId === void 0 || customerId === null || customerId === "") return;
208
192
  if (isolation !== B2C_ISOLATION) return;
209
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(
193
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
210
194
  `${where}: customer_id is not accepted on this instance${instanceId ? ` (${instanceId})` : ""}, which is B2C (user_context_isolation='${B2C_ISOLATION}'). Send user_id only; it is the whole identity, and the server files and reads your data under it. Received customer_id=${JSON.stringify(customerId)}.`
211
195
  );
212
196
  }
@@ -241,7 +225,7 @@ var HttpTransport = (_class2 = class {
241
225
  this.keepAliveOptions = _nullishCoalesce(options.keepAlive, () => ( {}));
242
226
  this.heartbeat = new Heartbeat(
243
227
  () => this.pingHealth(),
244
- _nullishCoalesce(_optionalChain([options, 'access', _8 => _8.keepAlive, 'optionalAccess', _9 => _9.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
228
+ _nullishCoalesce(_optionalChain([options, 'access', _6 => _6.keepAlive, 'optionalAccess', _7 => _7.heartbeatIntervalMs]), () => ( HEARTBEAT_INTERVAL_MS))
245
229
  );
246
230
  }
247
231
  /** Start keeping the connection warm. Opt-in: it is pointless in serverless. */
@@ -308,7 +292,7 @@ var HttpTransport = (_class2 = class {
308
292
  }
309
293
  async request(name, options = {}) {
310
294
  const spec = ENDPOINTS[name];
311
- const correlationId = _nullishCoalesce(options.correlationId, () => ( newCorrelationId()));
295
+ const correlationId = _nullishCoalesce(options.correlationId, () => ( _chunkT372OL3Qcjs.newCorrelationId.call(void 0, )));
312
296
  const idempotent = _nullishCoalesce(options.idempotent, () => ( spec.idempotent));
313
297
  let attempt = 0;
314
298
  let last = null;
@@ -330,7 +314,7 @@ var HttpTransport = (_class2 = class {
330
314
  await sleep(decision.delaySeconds * 1e3, options.signal);
331
315
  }
332
316
  }
333
- throw _nullishCoalesce(_optionalChain([last, 'optionalAccess', _10 => _10.error]), () => ( new (0, _chunk2TVL5IPQcjs.SynapError)("Request failed with no recorded error")));
317
+ throw _nullishCoalesce(_optionalChain([last, 'optionalAccess', _8 => _8.error]), () => ( new (0, _chunkT372OL3Qcjs.SynapError)("Request failed with no recorded error")));
334
318
  }
335
319
  async attempt(name, options, correlationId) {
336
320
  const spec = ENDPOINTS[name];
@@ -363,7 +347,7 @@ var HttpTransport = (_class2 = class {
363
347
  try {
364
348
  return JSON.parse(text);
365
349
  } catch (e3) {
366
- throw new (0, _chunk2TVL5IPQcjs.SynapError)(`Malformed JSON in response from ${url}`, { correlationId });
350
+ throw new (0, _chunkT372OL3Qcjs.SynapError)(`Malformed JSON in response from ${url}`, { correlationId });
367
351
  }
368
352
  }
369
353
  buildUrl(path, query) {
@@ -397,32 +381,42 @@ var HttpTransport = (_class2 = class {
397
381
  }
398
382
  }, _class2);
399
383
  function isOutcomeUnknown(error) {
400
- if (error instanceof _chunk2TVL5IPQcjs.RateLimitError) return false;
401
- if (error instanceof _chunk2TVL5IPQcjs.ServiceUnavailableError) return false;
402
- if (error instanceof _chunk2TVL5IPQcjs.AuthenticationError) return false;
403
- if (error instanceof _chunk2TVL5IPQcjs.InvalidInputError) return false;
404
- if (error instanceof _chunk2TVL5IPQcjs.ConflictError) return false;
405
- if (error instanceof _chunk2TVL5IPQcjs.InsufficientCreditsError) return false;
406
- if (error instanceof _chunk2TVL5IPQcjs.ContextNotFoundError) return false;
407
- if (error instanceof _chunk2TVL5IPQcjs.NetworkTimeoutError) return true;
384
+ if (error instanceof _chunkT372OL3Qcjs.RateLimitError) return false;
385
+ if (error instanceof _chunkT372OL3Qcjs.ServiceUnavailableError) return false;
386
+ if (error instanceof _chunkT372OL3Qcjs.AuthenticationError) return false;
387
+ if (error instanceof _chunkT372OL3Qcjs.InvalidInputError) return false;
388
+ if (error instanceof _chunkT372OL3Qcjs.ConflictError) return false;
389
+ if (error instanceof _chunkT372OL3Qcjs.InsufficientCreditsError) return false;
390
+ if (error instanceof _chunkT372OL3Qcjs.ContextNotFoundError) return false;
391
+ if (error instanceof _chunkT372OL3Qcjs.NetworkTimeoutError) return true;
408
392
  if (isConnectionRefusal(error)) return false;
409
393
  return true;
410
394
  }
411
395
  function isConnectionRefusal(error) {
412
- const code = _nullishCoalesce(_optionalChain([error, 'optionalAccess', _11 => _11.cause, 'optionalAccess', _12 => _12.code]), () => ( _optionalChain([error, 'optionalAccess', _13 => _13.code])));
396
+ const code = _nullishCoalesce(_optionalChain([error, 'optionalAccess', _9 => _9.cause, 'optionalAccess', _10 => _10.code]), () => ( _optionalChain([error, 'optionalAccess', _11 => _11.code])));
413
397
  return code === "ECONNREFUSED" || code === "ENOTFOUND" || code === "EAI_AGAIN" || code === "ECONNRESET" || code === "EHOSTUNREACH";
414
398
  }
415
399
  function toTransportError(error, correlationId) {
416
- if (error instanceof _chunk2TVL5IPQcjs.SynapError) return error;
417
- const name = _optionalChain([error, 'optionalAccess', _14 => _14.name]);
400
+ if (error instanceof _chunkT372OL3Qcjs.SynapError) return error;
401
+ const name = _optionalChain([error, 'optionalAccess', _12 => _12.name]);
418
402
  if (name === "AbortError" || name === "TimeoutError") {
419
- return new (0, _chunk2TVL5IPQcjs.NetworkTimeoutError)("Request timed out", { correlationId, cause: error });
403
+ return new (0, _chunkT372OL3Qcjs.NetworkTimeoutError)("Request timed out", { correlationId, cause: error });
420
404
  }
421
- return new (0, _chunk2TVL5IPQcjs.ServiceUnavailableError)(
422
- `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _15 => _15.message]), () => ( String(error)))}`,
405
+ return new (0, _chunkT372OL3Qcjs.ServiceUnavailableError)(
406
+ `Network request failed: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _13 => _13.message]), () => ( String(error)))}`,
423
407
  { correlationId, cause: error }
424
408
  );
425
409
  }
410
+ var CREDIT_ERRORS = /* @__PURE__ */ new Set(["insufficient_credits", "trial_limit_reached"]);
411
+ function creditPayload(parsed, detailObject) {
412
+ return _nullishCoalesce(detailObject, () => ( parsed));
413
+ }
414
+ function creditReason(payload) {
415
+ const reason = stringOrNull(payload["reason"]);
416
+ if (reason !== null) return reason;
417
+ const error = stringOrNull(payload["error"]);
418
+ return error !== null && CREDIT_ERRORS.has(error) ? error : null;
419
+ }
426
420
  async function toHttpError(response, correlationId) {
427
421
  const body = await response.text().catch(() => "");
428
422
  let parsed = {};
@@ -438,40 +432,48 @@ async function toHttpError(response, correlationId) {
438
432
  switch (response.status) {
439
433
  case 400:
440
434
  case 422:
441
- return new (0, _chunk2TVL5IPQcjs.InvalidInputError)(message, opts);
435
+ return new (0, _chunkT372OL3Qcjs.InvalidInputError)(message, opts);
442
436
  case 401:
443
437
  case 403:
444
- return new (0, _chunk2TVL5IPQcjs.AuthenticationError)(message, opts);
438
+ return new (0, _chunkT372OL3Qcjs.AuthenticationError)(message, opts);
445
439
  case 404:
446
- return new (0, _chunk2TVL5IPQcjs.ContextNotFoundError)(message, opts);
447
- case 402:
448
- return new (0, _chunk2TVL5IPQcjs.InsufficientCreditsError)(message, {
440
+ return new (0, _chunkT372OL3Qcjs.ContextNotFoundError)(message, opts);
441
+ case 402: {
442
+ const credit = creditPayload(parsed, detailObject);
443
+ return new (0, _chunkT372OL3Qcjs.InsufficientCreditsError)(message, {
449
444
  ...opts,
450
- balanceCredits: numberOrNull(parsed["balance_credits"]),
451
- requiredCredits: _nullishCoalesce(numberOrNull(parsed["minimum_required_credits"]), () => ( numberOrNull(parsed["required_credits"]))),
452
- recoveryUrl: stringOrNull(parsed["recovery_url"]),
453
- redeemUrl: stringOrNull(parsed["redeem_url"])
445
+ balanceCredits: numberOrNull(credit["balance_credits"]),
446
+ requiredCredits: _nullishCoalesce(numberOrNull(credit["minimum_required_credits"]), () => ( numberOrNull(credit["required_credits"]))),
447
+ recoveryUrl: stringOrNull(credit["recovery_url"]),
448
+ redeemUrl: stringOrNull(credit["redeem_url"]),
449
+ reason: creditReason(credit),
450
+ manageUrl: stringOrNull(credit["manage_url"])
454
451
  });
452
+ }
455
453
  case 409:
456
454
  if (detailObject !== null && detailObject["code"] === "transcript_conflict") {
457
- return new (0, _chunk2TVL5IPQcjs.TranscriptConflictError)(message, opts);
455
+ return new (0, _chunkT372OL3Qcjs.TranscriptConflictError)(message, opts);
458
456
  }
459
- return new (0, _chunk2TVL5IPQcjs.ConflictError)(message, opts);
457
+ return new (0, _chunkT372OL3Qcjs.ConflictError)(message, opts);
460
458
  case 429: {
461
459
  const header = response.headers.get("retry-after");
462
460
  const retryAfter = header !== null && header.trim() !== "" ? Number(header) : null;
463
- return new (0, _chunk2TVL5IPQcjs.RateLimitError)(message, {
461
+ const credit = creditPayload(parsed, detailObject);
462
+ return new (0, _chunkT372OL3Qcjs.RateLimitError)(message, {
464
463
  ...opts,
465
- retryAfterSeconds: retryAfter !== null && Number.isFinite(retryAfter) ? retryAfter : null
464
+ retryAfterSeconds: retryAfter !== null && Number.isFinite(retryAfter) ? retryAfter : null,
465
+ reason: creditReason(credit),
466
+ upgradeUrl: stringOrNull(credit["upgrade_url"]),
467
+ manageUrl: stringOrNull(credit["manage_url"])
466
468
  });
467
469
  }
468
470
  case 503:
469
- return new (0, _chunk2TVL5IPQcjs.ServiceUnavailableError)(message, opts);
471
+ return new (0, _chunkT372OL3Qcjs.ServiceUnavailableError)(message, opts);
470
472
  case 504:
471
- return new (0, _chunk2TVL5IPQcjs.AgentUnavailableError)(message, opts);
473
+ return new (0, _chunkT372OL3Qcjs.AgentUnavailableError)(message, opts);
472
474
  default:
473
- if (response.status >= 500) return new (0, _chunk2TVL5IPQcjs.ServiceUnavailableError)(message, opts);
474
- return new (0, _chunk2TVL5IPQcjs.SynapError)(message, opts);
475
+ if (response.status >= 500) return new (0, _chunkT372OL3Qcjs.ServiceUnavailableError)(message, opts);
476
+ return new (0, _chunkT372OL3Qcjs.SynapError)(message, opts);
475
477
  }
476
478
  }
477
479
  function numberOrNull(v) {
@@ -482,11 +484,11 @@ function stringOrNull(v) {
482
484
  }
483
485
  function withTimeout(ms, external) {
484
486
  const controller = new AbortController();
485
- const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _16 => _16.reason]));
487
+ const onExternalAbort = () => controller.abort(_optionalChain([external, 'optionalAccess', _14 => _14.reason]));
486
488
  const timer = setTimeout(() => {
487
- controller.abort(new (0, _chunk2TVL5IPQcjs.NetworkTimeoutError)(`Timed out after ${ms}ms`));
489
+ controller.abort(new (0, _chunkT372OL3Qcjs.NetworkTimeoutError)(`Timed out after ${ms}ms`));
488
490
  }, ms);
489
- _optionalChain([timer, 'access', _17 => _17.unref, 'optionalCall', _18 => _18()]);
491
+ _optionalChain([timer, 'access', _15 => _15.unref, 'optionalCall', _16 => _16()]);
490
492
  if (external) {
491
493
  if (external.aborted) onExternalAbort();
492
494
  else external.addEventListener("abort", onExternalAbort, { once: true });
@@ -495,7 +497,7 @@ function withTimeout(ms, external) {
495
497
  signal: controller.signal,
496
498
  dispose() {
497
499
  clearTimeout(timer);
498
- _optionalChain([external, 'optionalAccess', _19 => _19.removeEventListener, 'call', _20 => _20("abort", onExternalAbort)]);
500
+ _optionalChain([external, 'optionalAccess', _17 => _17.removeEventListener, 'call', _18 => _18("abort", onExternalAbort)]);
499
501
  }
500
502
  };
501
503
  }
@@ -503,14 +505,14 @@ function sleep(ms, signal) {
503
505
  if (ms <= 0) return Promise.resolve();
504
506
  return new Promise((resolve, reject) => {
505
507
  const timer = setTimeout(() => {
506
- _optionalChain([signal, 'optionalAccess', _21 => _21.removeEventListener, 'call', _22 => _22("abort", onAbort)]);
508
+ _optionalChain([signal, 'optionalAccess', _19 => _19.removeEventListener, 'call', _20 => _20("abort", onAbort)]);
507
509
  resolve();
508
510
  }, ms);
509
511
  function onAbort() {
510
512
  clearTimeout(timer);
511
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _23 => _23.reason]), () => ( new Error("Aborted"))));
513
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _21 => _21.reason]), () => ( new Error("Aborted"))));
512
514
  }
513
- _optionalChain([signal, 'optionalAccess', _24 => _24.addEventListener, 'call', _25 => _25("abort", onAbort, { once: true })]);
515
+ _optionalChain([signal, 'optionalAccess', _22 => _22.addEventListener, 'call', _23 => _23("abort", onAbort, { once: true })]);
514
516
  });
515
517
  }
516
518
 
@@ -536,10 +538,10 @@ function buildFetchRequest(scope, options) {
536
538
  const precisionLevel = _nullishCoalesce(opt(options, "precision_level", "precisionLevel"), () => ( "high"));
537
539
  const mode = _nullishCoalesce(options.mode, () => ( "fast"));
538
540
  if (searchQuery !== void 0 && !Array.isArray(searchQuery)) {
539
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("search_query must be an array when provided");
541
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("search_query must be an array when provided");
540
542
  }
541
543
  if (options.types !== void 0 && !Array.isArray(options.types)) {
542
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("types must be an array when provided");
544
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("types must be an array when provided");
543
545
  }
544
546
  const body = {
545
547
  conversation_id: _nullishCoalesce(conversationId, () => ( null)),
@@ -555,22 +557,22 @@ function buildFetchRequest(scope, options) {
555
557
  switch (scope) {
556
558
  case "user":
557
559
  {
558
- if (!userId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("user_id is required");
560
+ if (!userId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("user_id is required");
559
561
  body["user_id"] = userId;
560
562
  const scopePath = opt(options, "scope_path", "scopePath");
561
563
  if (scopePath !== void 0) body["scope"] = scopePath;
562
564
  const contextMode = _nullishCoalesce(opt(options, "context_mode", "contextMode"), () => ( "in-conversation"));
563
565
  if (!VALID_CONTEXT_MODES.includes(contextMode)) {
564
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(
566
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
565
567
  `Invalid context_mode '${contextMode}'. Must be one of: ${VALID_CONTEXT_MODES.join(", ")}`
566
568
  );
567
569
  }
568
570
  const lastN = _nullishCoalesce(opt(options, "last_n_conversations", "lastNConversations"), () => ( 1));
569
571
  if (!Number.isInteger(lastN)) {
570
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("last_n_conversations must be an integer");
572
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("last_n_conversations must be an integer");
571
573
  }
572
574
  if (lastN < 0 || lastN > 20) {
573
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("last_n_conversations must be between 0 and 20");
575
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("last_n_conversations must be between 0 and 20");
574
576
  }
575
577
  if (contextMode === "conversation-summary") {
576
578
  body["context_mode"] = contextMode;
@@ -582,11 +584,11 @@ function buildFetchRequest(scope, options) {
582
584
  }
583
585
  break;
584
586
  case "customer":
585
- if (!customerId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("customer_id is required");
587
+ if (!customerId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("customer_id is required");
586
588
  body["customer_id"] = customerId;
587
589
  break;
588
590
  case "conversation":
589
- if (!conversationId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("conversation_id is required");
591
+ if (!conversationId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("conversation_id is required");
590
592
  if (userId !== void 0) body["user_id"] = userId;
591
593
  if (customerId !== void 0) body["customer_id"] = customerId;
592
594
  break;
@@ -602,16 +604,16 @@ async function fetchContext(transport, scope, options = {}, hooks = {}) {
602
604
  opt(options, "customer_id", "customerId"),
603
605
  `${scope}.context.fetch`
604
606
  );
605
- const anticipated = _nullishCoalesce(_optionalChain([hooks, 'access', _26 => _26.beforeFetch, 'optionalCall', _27 => _27(scope, options)]), () => ( null));
607
+ const anticipated = _nullishCoalesce(_optionalChain([hooks, 'access', _24 => _24.beforeFetch, 'optionalCall', _25 => _25(scope, options)]), () => ( null));
606
608
  if (anticipated !== null) {
607
- _optionalChain([hooks, 'access', _28 => _28.onServedFromCache, 'optionalCall', _29 => _29(scope, options, anticipated)]);
608
- _optionalChain([hooks, 'access', _30 => _30.onAssembled, 'optionalCall', _31 => _31(scope, options, anticipated.response, startedAt)]);
609
+ _optionalChain([hooks, 'access', _26 => _26.onServedFromCache, 'optionalCall', _27 => _27(scope, options, anticipated)]);
610
+ _optionalChain([hooks, 'access', _28 => _28.onAssembled, 'optionalCall', _29 => _29(scope, options, anticipated.response, startedAt)]);
609
611
  return anticipated.response;
610
612
  }
611
613
  const { endpoint, body } = buildFetchRequest(scope, options);
612
614
  const result = await transport.request(endpoint, { body });
613
- const response = _nullishCoalesce(_optionalChain([result, 'optionalAccess', _32 => _32["context"]]), () => ( {}));
614
- _optionalChain([hooks, 'access', _33 => _33.onAssembled, 'optionalCall', _34 => _34(scope, options, response, startedAt)]);
615
+ const response = _nullishCoalesce(_optionalChain([result, 'optionalAccess', _30 => _30["context"]]), () => ( {}));
616
+ _optionalChain([hooks, 'access', _31 => _31.onAssembled, 'optionalCall', _32 => _32(scope, options, response, startedAt)]);
615
617
  return response;
616
618
  }
617
619
 
@@ -831,17 +833,17 @@ function isoOrNull(v) {
831
833
  return v instanceof Date ? v.toISOString() : v;
832
834
  }
833
835
  function buildCreateBody(options) {
834
- if (!options.document) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("document is required");
836
+ if (!options.document) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("document is required");
835
837
  const o2 = options;
836
838
  const documentType = _nullishCoalesce(either(o2, "document_type", "documentType"), () => ( DEFAULT_DOCUMENT_TYPE));
837
839
  const mode = _nullishCoalesce(options.mode, () => ( DEFAULT_INGEST_MODE));
838
840
  if (!DOCUMENT_TYPES.includes(documentType)) {
839
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(
841
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
840
842
  `Invalid document_type '${documentType}'. Expected one of: ${DOCUMENT_TYPES.join(", ")}`
841
843
  );
842
844
  }
843
845
  if (!INGEST_MODES.includes(mode)) {
844
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(
846
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
845
847
  `Invalid mode '${mode}'. Expected one of: ${INGEST_MODES.join(", ")}`
846
848
  );
847
849
  }
@@ -873,7 +875,7 @@ function createMemoriesInterface(transport) {
873
875
  async batch_create(options) {
874
876
  const docs = options.documents;
875
877
  if (!Array.isArray(docs) || docs.length === 0) {
876
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("documents must be a non-empty array");
878
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("documents must be a non-empty array");
877
879
  }
878
880
  const failFast = _nullishCoalesce(_nullishCoalesce(options.fail_fast, () => ( options.failFast)), () => ( false));
879
881
  return transport.request("memories_batch", {
@@ -883,15 +885,15 @@ function createMemoriesInterface(transport) {
883
885
  async create_from_file(options) {
884
886
  const userId = _nullishCoalesce(options.user_id, () => ( options.userId));
885
887
  const customerId = _nullishCoalesce(options.customer_id, () => ( options.customerId));
886
- if (!userId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("user_id is required");
888
+ if (!userId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("user_id is required");
887
889
  transport.checkCustomerId(customerId, "memories.create_from_file");
888
890
  const filePath = _nullishCoalesce(options.file_path, () => ( options.filePath));
889
891
  const sources = [filePath, options.file, options.text].filter((v) => v !== void 0);
890
892
  if (sources.length === 0) {
891
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("One of file_path, file, or text must be provided.");
893
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("One of file_path, file, or text must be provided.");
892
894
  }
893
895
  if (sources.length > 1) {
894
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(
896
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
895
897
  "Provide exactly one of file_path, file, or text, not several."
896
898
  );
897
899
  }
@@ -922,13 +924,13 @@ function createMemoriesInterface(transport) {
922
924
  });
923
925
  },
924
926
  async get(memoryId) {
925
- if (!memoryId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("memory_id is required");
927
+ if (!memoryId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("memory_id is required");
926
928
  return transport.request("memories_get", { pathParams: { memory_id: memoryId } });
927
929
  },
928
930
  async update(options) {
929
931
  const memoryId = _nullishCoalesce(options.memory_id, () => ( options.memoryId));
930
- if (!memoryId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("memory_id is required");
931
- if (!options.document) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("document is required");
932
+ if (!memoryId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("memory_id is required");
933
+ if (!options.document) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("document is required");
932
934
  const body = {
933
935
  document: options.document,
934
936
  merge_strategy: _nullishCoalesce(_nullishCoalesce(options.merge_strategy, () => ( options.mergeStrategy)), () => ( "smart-merge"))
@@ -943,20 +945,20 @@ function createMemoriesInterface(transport) {
943
945
  },
944
946
  async delete(memoryId) {
945
947
  if (!memoryId) {
946
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(
948
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
947
949
  "memory_id is required. Deleting by user is no longer supported: the previous implementation tracked ids in process memory, so it silently deleted nothing in any serverless or multi-process deployment while reporting success."
948
950
  );
949
951
  }
950
952
  return transport.request("memories_delete", { pathParams: { memory_id: memoryId } });
951
953
  },
952
954
  async status(ingestionId) {
953
- if (!ingestionId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("ingestion_id is required");
955
+ if (!ingestionId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("ingestion_id is required");
954
956
  return transport.request("memories_status", {
955
957
  pathParams: { ingestion_id: ingestionId }
956
958
  });
957
959
  },
958
960
  async wait_for_completion(ingestionId, options = {}) {
959
- if (!ingestionId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("ingestion_id is required");
961
+ if (!ingestionId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("ingestion_id is required");
960
962
  const timeoutMs = (_nullishCoalesce(_nullishCoalesce(options.timeout_seconds, () => ( options.timeoutSeconds)), () => ( 300))) * 1e3;
961
963
  const pollMs = (_nullishCoalesce(_nullishCoalesce(options.poll_interval_seconds, () => ( options.pollIntervalSeconds)), () => ( 2))) * 1e3;
962
964
  const deadline = Date.now() + timeoutMs;
@@ -977,14 +979,14 @@ function sleep2(ms, signal) {
977
979
  if (ms <= 0) return Promise.resolve();
978
980
  return new Promise((resolve, reject) => {
979
981
  const timer = setTimeout(() => {
980
- _optionalChain([signal, 'optionalAccess', _35 => _35.removeEventListener, 'call', _36 => _36("abort", onAbort)]);
982
+ _optionalChain([signal, 'optionalAccess', _33 => _33.removeEventListener, 'call', _34 => _34("abort", onAbort)]);
981
983
  resolve();
982
984
  }, ms);
983
985
  function onAbort() {
984
986
  clearTimeout(timer);
985
- reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _37 => _37.reason]), () => ( new Error("Aborted"))));
987
+ reject(_nullishCoalesce(_optionalChain([signal, 'optionalAccess', _35 => _35.reason]), () => ( new Error("Aborted"))));
986
988
  }
987
- _optionalChain([signal, 'optionalAccess', _38 => _38.addEventListener, 'call', _39 => _39("abort", onAbort, { once: true })]);
989
+ _optionalChain([signal, 'optionalAccess', _36 => _36.addEventListener, 'call', _37 => _37("abort", onAbort, { once: true })]);
988
990
  });
989
991
  }
990
992
 
@@ -994,13 +996,13 @@ var UUID_RE = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9
994
996
  function validateConversationId(conversationId) {
995
997
  if (conversationId === void 0 || conversationId === null || conversationId === "") return;
996
998
  if (typeof conversationId !== "string" || !UUID_RE.test(conversationId)) {
997
- throw new (0, _chunk2TVL5IPQcjs.InvalidConversationIdError)(`Invalid conversation ID: ${String(conversationId)}`);
999
+ throw new (0, _chunkT372OL3Qcjs.InvalidConversationIdError)(`Invalid conversation ID: ${String(conversationId)}`);
998
1000
  }
999
1001
  }
1000
1002
  function validateInstanceId(instanceId) {
1001
1003
  if (instanceId === void 0 || instanceId === null || instanceId === "") return;
1002
1004
  if (typeof instanceId !== "string" || !INSTANCE_ID_RE.test(instanceId)) {
1003
- throw new (0, _chunk2TVL5IPQcjs.InvalidInstanceIdError)(`Invalid instance ID: ${String(instanceId)}`);
1005
+ throw new (0, _chunkT372OL3Qcjs.InvalidInstanceIdError)(`Invalid instance ID: ${String(instanceId)}`);
1004
1006
  }
1005
1007
  }
1006
1008
 
@@ -1029,13 +1031,13 @@ function buildRecordMessageBody(options) {
1029
1031
  const conversationId = either2(o2, "conversation_id", "conversationId");
1030
1032
  const userId = either2(o2, "user_id", "userId");
1031
1033
  const customerId = either2(o2, "customer_id", "customerId");
1032
- if (!conversationId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("conversation_id is required");
1034
+ if (!conversationId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("conversation_id is required");
1033
1035
  validateConversationId(conversationId);
1034
- if (!options.role) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("role is required");
1036
+ if (!options.role) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("role is required");
1035
1037
  if (options.content === void 0 || options.content === null) {
1036
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("content is required");
1038
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("content is required");
1037
1039
  }
1038
- if (!userId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("user_id is required");
1040
+ if (!userId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("user_id is required");
1039
1041
  const body = {
1040
1042
  conversation_id: conversationId,
1041
1043
  role: options.role,
@@ -1047,16 +1049,18 @@ function buildRecordMessageBody(options) {
1047
1049
  };
1048
1050
  const sessionId = either2(o2, "session_id", "sessionId");
1049
1051
  if (sessionId !== void 0) body["session_id"] = sessionId;
1052
+ const scopePath = either2(o2, "scope_path", "scopePath");
1053
+ if (scopePath !== void 0) body["scope"] = scopePath;
1050
1054
  return body;
1051
1055
  }
1052
1056
  function buildIngestTranscriptBody(options) {
1053
1057
  const o2 = options;
1054
1058
  const conversationId = either2(o2, "conversation_id", "conversationId");
1055
1059
  const userId = either2(o2, "user_id", "userId");
1056
- if (!conversationId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("conversation_id is required");
1057
- if (!userId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("user_id is required");
1060
+ if (!conversationId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("conversation_id is required");
1061
+ if (!userId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("user_id is required");
1058
1062
  if (options.transcript === void 0 || options.transcript === null) {
1059
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("transcript is required");
1063
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("transcript is required");
1060
1064
  }
1061
1065
  const body = {
1062
1066
  conversation_id: conversationId,
@@ -1073,12 +1077,14 @@ function buildIngestTranscriptBody(options) {
1073
1077
  if (options.metadata !== void 0) body["metadata"] = options.metadata;
1074
1078
  if (startedAt !== void 0) body["started_at"] = startedAt;
1075
1079
  if (endedAt !== void 0) body["ended_at"] = endedAt;
1080
+ const scopePath = either2(o2, "scope_path", "scopePath");
1081
+ if (scopePath !== void 0) body["scope"] = scopePath;
1076
1082
  return body;
1077
1083
  }
1078
1084
  function buildCompactBody(options) {
1079
1085
  const o2 = options;
1080
1086
  const conversationId = either2(o2, "conversation_id", "conversationId");
1081
- if (!conversationId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("conversation_id is required");
1087
+ if (!conversationId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("conversation_id is required");
1082
1088
  validateConversationId(conversationId);
1083
1089
  const body = { conversation_id: conversationId, force: _nullishCoalesce(options.force, () => ( false)) };
1084
1090
  const strategy = _nullishCoalesce(options.strategy, () => ( either2(o2, "compaction_level", "compactionLevel")));
@@ -1134,7 +1140,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1134
1140
  }, localShortTerm = { prompt: () => null, compacted: () => null }) {
1135
1141
  const convId = (v) => {
1136
1142
  const id = typeof v === "string" ? v : _nullishCoalesce(v.conversation_id, () => ( v.conversationId));
1137
- if (!id) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("conversation_id is required");
1143
+ if (!id) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("conversation_id is required");
1138
1144
  validateConversationId(id);
1139
1145
  return id;
1140
1146
  };
@@ -1160,7 +1166,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1160
1166
  },
1161
1167
  async record_messages_batch(messages) {
1162
1168
  if (!Array.isArray(messages) || messages.length === 0) {
1163
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("messages must be a non-empty array");
1169
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("messages must be a non-empty array");
1164
1170
  }
1165
1171
  for (const m of messages) {
1166
1172
  const mo = m;
@@ -1219,7 +1225,7 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1219
1225
  pathParams: { conversation_id: id },
1220
1226
  query: { style: _nullishCoalesce(options.style, () => ( "structured")) }
1221
1227
  });
1222
- return _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _40 => _40["context_for_prompt"]]), () => ( result)), () => ( {}));
1228
+ return _nullishCoalesce(_nullishCoalesce(_optionalChain([result, 'optionalAccess', _38 => _38["context_for_prompt"]]), () => ( result)), () => ( {}));
1223
1229
  },
1224
1230
  async compact(options) {
1225
1231
  return transport.request("conversations_compact", { body: buildCompactBody(options) });
@@ -1258,8 +1264,8 @@ function createConversationNamespace(transport, subscribers = new CompactionSubs
1258
1264
  * Returns an idempotent unsubscribe thunk, matching Python.
1259
1265
  */
1260
1266
  subscribe_to_compaction_updates(conversationId, callback) {
1261
- if (!conversationId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("conversation_id is required");
1262
- if (typeof callback !== "function") throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("callback is required");
1267
+ if (!conversationId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("conversation_id is required");
1268
+ if (typeof callback !== "function") throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("callback is required");
1263
1269
  return subscribers.add(conversationId, callback);
1264
1270
  },
1265
1271
  /** Remove subscribers for one conversation, or all of them. Returns the count removed. */
@@ -1275,7 +1281,7 @@ function createUserNamespace(transport, hooks = {}) {
1275
1281
  return {
1276
1282
  async get_profile(options) {
1277
1283
  const userId = typeof options === "string" ? options : _nullishCoalesce(options.user_id, () => ( options.userId));
1278
- if (!userId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("user_id is required");
1284
+ if (!userId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("user_id is required");
1279
1285
  const customerId = typeof options === "string" ? void 0 : _nullishCoalesce(options.customer_id, () => ( options.customerId));
1280
1286
  return transport.request("user_profile", {
1281
1287
  pathParams: { user_id: userId },
@@ -1324,7 +1330,7 @@ function createCreditsNamespace(transport) {
1324
1330
  });
1325
1331
  },
1326
1332
  async redeem(code) {
1327
- if (!code) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("code is required");
1333
+ if (!code) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("code is required");
1328
1334
  return transport.request("credits_redeem", { body: { code } });
1329
1335
  }
1330
1336
  };
@@ -1335,11 +1341,11 @@ function createCacheNamespace(cache) {
1335
1341
  return {
1336
1342
  clear: () => cache.clear(),
1337
1343
  clear_user: (userId) => {
1338
- if (!userId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("user_id is required");
1344
+ if (!userId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("user_id is required");
1339
1345
  cache.dropEntity(userId);
1340
1346
  },
1341
1347
  clear_customer: (customerId) => {
1342
- if (!customerId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("customer_id is required");
1348
+ if (!customerId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("customer_id is required");
1343
1349
  cache.dropEntity(customerId);
1344
1350
  },
1345
1351
  stats: () => ({ bundles: cache.size, items: cache.itemCount })
@@ -1372,23 +1378,39 @@ function thinkingMetadata(options) {
1372
1378
  }
1373
1379
  return md;
1374
1380
  }
1381
+ var KNOWN_EVENT_TYPES = /* @__PURE__ */ new Set([
1382
+ "user_message",
1383
+ "assistant_message",
1384
+ "tool_call",
1385
+ "tool_result",
1386
+ "agent_thinking",
1387
+ "context_request",
1388
+ "context_fetch",
1389
+ "session_start",
1390
+ "session_end"
1391
+ ]);
1392
+ function toolResultJson(result) {
1393
+ if (result === void 0 || result === null) return "";
1394
+ return typeof result === "string" ? result : JSON.stringify(result);
1395
+ }
1375
1396
  function createInstanceNamespace(credentials, cache, onTurn) {
1376
1397
  let client = null;
1398
+ const openSessions = /* @__PURE__ */ new Map();
1377
1399
  let dispatchCompaction = null;
1378
1400
  let applyCompaction = null;
1379
1401
  const internals = {
1380
1402
  onCompactionUpdate(conversationId, bundle) {
1381
- _optionalChain([applyCompaction, 'optionalCall', _41 => _41(bundle)]);
1382
- _optionalChain([dispatchCompaction, 'optionalCall', _42 => _42(conversationId, bundle)]);
1403
+ _optionalChain([applyCompaction, 'optionalCall', _39 => _39(bundle)]);
1404
+ _optionalChain([dispatchCompaction, 'optionalCall', _40 => _40(conversationId, bundle)]);
1383
1405
  },
1384
1406
  setCompactionApplier(apply) {
1385
1407
  applyCompaction = apply;
1386
1408
  },
1387
1409
  sendContextUsed(event) {
1388
- _optionalChain([client, 'optionalAccess', _43 => _43.sendContextUsed, 'call', _44 => _44(event)]);
1410
+ _optionalChain([client, 'optionalAccess', _41 => _41.sendContextUsed, 'call', _42 => _42(event)]);
1389
1411
  },
1390
1412
  sendContextAssembled(event) {
1391
- _optionalChain([client, 'optionalAccess', _45 => _45.sendContextAssembled, 'call', _46 => _46(event)]);
1413
+ _optionalChain([client, 'optionalAccess', _43 => _43.sendContextAssembled, 'call', _44 => _44(event)]);
1392
1414
  },
1393
1415
  setCompactionDispatcher(dispatch) {
1394
1416
  dispatchCompaction = dispatch;
@@ -1397,16 +1419,33 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1397
1419
  return client !== null && client.isConnected;
1398
1420
  }
1399
1421
  };
1422
+ function ensureSession(conversationId, userId, customerId) {
1423
+ if (!conversationId || !userId || client === null) return;
1424
+ if (openSessions.has(conversationId)) return;
1425
+ const sessionId = _chunkT372OL3Qcjs.newCorrelationId.call(void 0, );
1426
+ try {
1427
+ client.sendSessionControl({
1428
+ action: "start",
1429
+ session_id: sessionId,
1430
+ conversation_id: conversationId,
1431
+ ...userId ? { user_id: userId } : {},
1432
+ ...customerId ? { customer_id: customerId } : {}
1433
+ });
1434
+ openSessions.set(conversationId, sessionId);
1435
+ } catch (e5) {
1436
+ }
1437
+ }
1400
1438
  const namespace = {
1401
1439
  async listen(options = {}) {
1402
1440
  if (client !== null) {
1403
- throw new (0, _chunk2TVL5IPQcjs.ListeningAlreadyActiveError)("Listening is already active on this instance");
1441
+ throw new (0, _chunkT372OL3Qcjs.ListeningAlreadyActiveError)("Listening is already active on this instance");
1404
1442
  }
1405
- const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-GPU37E6F.cjs")));
1443
+ const { GrpcStreamClient } = await Promise.resolve().then(() => _interopRequireWildcard(require("./stream-client-GJM4YSXW.cjs")));
1406
1444
  const onContext = _nullishCoalesce(options.on_context, () => ( options.onContext));
1407
1445
  const onDisconnect = _nullishCoalesce(options.on_disconnect, () => ( options.onDisconnect));
1408
1446
  const onReconnect = _nullishCoalesce(options.on_reconnect, () => ( options.onReconnect));
1409
1447
  let reconnectAttempts = 0;
1448
+ let stream = null;
1410
1449
  const created = new GrpcStreamClient(credentials(), cache, {
1411
1450
  host: _nullishCoalesce(_nullishCoalesce(options.host, () => ( _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_GRPC_HOST"))), () => ( DEFAULT_GRPC_HOST)),
1412
1451
  port: _nullishCoalesce(_nullishCoalesce(options.port, () => ( envPort())), () => ( DEFAULT_GRPC_PORT)),
@@ -1416,20 +1455,24 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1416
1455
  internals.onCompactionUpdate(conversationId, bundle);
1417
1456
  },
1418
1457
  onStateChange: (state) => {
1458
+ if (state !== "connected") openSessions.clear();
1419
1459
  if (state === "reconnecting") {
1420
1460
  reconnectAttempts += 1;
1421
- _optionalChain([onReconnect, 'optionalCall', _47 => _47(reconnectAttempts)]);
1461
+ _optionalChain([onReconnect, 'optionalCall', _45 => _45(reconnectAttempts)]);
1422
1462
  } else if (state === "disconnected") {
1423
- _optionalChain([onDisconnect, 'optionalCall', _48 => _48("stream disconnected")]);
1463
+ const stopped = _nullishCoalesce(_optionalChain([stream, 'optionalAccess', _46 => _46.lastError]), () => ( null));
1464
+ const reason = stopped === null ? "stream disconnected" : `credit_stop:${_nullishCoalesce(stopped.reason, () => ( "unknown"))}`;
1465
+ _optionalChain([onDisconnect, 'optionalCall', _47 => _47(reason)]);
1424
1466
  }
1425
1467
  }
1426
1468
  });
1469
+ stream = created;
1427
1470
  try {
1428
1471
  await created.connect();
1429
1472
  } catch (error) {
1430
- if (error instanceof _chunk2TVL5IPQcjs.SynapError) throw error;
1431
- throw new (0, _chunk2TVL5IPQcjs.SynapError)(
1432
- `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _49 => _49.message]), () => ( String(error)))}`,
1473
+ if (error instanceof _chunkT372OL3Qcjs.SynapError) throw error;
1474
+ throw new (0, _chunkT372OL3Qcjs.SynapError)(
1475
+ `Could not open the Synap anticipation stream: ${_nullishCoalesce(_optionalChain([error, 'optionalAccess', _48 => _48.message]), () => ( String(error)))}`,
1433
1476
  { cause: error }
1434
1477
  );
1435
1478
  }
@@ -1437,29 +1480,58 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1437
1480
  },
1438
1481
  async stop_listening() {
1439
1482
  if (client === null) return;
1483
+ for (const conversationId of [...openSessions.keys()]) {
1484
+ await namespace.end_session(conversationId);
1485
+ }
1440
1486
  const active = client;
1441
1487
  client = null;
1442
1488
  await active.disconnect();
1443
1489
  },
1490
+ async end_session(conversationId) {
1491
+ const sessionId = openSessions.get(conversationId);
1492
+ if (sessionId === void 0 || client === null) return;
1493
+ openSessions.delete(conversationId);
1494
+ try {
1495
+ client.sendSessionControl({
1496
+ action: "end",
1497
+ session_id: sessionId,
1498
+ conversation_id: conversationId
1499
+ });
1500
+ } catch (e6) {
1501
+ }
1502
+ },
1444
1503
  async send_message(options) {
1445
- if (client === null) throw new (0, _chunk2TVL5IPQcjs.ListeningNotActiveError)("Listening is not active");
1504
+ if (client === null) throw new (0, _chunkT372OL3Qcjs.ListeningNotActiveError)("Listening is not active");
1446
1505
  if (options.content === void 0) {
1447
- throw new (0, _chunk2TVL5IPQcjs.ListeningNotActiveError)("content is required");
1506
+ throw new (0, _chunkT372OL3Qcjs.ListeningNotActiveError)("content is required");
1507
+ }
1508
+ const eventType = _nullishCoalesce(_nullishCoalesce(options.event_type, () => ( options.eventType)), () => ( "user_message"));
1509
+ if (!KNOWN_EVENT_TYPES.has(eventType)) {
1510
+ throw new (0, _chunkT372OL3Qcjs.SynapError)(
1511
+ `unknown event_type '${eventType}'. Expected one of: ` + [...KNOWN_EVENT_TYPES].sort().join(", ")
1512
+ );
1448
1513
  }
1449
1514
  const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
1450
- _optionalChain([onTurn, 'optionalCall', _50 => _50({
1515
+ ensureSession(
1451
1516
  conversationId,
1452
- role: _nullishCoalesce(options.role, () => ( "user")),
1453
- content: options.content
1454
- })]);
1517
+ _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
1518
+ _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
1519
+ );
1520
+ if (eventType === "user_message" || eventType === "assistant_message") {
1521
+ _optionalChain([onTurn, 'optionalCall', _49 => _49({
1522
+ conversationId,
1523
+ role: _nullishCoalesce(options.role, () => ( "user")),
1524
+ content: options.content
1525
+ })]);
1526
+ }
1455
1527
  client.sendConversationEvent({
1456
- event_type: _nullishCoalesce(_nullishCoalesce(options.event_type, () => ( options.eventType)), () => ( "user_message")),
1528
+ event_type: eventType,
1457
1529
  content: options.content,
1458
1530
  role: _nullishCoalesce(options.role, () => ( "user")),
1459
1531
  conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
1460
1532
  user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
1461
1533
  customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
1462
- session_id: _nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( "")),
1534
+ session_id: _nullishCoalesce(_nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( openSessions.get(conversationId))), () => ( "")),
1463
1535
  metadata: _nullishCoalesce(options.metadata, () => ( {})),
1464
1536
  timestamp_ms: Date.now(),
1465
1537
  tool_name: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")),
@@ -1468,17 +1540,61 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1468
1540
  const a = _nullishCoalesce(options.tool_args, () => ( options.toolArgs));
1469
1541
  return a === void 0 ? "" : JSON.stringify(a);
1470
1542
  })(),
1543
+ tool_result_json: toolResultJson(_nullishCoalesce(options.tool_result, () => ( options.toolResult))),
1544
+ tool_call_id: _nullishCoalesce(_nullishCoalesce(options.tool_call_id, () => ( options.toolCallId)), () => ( "")),
1471
1545
  search_queries: _nullishCoalesce(_nullishCoalesce(options.search_queries, () => ( options.searchQueries)), () => ( [])),
1472
1546
  context_types: _nullishCoalesce(_nullishCoalesce(options.context_types, () => ( options.contextTypes)), () => ( []))
1473
1547
  });
1474
1548
  },
1549
+ async record_tool_call(options) {
1550
+ await namespace.send_message({
1551
+ content: "",
1552
+ role: "assistant",
1553
+ event_type: "tool_call",
1554
+ tool_name: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")),
1555
+ ..._nullishCoalesce(options.tool_args, () => ( options.toolArgs)) ? { tool_args: _nullishCoalesce(options.tool_args, () => ( options.toolArgs)) } : {},
1556
+ tool_call_id: _nullishCoalesce(_nullishCoalesce(options.tool_call_id, () => ( options.toolCallId)), () => ( "")),
1557
+ conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
1558
+ user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
1559
+ customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
1560
+ session_id: _nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( "")),
1561
+ metadata: _nullishCoalesce(options.metadata, () => ( {}))
1562
+ });
1563
+ },
1564
+ async record_tool_result(options) {
1565
+ await namespace.send_message({
1566
+ content: "",
1567
+ role: "tool",
1568
+ event_type: "tool_result",
1569
+ tool_result: options.result,
1570
+ tool_name: _nullishCoalesce(_nullishCoalesce(options.tool_name, () => ( options.toolName)), () => ( "")),
1571
+ tool_call_id: _nullishCoalesce(_nullishCoalesce(options.tool_call_id, () => ( options.toolCallId)), () => ( "")),
1572
+ conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
1573
+ user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
1574
+ customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
1575
+ session_id: _nullishCoalesce(_nullishCoalesce(options.session_id, () => ( options.sessionId)), () => ( "")),
1576
+ metadata: _nullishCoalesce(options.metadata, () => ( {}))
1577
+ });
1578
+ },
1475
1579
  async record_thinking(options) {
1476
- if (client === null) throw new (0, _chunk2TVL5IPQcjs.ListeningNotActiveError)("Listening is not active");
1580
+ if (client === null) throw new (0, _chunkT372OL3Qcjs.ListeningNotActiveError)("Listening is not active");
1581
+ const conversationId = _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( ""));
1582
+ ensureSession(
1583
+ conversationId,
1584
+ _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
1585
+ _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( ""))
1586
+ );
1477
1587
  client.sendConversationEvent({
1478
1588
  // Python emits reasoning as an `agent_thinking` conversation event.
1479
1589
  event_type: "agent_thinking",
1480
1590
  content: options.content,
1481
- role: "assistant",
1591
+ // Deliberately no role. A thought is not the assistant's reply, and
1592
+ // this went out as 'assistant' from the day it shipped: the server
1593
+ // checked role before event_type, so every reasoning step any client
1594
+ // sent was filed as the final answer and the reasoning path never ran.
1595
+ // Sending no role is correct against both the fixed server and one that
1596
+ // has not been updated yet.
1597
+ role: "",
1482
1598
  conversation_id: _nullishCoalesce(_nullishCoalesce(options.conversation_id, () => ( options.conversationId)), () => ( "")),
1483
1599
  user_id: _nullishCoalesce(_nullishCoalesce(options.user_id, () => ( options.userId)), () => ( "")),
1484
1600
  customer_id: _nullishCoalesce(_nullishCoalesce(options.customer_id, () => ( options.customerId)), () => ( "")),
@@ -1496,7 +1612,7 @@ function createInstanceNamespace(credentials, cache, onTurn) {
1496
1612
  }
1497
1613
 
1498
1614
  // src/version.ts
1499
- var SDK_VERSION = "0.4.7";
1615
+ var SDK_VERSION = "0.5.2";
1500
1616
 
1501
1617
  // src/registry.ts
1502
1618
  var instances = /* @__PURE__ */ new Map();
@@ -1685,7 +1801,7 @@ function budgetRecentTurns(turns) {
1685
1801
  return windowed;
1686
1802
  }
1687
1803
  function overlayLocalRecentTurns(response, store, conversationId, configured) {
1688
- if (conversationId === void 0 || conversationId === "") return;
1804
+ if (conversationId === void 0 || conversationId === null || conversationId === "") return;
1689
1805
  try {
1690
1806
  const entry = store.get(conversationId);
1691
1807
  if (entry === null) return;
@@ -1708,7 +1824,7 @@ function overlayLocalRecentTurns(response, store, conversationId, configured) {
1708
1824
  compacted_at: orLocal("compacted_at", entry.compactedAt),
1709
1825
  conversation_id: conversationId
1710
1826
  };
1711
- } catch (e5) {
1827
+ } catch (e7) {
1712
1828
  }
1713
1829
  }
1714
1830
 
@@ -1721,7 +1837,7 @@ function stringify(value) {
1721
1837
  if (t === "string" || t === "number" || t === "boolean") return String(value);
1722
1838
  try {
1723
1839
  return _nullishCoalesce(JSON.stringify(value), () => ( ""));
1724
- } catch (e6) {
1840
+ } catch (e8) {
1725
1841
  return String(value);
1726
1842
  }
1727
1843
  }
@@ -1995,7 +2111,7 @@ function tryServeFromCache(cache, scope, params, maxItems) {
1995
2111
  });
1996
2112
  if (hit === null) return { response: null, hit: null };
1997
2113
  return { response: buildAnticipationResponse(hit), hit };
1998
- } catch (e7) {
2114
+ } catch (e9) {
1999
2115
  return { response: null, hit: null };
2000
2116
  }
2001
2117
  }
@@ -2390,7 +2506,7 @@ function buildTool(target, options = {}, onWarning = () => {
2390
2506
  const scope = String(_nullishCoalesce(options.scope, () => ( "user"))).toLowerCase();
2391
2507
  if (!VALID_SCOPES.includes(scope)) {
2392
2508
  const sorted = [...VALID_SCOPES].sort();
2393
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(
2509
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
2394
2510
  `scope must be one of ['${sorted.join("', '")}'], got '${String(options.scope)}'`
2395
2511
  );
2396
2512
  }
@@ -2398,10 +2514,10 @@ function buildTool(target, options = {}, onWarning = () => {
2398
2514
  const customerId = _nullishCoalesce(options.customer_id, () => ( options.customerId));
2399
2515
  const conversationId = _nullishCoalesce(options.conversation_id, () => ( options.conversationId));
2400
2516
  if (scope === "user" && (userId === void 0 || userId === "")) {
2401
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("scope='user' requires user_id");
2517
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("scope='user' requires user_id");
2402
2518
  }
2403
2519
  if (scope === "customer" && (customerId === void 0 || customerId === "")) {
2404
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("scope='customer' requires customer_id");
2520
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("scope='customer' requires customer_id");
2405
2521
  }
2406
2522
  if (scope === "conversation" && (userId === void 0 || userId === "")) {
2407
2523
  onWarning(
@@ -2410,7 +2526,7 @@ function buildTool(target, options = {}, onWarning = () => {
2410
2526
  }
2411
2527
  const style = String(_nullishCoalesce(options.style, () => ( "openai")));
2412
2528
  if (style !== "openai" && style !== "anthropic") {
2413
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(`style must be 'openai' or 'anthropic', got '${style}'`);
2529
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(`style must be 'openai' or 'anthropic', got '${style}'`);
2414
2530
  }
2415
2531
  const toolName = _nullishCoalesce(options.name, () => ( `synap_fetch_${scope}_context`));
2416
2532
  const toolDesc = _nullishCoalesce(options.description, () => ( defaultToolDescription(scope)));
@@ -2613,9 +2729,9 @@ var SynapClient = class {
2613
2729
  */
2614
2730
  async searchMemory(options) {
2615
2731
  const userId = _nullishCoalesce(options.user_id, () => ( options.userId));
2616
- if (!userId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("user_id is required");
2732
+ if (!userId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("user_id is required");
2617
2733
  if (options.query === void 0 || options.query === null) {
2618
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("query is required");
2734
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("query is required");
2619
2735
  }
2620
2736
  const context = await fetchContext(this.#transport, "user", {
2621
2737
  user_id: userId,
@@ -2636,7 +2752,7 @@ var SynapClient = class {
2636
2752
  */
2637
2753
  async getMemories(options) {
2638
2754
  const userId = _nullishCoalesce(options.user_id, () => ( options.userId));
2639
- if (!userId) throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("user_id is required");
2755
+ if (!userId) throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("user_id is required");
2640
2756
  const context = await fetchContext(this.#transport, "user", {
2641
2757
  user_id: userId,
2642
2758
  ...pick3(options, "customer_id", "customerId") !== void 0 ? { customer_id: pick3(options, "customer_id", "customerId") } : {},
@@ -2695,7 +2811,7 @@ var SynapClient = class {
2695
2811
  this.#registryKeys.push(resolvedInstanceId);
2696
2812
  }
2697
2813
  }
2698
- } catch (e8) {
2814
+ } catch (e10) {
2699
2815
  }
2700
2816
  }
2701
2817
  /**
@@ -2730,7 +2846,7 @@ var SynapClient = class {
2730
2846
  */
2731
2847
  configure(options = {}) {
2732
2848
  if (this.#initialized) {
2733
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)("Cannot reconfigure after initialization");
2849
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)("Cannot reconfigure after initialization");
2734
2850
  }
2735
2851
  if (options.timeouts !== void 0) this.#transport.setTimeouts(options.timeouts);
2736
2852
  if (options.retryPolicy !== void 0 || options.retry_policy !== void 0) {
@@ -2781,7 +2897,8 @@ var SynapClient = class {
2781
2897
  };
2782
2898
  const labels = [];
2783
2899
  const tasks = [];
2784
- if (conversationId !== void 0 && conversationId !== "" && wants("conversation")) {
2900
+ const present = (v) => v !== void 0 && v !== null && v !== "";
2901
+ if (present(conversationId) && wants("conversation")) {
2785
2902
  labels.push("conversation");
2786
2903
  tasks.push(this.conversation.context.fetch({
2787
2904
  conversation_id: conversationId,
@@ -2790,7 +2907,7 @@ var SynapClient = class {
2790
2907
  customer_id: customerId
2791
2908
  }));
2792
2909
  }
2793
- if (userId !== void 0 && userId !== "" && wants("user")) {
2910
+ if (present(userId) && wants("user")) {
2794
2911
  labels.push("user");
2795
2912
  tasks.push(this.user.context.fetch({
2796
2913
  user_id: userId,
@@ -2802,7 +2919,7 @@ var SynapClient = class {
2802
2919
  last_n_conversations: lastNConversations
2803
2920
  }));
2804
2921
  }
2805
- if (customerId !== void 0 && customerId !== "" && wants("customer")) {
2922
+ if (present(customerId) && wants("customer")) {
2806
2923
  labels.push("customer");
2807
2924
  tasks.push(this.customer.context.fetch({
2808
2925
  customer_id: customerId,
@@ -2829,19 +2946,19 @@ var SynapClient = class {
2829
2946
  successful.push([label, result.value]);
2830
2947
  continue;
2831
2948
  }
2832
- if (result.reason instanceof _chunk2TVL5IPQcjs.InvalidInputError) throw result.reason;
2949
+ if (result.reason instanceof _chunkT372OL3Qcjs.InvalidInputError) throw result.reason;
2833
2950
  this.#warn(`Scope '${label}' fetch failed in unified fetch (non-fatal): ${String(result.reason)}`);
2834
2951
  }
2835
2952
  const merged = mergeScopeResults(successful);
2836
2953
  for (const [, response] of successful) {
2837
2954
  overlayLocalRecentTurns(response, this.#shortTerm, conversationId, this.#stVerbatimOverlay);
2838
2955
  }
2839
- if (includeConversationContext && conversationId !== void 0 && conversationId !== "") {
2956
+ if (includeConversationContext && present(conversationId)) {
2840
2957
  try {
2841
2958
  merged.conversation_context = await this.conversation.context.get_context_for_prompt({
2842
2959
  conversation_id: conversationId
2843
2960
  });
2844
- } catch (e9) {
2961
+ } catch (e11) {
2845
2962
  }
2846
2963
  }
2847
2964
  merged.formatted_context = formatForPrompt(merged, {
@@ -2888,7 +3005,7 @@ var SynapClient = class {
2888
3005
  source_bundle_ids: served.bundleId ? [served.bundleId] : [],
2889
3006
  timestamp_ms: Date.now()
2890
3007
  });
2891
- } catch (e10) {
3008
+ } catch (e12) {
2892
3009
  }
2893
3010
  }
2894
3011
  /**
@@ -2903,7 +3020,7 @@ var SynapClient = class {
2903
3020
  if (!this.instance.is_listening) return;
2904
3021
  this.instance._internal.sendContextAssembled({
2905
3022
  ...buildAssembledEvent({
2906
- correlationId: newCorrelationId(),
3023
+ correlationId: _chunkT372OL3Qcjs.newCorrelationId.call(void 0, ),
2907
3024
  response,
2908
3025
  conversationId: _nullishCoalesce(options["conversation_id"], () => ( options["conversationId"])),
2909
3026
  userId: _nullishCoalesce(options["user_id"], () => ( options["userId"])),
@@ -2913,7 +3030,7 @@ var SynapClient = class {
2913
3030
  }),
2914
3031
  scope
2915
3032
  });
2916
- } catch (e11) {
3033
+ } catch (e13) {
2917
3034
  }
2918
3035
  }
2919
3036
  /**
@@ -2991,13 +3108,13 @@ function pick3(o2, snake, camel) {
2991
3108
  function resolveBaseUrl(options) {
2992
3109
  const explicit = _nullishCoalesce(options.baseUrl, () => ( options.api_base_url));
2993
3110
  if (explicit !== void 0) return explicit;
2994
- const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _51 => _51.trim, 'call', _52 => _52()]);
3111
+ const fromEnv = _optionalChain([_chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_BASE_URL"), 'optionalAccess', _50 => _50.trim, 'call', _51 => _51()]);
2995
3112
  return fromEnv !== void 0 && fromEnv !== "" ? fromEnv : void 0;
2996
3113
  }
2997
3114
  function resolveCredentials(options) {
2998
3115
  const apiKey = _nullishCoalesce(options.apiKey, () => ( _chunkZKOJDUN4cjs.getEnv.call(void 0, "SYNAP_API_KEY")));
2999
3116
  if (!apiKey) {
3000
- throw new (0, _chunk2TVL5IPQcjs.InvalidInputError)(
3117
+ throw new (0, _chunkT372OL3Qcjs.InvalidInputError)(
3001
3118
  "No Synap API key found. Set SYNAP_API_KEY in your environment, or pass apiKey to the SynapClient constructor."
3002
3119
  );
3003
3120
  }
@@ -3058,5 +3175,5 @@ function resolveCredentials(options) {
3058
3175
 
3059
3176
 
3060
3177
 
3061
- exports.ANY_SCOPE = _chunkT6U5PVADcjs.ANY_SCOPE; exports.AgentUnavailableError = _chunk2TVL5IPQcjs.AgentUnavailableError; exports.AnticipationCache = _chunkT6U5PVADcjs.AnticipationCache; exports.AuthenticationError = _chunk2TVL5IPQcjs.AuthenticationError; exports.BM25 = _chunkT6U5PVADcjs.BM25; exports.COMPACTION_LEVELS = COMPACTION_LEVELS; exports.CONTRACT = _chunkT6U5PVADcjs.CONTRACT; exports.ConflictError = _chunk2TVL5IPQcjs.ConflictError; exports.ConnectionError = _chunk2TVL5IPQcjs.ConnectionError; exports.ContextNotFoundError = _chunk2TVL5IPQcjs.ContextNotFoundError; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_DOCUMENT_TYPE = DEFAULT_DOCUMENT_TYPE; exports.DEFAULT_INGEST_MODE = DEFAULT_INGEST_MODE; exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY; exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS; exports.DOCUMENT_TYPES = DOCUMENT_TYPES; exports.ENDPOINTS = ENDPOINTS; exports.HttpTransport = HttpTransport; exports.INGEST_MODES = INGEST_MODES; exports.ITEM_COLLECTIONS = ITEM_COLLECTIONS; exports.InsufficientCreditsError = _chunk2TVL5IPQcjs.InsufficientCreditsError; exports.InvalidConversationIdError = _chunk2TVL5IPQcjs.InvalidConversationIdError; exports.InvalidInputError = _chunk2TVL5IPQcjs.InvalidInputError; exports.InvalidInstanceIdError = _chunk2TVL5IPQcjs.InvalidInstanceIdError; exports.ListeningAlreadyActiveError = _chunk2TVL5IPQcjs.ListeningAlreadyActiveError; exports.ListeningNotActiveError = _chunk2TVL5IPQcjs.ListeningNotActiveError; exports.NetworkTimeoutError = _chunk2TVL5IPQcjs.NetworkTimeoutError; exports.PermanentError = _chunk2TVL5IPQcjs.PermanentError; exports.RateLimitError = _chunk2TVL5IPQcjs.RateLimitError; exports.SDKError = _chunk2TVL5IPQcjs.SDKError; exports.SDK_VERSION = SDK_VERSION; exports.ServiceUnavailableError = _chunk2TVL5IPQcjs.ServiceUnavailableError; exports.SessionExpiredError = _chunk2TVL5IPQcjs.SessionExpiredError; exports.SynapClient = SynapClient; exports.SynapError = _chunk2TVL5IPQcjs.SynapError; exports.SynapPermanentError = _chunk2TVL5IPQcjs.SynapPermanentError; exports.SynapTransientError = _chunk2TVL5IPQcjs.SynapTransientError; exports.THRESHOLDS = _chunkT6U5PVADcjs.THRESHOLDS; exports.TranscriptConflictError = _chunk2TVL5IPQcjs.TranscriptConflictError; exports.TransientError = _chunk2TVL5IPQcjs.TransientError; exports.flattenContextItems = flattenContextItems; exports.formatForPrompt = formatForPrompt; exports.isOutcomeUnknown = isOutcomeUnknown; exports.isRecallQuery = _chunkT6U5PVADcjs.isRecallQuery; exports.isSynapError = _chunk2TVL5IPQcjs.isSynapError; exports.mergeScopeResults = mergeScopeResults; exports.resolvePath = resolvePath; exports.shouldRetry = shouldRetry; exports.stem = _chunkT6U5PVADcjs.stem; exports.tokenize = _chunkT6U5PVADcjs.tokenize;
3178
+ exports.ANY_SCOPE = _chunkT6U5PVADcjs.ANY_SCOPE; exports.AgentUnavailableError = _chunkT372OL3Qcjs.AgentUnavailableError; exports.AnticipationCache = _chunkT6U5PVADcjs.AnticipationCache; exports.AuthenticationError = _chunkT372OL3Qcjs.AuthenticationError; exports.BM25 = _chunkT6U5PVADcjs.BM25; exports.COMPACTION_LEVELS = COMPACTION_LEVELS; exports.CONTRACT = _chunkT6U5PVADcjs.CONTRACT; exports.ConflictError = _chunkT372OL3Qcjs.ConflictError; exports.ConnectionError = _chunkT372OL3Qcjs.ConnectionError; exports.ContextNotFoundError = _chunkT372OL3Qcjs.ContextNotFoundError; exports.DEFAULT_BASE_URL = DEFAULT_BASE_URL; exports.DEFAULT_DOCUMENT_TYPE = DEFAULT_DOCUMENT_TYPE; exports.DEFAULT_INGEST_MODE = DEFAULT_INGEST_MODE; exports.DEFAULT_RETRY_POLICY = DEFAULT_RETRY_POLICY; exports.DEFAULT_TIMEOUTS = DEFAULT_TIMEOUTS; exports.DOCUMENT_TYPES = DOCUMENT_TYPES; exports.ENDPOINTS = ENDPOINTS; exports.HttpTransport = HttpTransport; exports.INGEST_MODES = INGEST_MODES; exports.ITEM_COLLECTIONS = ITEM_COLLECTIONS; exports.InsufficientCreditsError = _chunkT372OL3Qcjs.InsufficientCreditsError; exports.InvalidConversationIdError = _chunkT372OL3Qcjs.InvalidConversationIdError; exports.InvalidInputError = _chunkT372OL3Qcjs.InvalidInputError; exports.InvalidInstanceIdError = _chunkT372OL3Qcjs.InvalidInstanceIdError; exports.ListeningAlreadyActiveError = _chunkT372OL3Qcjs.ListeningAlreadyActiveError; exports.ListeningNotActiveError = _chunkT372OL3Qcjs.ListeningNotActiveError; exports.NetworkTimeoutError = _chunkT372OL3Qcjs.NetworkTimeoutError; exports.PermanentError = _chunkT372OL3Qcjs.PermanentError; exports.RateLimitError = _chunkT372OL3Qcjs.RateLimitError; exports.SDKError = _chunkT372OL3Qcjs.SDKError; exports.SDK_VERSION = SDK_VERSION; exports.ServiceUnavailableError = _chunkT372OL3Qcjs.ServiceUnavailableError; exports.SessionExpiredError = _chunkT372OL3Qcjs.SessionExpiredError; exports.SynapClient = SynapClient; exports.SynapError = _chunkT372OL3Qcjs.SynapError; exports.SynapPermanentError = _chunkT372OL3Qcjs.SynapPermanentError; exports.SynapTransientError = _chunkT372OL3Qcjs.SynapTransientError; exports.THRESHOLDS = _chunkT6U5PVADcjs.THRESHOLDS; exports.TranscriptConflictError = _chunkT372OL3Qcjs.TranscriptConflictError; exports.TransientError = _chunkT372OL3Qcjs.TransientError; exports.flattenContextItems = flattenContextItems; exports.formatForPrompt = formatForPrompt; exports.isOutcomeUnknown = isOutcomeUnknown; exports.isRecallQuery = _chunkT6U5PVADcjs.isRecallQuery; exports.isSynapError = _chunkT372OL3Qcjs.isSynapError; exports.mergeScopeResults = mergeScopeResults; exports.resolvePath = resolvePath; exports.shouldRetry = shouldRetry; exports.stem = _chunkT6U5PVADcjs.stem; exports.tokenize = _chunkT6U5PVADcjs.tokenize;
3062
3179
  //# sourceMappingURL=index.cjs.map