@anuma/sdk 6.7.2 → 6.7.3

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 (28) hide show
  1. package/dist/expo/{chunk-2YHVYDEL.mjs → chunk-37VWRZTL.mjs} +2 -2
  2. package/dist/{react/chunk-B5UPJRCU.mjs → expo/chunk-5GBYOWRY.mjs} +48 -10
  3. package/dist/expo/{chunk-VOMDHMKH.mjs → chunk-ITRFWFNS.mjs} +1 -1
  4. package/dist/{react/consolidate-ZCGS7QUA.mjs → expo/consolidate-H6YD36XI.mjs} +2 -2
  5. package/dist/expo/index.cjs +67 -16
  6. package/dist/expo/index.d.mts +67 -2
  7. package/dist/expo/index.d.ts +67 -2
  8. package/dist/expo/index.mjs +22 -9
  9. package/dist/expo/{recall-M3JVFTZL.mjs → recall-FZ7JC4AX.mjs} +2 -2
  10. package/dist/{expo/chunk-B5UPJRCU.mjs → react/chunk-5GBYOWRY.mjs} +48 -10
  11. package/dist/react/{chunk-S6WPXD5N.mjs → chunk-NC7BZEEF.mjs} +2 -2
  12. package/dist/react/{chunk-2ARMO2NN.mjs → chunk-ZZDMEEHO.mjs} +1 -1
  13. package/dist/{expo/consolidate-TWE6OSSZ.mjs → react/consolidate-FNFIDL37.mjs} +2 -2
  14. package/dist/react/index.cjs +67 -16
  15. package/dist/react/index.d.mts +67 -2
  16. package/dist/react/index.d.ts +67 -2
  17. package/dist/react/index.mjs +22 -9
  18. package/dist/react/{recall-ROEK55FJ.mjs → recall-546HTUPK.mjs} +2 -2
  19. package/dist/server/{chunk-CR5P3YIK.mjs → chunk-5KIUGHQZ.mjs} +1 -1
  20. package/dist/server/{chunk-TD7SMY7C.mjs → chunk-G6IH6QTZ.mjs} +2 -2
  21. package/dist/server/{chunk-VHWLLYKO.mjs → chunk-I2U35Z3O.mjs} +48 -10
  22. package/dist/server/{consolidate-FWYK5KXB.mjs → consolidate-S7QZ7V6T.mjs} +2 -2
  23. package/dist/server/index.cjs +67 -16
  24. package/dist/server/index.d.mts +67 -2
  25. package/dist/server/index.d.ts +67 -2
  26. package/dist/server/index.mjs +22 -9
  27. package/dist/server/{recall-CGDEW2LQ.mjs → recall-BIPVQMG4.mjs} +2 -2
  28. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  callPortalJsonCompletion,
3
3
  getLogger
4
- } from "./chunk-B5UPJRCU.mjs";
4
+ } from "./chunk-5GBYOWRY.mjs";
5
5
  import {
6
6
  BASE_URL,
7
7
  createClientConfig
@@ -6807,7 +6807,7 @@ function createMemoryVaultSearchTool(vaultCtx, embeddingOptions, cache, searchOp
6807
6807
  subQueries = decomp.subQueries;
6808
6808
  }
6809
6809
  }
6810
- const { recall: recall2 } = await import("./recall-M3JVFTZL.mjs");
6810
+ const { recall: recall2 } = await import("./recall-FZ7JC4AX.mjs");
6811
6811
  let recallDegraded = [];
6812
6812
  const result = await recall2(
6813
6813
  query,
@@ -115,9 +115,15 @@ async function callPortalJsonCompletion(req) {
115
115
  const maxAttempts = Math.max(1, req.maxAttempts ?? 3);
116
116
  const startedAt = Date.now();
117
117
  const overBudget = () => req.totalTimeoutMs !== void 0 && Date.now() - startedAt >= req.totalTimeoutMs;
118
+ let lastFailure;
119
+ const giveUp = () => {
120
+ req.onFailure?.(lastFailure ?? { reason: "network", attempts: maxAttempts });
121
+ return null;
122
+ };
118
123
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
119
124
  if (attempt > 1 && overBudget()) {
120
125
  log.warn(`[${req.tag}] over time budget before attempt ${attempt}, giving up`);
126
+ lastFailure = { reason: "time-budget-exhausted", attempts: attempt - 1 };
121
127
  break;
122
128
  }
123
129
  const attemptReq = req.totalTimeoutMs !== void 0 ? {
@@ -129,9 +135,14 @@ async function callPortalJsonCompletion(req) {
129
135
  } : req;
130
136
  const outcome = await attemptPortalJson(attemptReq, endpoint);
131
137
  if (outcome.kind === "ok") return outcome.value;
138
+ lastFailure = {
139
+ reason: outcome.code,
140
+ ...outcome.httpStatus !== void 0 && { httpStatus: outcome.httpStatus },
141
+ attempts: attempt
142
+ };
132
143
  if (outcome.kind === "terminal") {
133
144
  log.warn(`[${req.tag}] ${outcome.reason}`);
134
- return null;
145
+ return giveUp();
135
146
  }
136
147
  if (attempt >= maxAttempts) {
137
148
  log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, giving up`);
@@ -143,19 +154,21 @@ async function callPortalJsonCompletion(req) {
143
154
  log.warn(
144
155
  `[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, over time budget, giving up`
145
156
  );
157
+ lastFailure = { reason: "time-budget-exhausted", attempts: attempt };
146
158
  break;
147
159
  }
148
160
  log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, retrying`);
149
161
  if (delay > 0) await sleep(delay);
150
162
  }
151
- return null;
163
+ return giveUp();
152
164
  }
153
165
  async function attemptPortalJson(req, endpoint) {
154
166
  const baseUrl = req.baseUrl ?? defaultBaseUrl();
155
167
  const fetchImpl = req.fetchFn ?? fetch;
156
168
  const timeoutMs = req.timeoutMs ?? 6e4;
157
169
  const authHeaders = await resolvePortalAuthHeaders(req, req.tag);
158
- if (authHeaders === null) return { kind: "terminal", reason: "auth unavailable (no token)" };
170
+ if (authHeaders === null)
171
+ return { kind: "terminal", code: "auth-unavailable", reason: "auth unavailable (no token)" };
159
172
  const isAnthropic = req.model.startsWith("anthropic/");
160
173
  const prefill = isAnthropic ? "{" : "";
161
174
  const messages = [
@@ -188,31 +201,55 @@ async function attemptPortalJson(req, endpoint) {
188
201
  });
189
202
  } catch (err) {
190
203
  clearTimeout(timer);
191
- return { kind: "retryable", reason: `fetch failed: ${err.message}` };
204
+ return {
205
+ kind: "retryable",
206
+ code: "network",
207
+ reason: `fetch failed: ${err.message}`
208
+ };
192
209
  }
193
210
  if (!response.ok) {
194
211
  clearTimeout(timer);
195
212
  const reason = `portal returned ${response.status}`;
196
213
  if (response.status === 401) {
197
214
  const tokenAuth = !req.apiKey && !!req.getToken;
198
- return tokenAuth ? { kind: "retryable", reason: `${reason} (token may be expired; refreshing)` } : { kind: "terminal", reason };
215
+ return tokenAuth ? {
216
+ kind: "retryable",
217
+ code: "http-retryable",
218
+ reason: `${reason} (token may be expired; refreshing)`,
219
+ httpStatus: response.status
220
+ } : { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
199
221
  }
200
- if (!isRetryableStatus(response.status)) return { kind: "terminal", reason };
222
+ if (!isRetryableStatus(response.status))
223
+ return { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
201
224
  const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
202
- return retryAfterMs !== null ? { kind: "retryable", reason, retryAfterMs } : { kind: "retryable", reason };
225
+ return {
226
+ kind: "retryable",
227
+ code: "http-retryable",
228
+ reason,
229
+ httpStatus: response.status,
230
+ ...retryAfterMs !== null && { retryAfterMs }
231
+ };
203
232
  }
204
233
  let body;
205
234
  try {
206
235
  body = await response.json();
207
236
  } catch (err) {
208
237
  clearTimeout(timer);
209
- return { kind: "retryable", reason: `response body parse failed: ${err.message}` };
238
+ return {
239
+ kind: "retryable",
240
+ code: "body-parse-failed",
241
+ reason: `response body parse failed: ${err.message}`
242
+ };
210
243
  }
211
244
  clearTimeout(timer);
212
245
  logPortalUsage(body, req.tag);
213
246
  const rawContent = extractCompletionContent(body);
214
247
  if (!rawContent) {
215
- return { kind: "retryable", reason: "portal response had no completion content" };
248
+ return {
249
+ kind: "retryable",
250
+ code: "empty-content",
251
+ reason: "portal response had no completion content"
252
+ };
216
253
  }
217
254
  const looksLikeContinuation = prefill && /^\s*"/.test(rawContent);
218
255
  const content = looksLikeContinuation ? prefill + rawContent : rawContent;
@@ -223,11 +260,12 @@ async function attemptPortalJson(req, endpoint) {
223
260
  } catch (err) {
224
261
  return {
225
262
  kind: "retryable",
263
+ code: "invalid-json",
226
264
  reason: `completion was not valid JSON: ${err.message}`
227
265
  };
228
266
  }
229
267
  if (value === null) {
230
- return { kind: "retryable", reason: "completion parsed to null" };
268
+ return { kind: "retryable", code: "null-completion", reason: "completion parsed to null" };
231
269
  }
232
270
  return { kind: "ok", value };
233
271
  }
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getLogger
3
- } from "./chunk-B5UPJRCU.mjs";
3
+ } from "./chunk-5GBYOWRY.mjs";
4
4
 
5
5
  // src/lib/pii/patterns.ts
6
6
  function luhnCheck(digits) {
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  notifyConsolidationFallback,
3
3
  resolvePiiRedactor
4
- } from "./chunk-2ARMO2NN.mjs";
4
+ } from "./chunk-ITRFWFNS.mjs";
5
5
  import {
6
6
  callPortalJsonCompletion
7
- } from "./chunk-B5UPJRCU.mjs";
7
+ } from "./chunk-5GBYOWRY.mjs";
8
8
  import "./chunk-GYKJOWEO.mjs";
9
9
 
10
10
  // src/lib/memory/consolidate.ts
@@ -6151,9 +6151,15 @@ async function callPortalJsonCompletion(req) {
6151
6151
  const maxAttempts = Math.max(1, req.maxAttempts ?? 3);
6152
6152
  const startedAt = Date.now();
6153
6153
  const overBudget = () => req.totalTimeoutMs !== void 0 && Date.now() - startedAt >= req.totalTimeoutMs;
6154
+ let lastFailure;
6155
+ const giveUp = () => {
6156
+ req.onFailure?.(lastFailure ?? { reason: "network", attempts: maxAttempts });
6157
+ return null;
6158
+ };
6154
6159
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
6155
6160
  if (attempt > 1 && overBudget()) {
6156
6161
  log.warn(`[${req.tag}] over time budget before attempt ${attempt}, giving up`);
6162
+ lastFailure = { reason: "time-budget-exhausted", attempts: attempt - 1 };
6157
6163
  break;
6158
6164
  }
6159
6165
  const attemptReq = req.totalTimeoutMs !== void 0 ? {
@@ -6165,9 +6171,14 @@ async function callPortalJsonCompletion(req) {
6165
6171
  } : req;
6166
6172
  const outcome = await attemptPortalJson(attemptReq, endpoint);
6167
6173
  if (outcome.kind === "ok") return outcome.value;
6174
+ lastFailure = {
6175
+ reason: outcome.code,
6176
+ ...outcome.httpStatus !== void 0 && { httpStatus: outcome.httpStatus },
6177
+ attempts: attempt
6178
+ };
6168
6179
  if (outcome.kind === "terminal") {
6169
6180
  log.warn(`[${req.tag}] ${outcome.reason}`);
6170
- return null;
6181
+ return giveUp();
6171
6182
  }
6172
6183
  if (attempt >= maxAttempts) {
6173
6184
  log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, giving up`);
@@ -6179,19 +6190,21 @@ async function callPortalJsonCompletion(req) {
6179
6190
  log.warn(
6180
6191
  `[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, over time budget, giving up`
6181
6192
  );
6193
+ lastFailure = { reason: "time-budget-exhausted", attempts: attempt };
6182
6194
  break;
6183
6195
  }
6184
6196
  log.warn(`[${req.tag}] ${outcome.reason} \u2014 attempt ${attempt}/${maxAttempts}, retrying`);
6185
6197
  if (delay > 0) await sleep3(delay);
6186
6198
  }
6187
- return null;
6199
+ return giveUp();
6188
6200
  }
6189
6201
  async function attemptPortalJson(req, endpoint) {
6190
6202
  const baseUrl = req.baseUrl ?? defaultBaseUrl();
6191
6203
  const fetchImpl = req.fetchFn ?? fetch;
6192
6204
  const timeoutMs = req.timeoutMs ?? 6e4;
6193
6205
  const authHeaders = await resolvePortalAuthHeaders(req, req.tag);
6194
- if (authHeaders === null) return { kind: "terminal", reason: "auth unavailable (no token)" };
6206
+ if (authHeaders === null)
6207
+ return { kind: "terminal", code: "auth-unavailable", reason: "auth unavailable (no token)" };
6195
6208
  const isAnthropic = req.model.startsWith("anthropic/");
6196
6209
  const prefill = isAnthropic ? "{" : "";
6197
6210
  const messages = [
@@ -6224,31 +6237,55 @@ async function attemptPortalJson(req, endpoint) {
6224
6237
  });
6225
6238
  } catch (err) {
6226
6239
  clearTimeout(timer);
6227
- return { kind: "retryable", reason: `fetch failed: ${err.message}` };
6240
+ return {
6241
+ kind: "retryable",
6242
+ code: "network",
6243
+ reason: `fetch failed: ${err.message}`
6244
+ };
6228
6245
  }
6229
6246
  if (!response.ok) {
6230
6247
  clearTimeout(timer);
6231
6248
  const reason = `portal returned ${response.status}`;
6232
6249
  if (response.status === 401) {
6233
6250
  const tokenAuth = !req.apiKey && !!req.getToken;
6234
- return tokenAuth ? { kind: "retryable", reason: `${reason} (token may be expired; refreshing)` } : { kind: "terminal", reason };
6235
- }
6236
- if (!isRetryableStatus(response.status)) return { kind: "terminal", reason };
6251
+ return tokenAuth ? {
6252
+ kind: "retryable",
6253
+ code: "http-retryable",
6254
+ reason: `${reason} (token may be expired; refreshing)`,
6255
+ httpStatus: response.status
6256
+ } : { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
6257
+ }
6258
+ if (!isRetryableStatus(response.status))
6259
+ return { kind: "terminal", code: "http-terminal", reason, httpStatus: response.status };
6237
6260
  const retryAfterMs = parseRetryAfterMs(response.headers.get("retry-after"));
6238
- return retryAfterMs !== null ? { kind: "retryable", reason, retryAfterMs } : { kind: "retryable", reason };
6261
+ return {
6262
+ kind: "retryable",
6263
+ code: "http-retryable",
6264
+ reason,
6265
+ httpStatus: response.status,
6266
+ ...retryAfterMs !== null && { retryAfterMs }
6267
+ };
6239
6268
  }
6240
6269
  let body;
6241
6270
  try {
6242
6271
  body = await response.json();
6243
6272
  } catch (err) {
6244
6273
  clearTimeout(timer);
6245
- return { kind: "retryable", reason: `response body parse failed: ${err.message}` };
6274
+ return {
6275
+ kind: "retryable",
6276
+ code: "body-parse-failed",
6277
+ reason: `response body parse failed: ${err.message}`
6278
+ };
6246
6279
  }
6247
6280
  clearTimeout(timer);
6248
6281
  logPortalUsage(body, req.tag);
6249
6282
  const rawContent = extractCompletionContent(body);
6250
6283
  if (!rawContent) {
6251
- return { kind: "retryable", reason: "portal response had no completion content" };
6284
+ return {
6285
+ kind: "retryable",
6286
+ code: "empty-content",
6287
+ reason: "portal response had no completion content"
6288
+ };
6252
6289
  }
6253
6290
  const looksLikeContinuation = prefill && /^\s*"/.test(rawContent);
6254
6291
  const content = looksLikeContinuation ? prefill + rawContent : rawContent;
@@ -6259,11 +6296,12 @@ async function attemptPortalJson(req, endpoint) {
6259
6296
  } catch (err) {
6260
6297
  return {
6261
6298
  kind: "retryable",
6299
+ code: "invalid-json",
6262
6300
  reason: `completion was not valid JSON: ${err.message}`
6263
6301
  };
6264
6302
  }
6265
6303
  if (value === null) {
6266
- return { kind: "retryable", reason: "completion parsed to null" };
6304
+ return { kind: "retryable", code: "null-completion", reason: "completion parsed to null" };
6267
6305
  }
6268
6306
  return { kind: "ok", value };
6269
6307
  }
@@ -16562,7 +16600,11 @@ async function extractFacts(messages, options) {
16562
16600
  }
16563
16601
  const transcript = transcriptLines.join("\n");
16564
16602
  const today = formatLocalDate(options.now ?? Date.now());
16603
+ let failure;
16565
16604
  const parsed = await callPortalJsonCompletion({
16605
+ onFailure: (f) => {
16606
+ failure = f;
16607
+ },
16566
16608
  ...options.apiKey !== void 0 && { apiKey: options.apiKey },
16567
16609
  ...options.getToken !== void 0 && { getToken: options.getToken },
16568
16610
  ...options.baseUrl !== void 0 && { baseUrl: options.baseUrl },
@@ -16585,7 +16627,7 @@ Extract durable user facts.`,
16585
16627
  ...options.backoffMs && { backoffMs: options.backoffMs }
16586
16628
  });
16587
16629
  if (parsed === null) {
16588
- options.onExhaustedEmpty?.();
16630
+ options.onExhaustedEmpty?.(failure ?? { reason: "empty-content", attempts: 1 });
16589
16631
  return [];
16590
16632
  }
16591
16633
  const fallbackSourceId = [...messages].reverse().find((m) => m.role === "user")?.id;
@@ -16629,14 +16671,16 @@ async function extractAndRetain(messages, retainCtx, options) {
16629
16671
  ...resolvedConsolidatePii !== void 0 && { piiRedaction: resolvedConsolidatePii }
16630
16672
  } : void 0;
16631
16673
  let exhaustedEmpty = false;
16674
+ let exhaustedFailure;
16632
16675
  let droppedAfterRedaction = false;
16633
16676
  const callerOnExhaustedEmpty = options.extract.onExhaustedEmpty;
16634
16677
  const callerOnCandidatesDropped = options.extract.onCandidatesDropped;
16635
16678
  const candidates = await extractFacts(messages, {
16636
16679
  ...options.extract,
16637
- onExhaustedEmpty: () => {
16680
+ onExhaustedEmpty: (failure) => {
16638
16681
  exhaustedEmpty = true;
16639
- callerOnExhaustedEmpty?.();
16682
+ exhaustedFailure = failure;
16683
+ callerOnExhaustedEmpty?.(failure);
16640
16684
  },
16641
16685
  onCandidatesDropped: () => {
16642
16686
  droppedAfterRedaction = true;
@@ -16755,12 +16799,19 @@ async function extractAndRetain(messages, retainCtx, options) {
16755
16799
  results,
16756
16800
  failedCount: failedWrites,
16757
16801
  outcome,
16758
- quarantined: quarantinedInfo
16802
+ quarantined: quarantinedInfo,
16803
+ // Only meaningful alongside `outcome: "empty-after-retry"`. Returned as well
16804
+ // as pushed through the callback so a consumer that only inspects the result
16805
+ // (rather than wiring a hook) can still report WHY.
16806
+ ...exhaustedFailure !== void 0 && { failure: exhaustedFailure }
16759
16807
  };
16760
16808
  }
16809
+ var UTTERANCE_ECHO_RE = /^(?:said|says|asked|answered|replied|guessed|typed)\s*:\s*(?:'[^']*'|"[^"]*"|‘[^’]*’|“[^”]*”)[\s.!?]*$/iu;
16761
16810
  function isLowSignalContent(content, ownNames) {
16762
- const normalized = content.trim().replace(/[.!?]+$/, "").toLowerCase();
16811
+ const trimmed = content.trim();
16812
+ const normalized = trimmed.replace(/[.!?]+$/, "").toLowerCase();
16763
16813
  if (normalized.length < MIN_CONTENT_LENGTH) return true;
16814
+ if (UTTERANCE_ECHO_RE.test(trimmed)) return true;
16764
16815
  if (ownNames.some(
16765
16816
  (n) => normalized === n.trim().replace(/[.!?]+$/, "").toLowerCase()
16766
16817
  )) {
@@ -4880,6 +4880,60 @@ interface PortalLlmAuth {
4880
4880
  /** Function to get an auth token (e.g., Privy's getIdentityToken). Token is sent as `Authorization: Bearer`. */
4881
4881
  getToken?: () => Promise<string | null>;
4882
4882
  }
4883
+ /**
4884
+ * Why a portal JSON completion gave up, as a STABLE low-cardinality code.
4885
+ *
4886
+ * The retry loop has always classified its failures precisely, but only as an
4887
+ * interpolated `reason` string for `log.warn` — and prod ships no SDK log
4888
+ * (sdk#883), so in production every one of these collapsed into a single
4889
+ * `empty-after-retry` with no way to tell them apart. That is what made the
4890
+ * 2026-08-11 audit need a Prometheus cross-check to discover that the portal
4891
+ * was returning HTTP 200 with an empty body on ~60% of extraction turns.
4892
+ *
4893
+ * Codes are deliberately an enum, not the `reason` string: the strings embed
4894
+ * status codes and error messages, so they are unbounded and useless as an
4895
+ * analytics property. Keep this list SHORT and stable — it is a telemetry
4896
+ * contract, and a value added here has to mean the same thing in six months.
4897
+ *
4898
+ * @public
4899
+ */
4900
+ type PortalLlmFailureReason =
4901
+ /** No usable credential — `getToken` returned null or threw. Terminal. */
4902
+ "auth-unavailable"
4903
+ /** Non-retryable HTTP status (400/403/404, or 401 on the static-apiKey path). */
4904
+ | "http-terminal"
4905
+ /** Retryable status (408/409/425/429/5xx) that never succeeded. */
4906
+ | "http-retryable"
4907
+ /** Network error or the per-attempt timeout aborted the fetch. */
4908
+ | "network"
4909
+ /** HTTP 200 but the envelope itself wasn't JSON. */
4910
+ | "body-parse-failed"
4911
+ /**
4912
+ * HTTP 200 with NO completion content. The reasoning-class failure mode:
4913
+ * the model spends its budget on unreturned thinking and answers empty.
4914
+ */
4915
+ | "empty-content"
4916
+ /** Content present, but no parseable JSON in it (prose, a clarifying question). */
4917
+ | "invalid-json"
4918
+ /** Content parsed to a literal `null`, which is never a valid response. */
4919
+ | "null-completion"
4920
+ /** `totalTimeoutMs` was spent before the next attempt could run. */
4921
+ | "time-budget-exhausted";
4922
+ /**
4923
+ * A give-up report: the classified {@link PortalLlmFailureReason} plus the
4924
+ * little context worth carrying into telemetry. Both extra fields are bounded
4925
+ * (a status code, a small attempt count), so both are safe as event properties.
4926
+ *
4927
+ * @public
4928
+ */
4929
+ interface PortalLlmFailure {
4930
+ /** Stable code for the last failure observed. */
4931
+ reason: PortalLlmFailureReason;
4932
+ /** HTTP status, when the failure was an HTTP one. */
4933
+ httpStatus?: number;
4934
+ /** How many attempts ran before giving up (1-based, ≥ 1). */
4935
+ attempts: number;
4936
+ }
4883
4937
 
4884
4938
  /**
4885
4939
  * Optional LLM injection classifier — Tier-0 security second layer (PR5).
@@ -5984,8 +6038,14 @@ interface ExtractFactsOptions extends PortalLlmAuth {
5984
6038
  * `{candidates: []}` "nothing durable here". Lets callers distinguish a
5985
6039
  * silently-degrading extractor from quiet turns (the two are otherwise
5986
6040
  * indistinguishable). See {@link extractAndRetain}'s `outcome`.
6041
+ *
6042
+ * Receives the classified {@link PortalLlmFailure}. Knowing THAT extraction
6043
+ * failed was not enough: the 2026-08-11 audit found ~60% of production turns
6044
+ * ending here and had to cross-check Prometheus to learn that the cause was
6045
+ * HTTP-200-with-empty-body rather than the 403 everyone assumed. Forward
6046
+ * `failure.reason` into analytics so the next such question is a query.
5987
6047
  */
5988
- onExhaustedEmpty?: () => void;
6048
+ onExhaustedEmpty?: (failure: PortalLlmFailure) => void;
5989
6049
  /**
5990
6050
  * Called when the extractor DID produce candidates but PII de-anonymization
5991
6051
  * dropped every one of them — the model mangled its placeholders (so they
@@ -6108,6 +6168,11 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6108
6168
  * "extracted but held for review".
6109
6169
  */
6110
6170
  quarantined: QuarantinedMemoryInfo[];
6171
+ /**
6172
+ * Present only when `outcome` is `empty-after-retry` — the classified cause of
6173
+ * the give-up, so "extraction is failing" can be reported as *why* it failed.
6174
+ */
6175
+ failure?: PortalLlmFailure;
6111
6176
  }>;
6112
6177
 
6113
6178
  /**
@@ -10232,4 +10297,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
10232
10297
  */
10233
10298
  declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
10234
10299
 
10235
- export { type AutoExtractMessage, type AutoExtractor, type Budget, CHUNKS_DISCARDED_ORIGIN, type CachedChunkVectors, type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ChunkVectorCache, type ChunkingOptions, type ConsolidationFallbackReason, type ConversationMemoryInput, ConversationMemory as ConversationMemoryModel, type ConversationMemoryOperationsContext, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMessageOptions, type CreateVaultFolderOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_VAULT_CACHE_SIZE, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type DecayCandidateRaw, type DecayClassifier, type DecayInput, type DecayPolicy, type DecaySweepResult, type DecaySweeper, type DecayVerdict, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, type FlushResult, type GetConversationsPageOptions, type GetMessagesPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, type MessageRedactionResult, type MessageSkeleton, NEVER_TTL_MS, NODE_BUDGET, NOTION_OAUTH_CONFIG, type NeighborRefiner, type NotionAuthUrlParams, type NotionClientRegistration, type NotionExchangeCodeParams, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type ResumeStreamWithStorageResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, SDK_SCHEMA_VERSION, SHORT_TTL_MS, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageDetachedResult, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type StockPriceClassification, type StockPricePreProcessorOptions, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredConversationMemory, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateVaultFolderOptions, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, type VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, backfillMemoryTopicsOp, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createLlmDecayClassifier, createLlmNeighborRefiner, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionTools, createPlatformCursorStore, createRecallTool, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, generateConversationId, generateEmbedding, generateEmbeddings, generateNotionPKCE, getAllVaultFoldersOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getCachedServerTools, getConversationMemoriesOp, getConversationsByProjectLazyOp, getConversationsLazyOp, getConversationsPageOp, getDecayCandidatesRawOp, getLogger, getMemoriesNeedingTopicExtractionOp, getServerTools, getUnfiledVaultMemoriesOp, getVaultFolderMemoryCountOp, getVaultMemoriesByIdsOp, getVaultMemoryOp, getVaultRankingProjectionsOp, hardDeleteDecayedOp, hasEncryptionKey, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isPiiRedactor, isRerankerAvailable, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
10300
+ export { type AutoExtractMessage, type AutoExtractor, type Budget, CHUNKS_DISCARDED_ORIGIN, type CachedChunkVectors, type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ChunkVectorCache, type ChunkingOptions, type ConsolidationFallbackReason, type ConversationMemoryInput, ConversationMemory as ConversationMemoryModel, type ConversationMemoryOperationsContext, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMessageOptions, type CreateVaultFolderOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_VAULT_CACHE_SIZE, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type DecayCandidateRaw, type DecayClassifier, type DecayInput, type DecayPolicy, type DecaySweepResult, type DecaySweeper, type DecayVerdict, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, type FlushResult, type GetConversationsPageOptions, type GetMessagesPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, type MessageRedactionResult, type MessageSkeleton, NEVER_TTL_MS, NODE_BUDGET, NOTION_OAUTH_CONFIG, type NeighborRefiner, type NotionAuthUrlParams, type NotionClientRegistration, type NotionExchangeCodeParams, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type ResumeStreamWithStorageResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, SDK_SCHEMA_VERSION, SHORT_TTL_MS, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageDetachedResult, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type StockPriceClassification, type StockPricePreProcessorOptions, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredConversationMemory, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateVaultFolderOptions, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, type VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, backfillMemoryTopicsOp, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createLlmDecayClassifier, createLlmNeighborRefiner, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionTools, createPlatformCursorStore, createRecallTool, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, generateConversationId, generateEmbedding, generateEmbeddings, generateNotionPKCE, getAllVaultFoldersOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getCachedServerTools, getConversationMemoriesOp, getConversationsByProjectLazyOp, getConversationsLazyOp, getConversationsPageOp, getDecayCandidatesRawOp, getLogger, getMemoriesNeedingTopicExtractionOp, getServerTools, getUnfiledVaultMemoriesOp, getVaultFolderMemoryCountOp, getVaultMemoriesByIdsOp, getVaultMemoryOp, getVaultRankingProjectionsOp, hardDeleteDecayedOp, hasEncryptionKey, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isPiiRedactor, isRerankerAvailable, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
@@ -4880,6 +4880,60 @@ interface PortalLlmAuth {
4880
4880
  /** Function to get an auth token (e.g., Privy's getIdentityToken). Token is sent as `Authorization: Bearer`. */
4881
4881
  getToken?: () => Promise<string | null>;
4882
4882
  }
4883
+ /**
4884
+ * Why a portal JSON completion gave up, as a STABLE low-cardinality code.
4885
+ *
4886
+ * The retry loop has always classified its failures precisely, but only as an
4887
+ * interpolated `reason` string for `log.warn` — and prod ships no SDK log
4888
+ * (sdk#883), so in production every one of these collapsed into a single
4889
+ * `empty-after-retry` with no way to tell them apart. That is what made the
4890
+ * 2026-08-11 audit need a Prometheus cross-check to discover that the portal
4891
+ * was returning HTTP 200 with an empty body on ~60% of extraction turns.
4892
+ *
4893
+ * Codes are deliberately an enum, not the `reason` string: the strings embed
4894
+ * status codes and error messages, so they are unbounded and useless as an
4895
+ * analytics property. Keep this list SHORT and stable — it is a telemetry
4896
+ * contract, and a value added here has to mean the same thing in six months.
4897
+ *
4898
+ * @public
4899
+ */
4900
+ type PortalLlmFailureReason =
4901
+ /** No usable credential — `getToken` returned null or threw. Terminal. */
4902
+ "auth-unavailable"
4903
+ /** Non-retryable HTTP status (400/403/404, or 401 on the static-apiKey path). */
4904
+ | "http-terminal"
4905
+ /** Retryable status (408/409/425/429/5xx) that never succeeded. */
4906
+ | "http-retryable"
4907
+ /** Network error or the per-attempt timeout aborted the fetch. */
4908
+ | "network"
4909
+ /** HTTP 200 but the envelope itself wasn't JSON. */
4910
+ | "body-parse-failed"
4911
+ /**
4912
+ * HTTP 200 with NO completion content. The reasoning-class failure mode:
4913
+ * the model spends its budget on unreturned thinking and answers empty.
4914
+ */
4915
+ | "empty-content"
4916
+ /** Content present, but no parseable JSON in it (prose, a clarifying question). */
4917
+ | "invalid-json"
4918
+ /** Content parsed to a literal `null`, which is never a valid response. */
4919
+ | "null-completion"
4920
+ /** `totalTimeoutMs` was spent before the next attempt could run. */
4921
+ | "time-budget-exhausted";
4922
+ /**
4923
+ * A give-up report: the classified {@link PortalLlmFailureReason} plus the
4924
+ * little context worth carrying into telemetry. Both extra fields are bounded
4925
+ * (a status code, a small attempt count), so both are safe as event properties.
4926
+ *
4927
+ * @public
4928
+ */
4929
+ interface PortalLlmFailure {
4930
+ /** Stable code for the last failure observed. */
4931
+ reason: PortalLlmFailureReason;
4932
+ /** HTTP status, when the failure was an HTTP one. */
4933
+ httpStatus?: number;
4934
+ /** How many attempts ran before giving up (1-based, ≥ 1). */
4935
+ attempts: number;
4936
+ }
4883
4937
 
4884
4938
  /**
4885
4939
  * Optional LLM injection classifier — Tier-0 security second layer (PR5).
@@ -5984,8 +6038,14 @@ interface ExtractFactsOptions extends PortalLlmAuth {
5984
6038
  * `{candidates: []}` "nothing durable here". Lets callers distinguish a
5985
6039
  * silently-degrading extractor from quiet turns (the two are otherwise
5986
6040
  * indistinguishable). See {@link extractAndRetain}'s `outcome`.
6041
+ *
6042
+ * Receives the classified {@link PortalLlmFailure}. Knowing THAT extraction
6043
+ * failed was not enough: the 2026-08-11 audit found ~60% of production turns
6044
+ * ending here and had to cross-check Prometheus to learn that the cause was
6045
+ * HTTP-200-with-empty-body rather than the 403 everyone assumed. Forward
6046
+ * `failure.reason` into analytics so the next such question is a query.
5987
6047
  */
5988
- onExhaustedEmpty?: () => void;
6048
+ onExhaustedEmpty?: (failure: PortalLlmFailure) => void;
5989
6049
  /**
5990
6050
  * Called when the extractor DID produce candidates but PII de-anonymization
5991
6051
  * dropped every one of them — the model mangled its placeholders (so they
@@ -6108,6 +6168,11 @@ declare function extractAndRetain(messages: AutoExtractMessage[], retainCtx: Ret
6108
6168
  * "extracted but held for review".
6109
6169
  */
6110
6170
  quarantined: QuarantinedMemoryInfo[];
6171
+ /**
6172
+ * Present only when `outcome` is `empty-after-retry` — the classified cause of
6173
+ * the give-up, so "extraction is failing" can be reported as *why* it failed.
6174
+ */
6175
+ failure?: PortalLlmFailure;
6111
6176
  }>;
6112
6177
 
6113
6178
  /**
@@ -10232,4 +10297,4 @@ declare function refreshNotionAccessToken(params: NotionRefreshTokenParams): Pro
10232
10297
  */
10233
10298
  declare function createNotionTools(getAccessToken: () => string | null, requestNotionAccess: () => Promise<string>): ToolConfig[];
10234
10299
 
10235
- export { type AutoExtractMessage, type AutoExtractor, type Budget, CHUNKS_DISCARDED_ORIGIN, type CachedChunkVectors, type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ChunkVectorCache, type ChunkingOptions, type ConsolidationFallbackReason, type ConversationMemoryInput, ConversationMemory as ConversationMemoryModel, type ConversationMemoryOperationsContext, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMessageOptions, type CreateVaultFolderOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_VAULT_CACHE_SIZE, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type DecayCandidateRaw, type DecayClassifier, type DecayInput, type DecayPolicy, type DecaySweepResult, type DecaySweeper, type DecayVerdict, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, type FlushResult, type GetConversationsPageOptions, type GetMessagesPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, type MessageRedactionResult, type MessageSkeleton, NEVER_TTL_MS, NODE_BUDGET, NOTION_OAUTH_CONFIG, type NeighborRefiner, type NotionAuthUrlParams, type NotionClientRegistration, type NotionExchangeCodeParams, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type ResumeStreamWithStorageResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, SDK_SCHEMA_VERSION, SHORT_TTL_MS, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageDetachedResult, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type StockPriceClassification, type StockPricePreProcessorOptions, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredConversationMemory, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateVaultFolderOptions, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, type VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, backfillMemoryTopicsOp, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createLlmDecayClassifier, createLlmNeighborRefiner, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionTools, createPlatformCursorStore, createRecallTool, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, generateConversationId, generateEmbedding, generateEmbeddings, generateNotionPKCE, getAllVaultFoldersOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getCachedServerTools, getConversationMemoriesOp, getConversationsByProjectLazyOp, getConversationsLazyOp, getConversationsPageOp, getDecayCandidatesRawOp, getLogger, getMemoriesNeedingTopicExtractionOp, getServerTools, getUnfiledVaultMemoriesOp, getVaultFolderMemoryCountOp, getVaultMemoriesByIdsOp, getVaultMemoryOp, getVaultRankingProjectionsOp, hardDeleteDecayedOp, hasEncryptionKey, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isPiiRedactor, isRerankerAvailable, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };
10300
+ export { type AutoExtractMessage, type AutoExtractor, type Budget, CHUNKS_DISCARDED_ORIGIN, type CachedChunkVectors, type CachedServerTools, Conversation as ChatConversation, Message as ChatMessage, type ChatRole, type ChunkVectorCache, type ChunkingOptions, type ConsolidationFallbackReason, type ConversationMemoryInput, ConversationMemory as ConversationMemoryModel, type ConversationMemoryOperationsContext, type CreateAutoExtractorOptions, type CreateConversationOptions, type CreateDecaySweeperOptions, type CreateMessageOptions, type CreateVaultFolderOptions, type CreateVaultMemoryOptions, type CryptoPriceClassification, type CryptoPricePreProcessorOptions, DEFAULT_CACHE_EXPIRATION_MS, DEFAULT_CHUNK_CACHE_SIZE, DEFAULT_CHUNK_OVERLAP, DEFAULT_CHUNK_SIZE, DEFAULT_DECAY_POLICY, DEFAULT_MAX_CLASSIFIER_CALLS_PER_SWEEP, DEFAULT_MIN_CHUNK_SIZE, DEFAULT_PROFILE_FACETS, DEFAULT_PROFILE_FACT_TYPE_WEIGHTS, DEFAULT_PROFILE_PROOF_ALPHA, DEFAULT_PROFILE_TREND_MULTIPLIERS, DEFAULT_VAULT_CACHE_SIZE, DatabaseManager, type DatabaseManagerLogger, type DatabaseManagerOptions, type DecayCandidateRaw, type DecayClassifier, type DecayInput, type DecayPolicy, type DecaySweepResult, type DecaySweeper, type DecayVerdict, ENTITY_FANOUT, type EmbeddedWalletSignerFn, EncryptionKeyMissingError, type ExtractFactsOptions, type ExtractOutcome, type ExtractedCandidate, type ExtractedEntity, type ExtractionCursorStore, type FactType, type FileMetadata, type FlushResult, type GetConversationsPageOptions, type GetMessagesPageOptions, type GraphTraversalOptions, HARD_DELETE_WINDOW_MS, INFERENCE_ID_HEADER, type InjectionClassifierOptions, type InjectionReason, type LazyStoredConversation, type LlmDecayClassifierOptions, type LlmNeighborRefinerOptions, type Logger, LoggerProvider, type LoggerProviderProps, MAX_HOPS, MEDIUM_TTL_MS, type MemoriesNeedingTopicExtraction, type EmbeddingOptions as MemoryEngineEmbeddingOptions, type MemoryEngineResult, type MemoryEngineSearchOptions, type MemoryExtractedEvent, type MemoryKind, type MemoryQuarantinedEvent, type MemoryToVerify, type MemoryVaultSearchOptions, type MemoryVaultToolOptions, type MemoryVerification, type MessageRedactionResult, type MessageSkeleton, NEVER_TTL_MS, NODE_BUDGET, NOTION_OAUTH_CONFIG, type NeighborRefiner, type NotionAuthUrlParams, type NotionClientRegistration, type NotionExchangeCodeParams, type NotionOAuthEndpoints, type NotionPKCEChallenge, type NotionRefreshTokenParams, type NotionTokenResponse, type NowSource, type ObservationTrend, type ObservationTrendInput, PAST_EVENT_GRACE_MS, PII_PATTERNS, PROFILE_DOC_VERSION, type PhotoIngestResult, type PhotoMediaRef, type PiiCategory, type PiiMatch, type PiiPattern, PiiRedactor, type PiiRedactorOptions, type PlatformStorage, type PortalLlmAuth, type PortalLlmFailure, type PortalLlmFailureReason, type ProfileConfigFingerprint, type ProfileDoc, type ProfileFacet, type ProfileFacetKey, type ProfileSalienceInput, type ProfileSection, type PromptPreProcessor, type PromptPreProcessorContext, type PublishedPhotoMemory, type QuantizedEmbedding, type QuarantinedMemoryInfo, QueueManager, type QueueStatus, RECALL_MAX_LIMIT, RECALL_TOOL_NAME, type RankableVaultMemory, type RankedMemory, type RankedProfileCandidate, type RecallContext, type RecallDegradation, type RecallDiagnostics, type RecallOptions, type RecallResult, type RecallToolCallbacks, type RecallToolOptions, type RecencyOptions, type RedactionResult, type ReflectOptions, type ReflectResult, type RequestEncryptionKeyOptions, RerankerUnavailableError, type ResumeStreamOptions, type ResumeStreamResult, type ResumeStreamWithStorageResult, type RetainAction, type RetainContext, type RetainOptions, type RetainResult, type RetainSource, SDK_SCHEMA_VERSION, SHORT_TTL_MS, STREAM_RESUMABLE_HEADER, type ScoreBreakdown, type ScoreProfileSalienceOptions, type ScreenResult, type ScreenedCandidate, type SearchSource, type SendMessageWithStorageArgs, type SendMessageWithStorageDetachedResult, type SendMessageWithStorageResult, type ServerToolsOptions, type ServerToolsResponse, type SignMessageFn, type StockPriceClassification, type StockPricePreProcessorOptions, type ChatCompletionUsage as StoredChatCompletionUsage, type StoredConversation, type StoredConversationMemory, type StoredMessage, type StoredMessageWithSimilarity, type StoredVaultFolder, VaultFolder as StoredVaultFolderModel, type StoredVaultMemory, VaultMemory as StoredVaultMemoryModel, StreamExpiredError, type StreamMetaEvent, type StreamResumeHandle, type SynthesizeProfileOptions, TOOL_RESULT_ORIGIN, TOPICS_EXTRACTION_VERSION, TOPIC_EXTRACTION_BATCH_SIZE, TREND_RECENT_WINDOW_DAYS, TREND_STALE_WINDOW_DAYS, type TextChunk, type TopicExtractOptions, type TopicExtractionInput, type TopicExtractionRunResult, type TurnCompleteEvent, type TurnSkippedEvent, type UncheckedReason, type UnverifiableReason, type UpdateVaultFolderOptions, type UpdateVaultMemoryOptions, type UseChatStorageOptions, type UseChatStorageResult, type UseCreditsOptions, type UseCreditsResult, type UseModelsOptions, type UseModelsResult, VAULT_SIZE_HOP_CAP, type VaultEmbeddingCache, type VaultFolderOperationsContext, type VaultMemoryOperationsContext, type VaultMemoryVisibility, type VaultSaveOperation, type VaultSearchResult, type VerificationSources, type VerifyMemoriesForPublishOptions, WalletPoller, type WeatherClassification, type WeatherPreProcessorOptions, type WebSearchClassification, type WebSearchPreProcessorOptions, addConversationMemoriesOp, archiveVaultMemoryOp, backfillMemoryTopicsOp, buildNotionAuthUrl, capHopsForDensity, chatStorageMigrations, chatStorageSchema, chunkAndEmbedAllMessages, chunkAndEmbedMessage, chunkText, classifyCryptoPrice, classifyCryptoPriceBatch, classifyDecay, classifyInjectionCandidates, classifyObservationTrend, classifyStockPrice, classifyStockPriceBatch, classifyWeather, classifyWeatherBatch, classifyWebSearch, classifyWebSearchBatch, clearAllEncryptionKeys, clearAllEncryptionState, clearConversationMemoriesOp, clearEncryptionKey, clearLazyTitleCache, clearServerToolsCache, consoleLogger, conversationMemoryToStored, cosineInt8, createAutoExtractor, createChunkVectorCache, createCryptoPricePreProcessor, createDecaySweeper, createLlmDecayClassifier, createLlmNeighborRefiner, createMemoryEngineTool, createMemoryVaultSearchTool, createMemoryVaultTool, createMessageSourceResolver, createNotionTools, createPlatformCursorStore, createRecallTool, createStockPricePreProcessor, createStreamingDeAnonymizer, createVaultEmbeddingCache, createVaultFolderOp, createVaultMemoriesBatchOp, createVaultMemoryOp, createWeatherPreProcessor, createWebSearchPreProcessor, decodeChunkVector, decryptConversationTitle, deleteAllVaultMemoriesForUserOp, deleteVaultFolderOp, deleteVaultMemoryOp, dequantizeEmbedding, discoverNotionOAuthEndpoints, eagerEmbedContent, embedAllMessages, embedMessage, encodeChunkVector, ensureDefaultFoldersOp, exchangeNotionCode, extractAndLinkEntitiesForMemoriesOp, extractAndRetain, extractEntitiesForMemories, extractFacts, generateConversationId, generateEmbedding, generateEmbeddings, generateNotionPKCE, getAllVaultFoldersOp, getAllVaultMemoriesOp, getAllVaultMemoryContentsOp, getCachedServerTools, getConversationMemoriesOp, getConversationsByProjectLazyOp, getConversationsLazyOp, getConversationsPageOp, getDecayCandidatesRawOp, getLogger, getMemoriesNeedingTopicExtractionOp, getServerTools, getUnfiledVaultMemoriesOp, getVaultFolderMemoryCountOp, getVaultMemoriesByIdsOp, getVaultMemoryOp, getVaultRankingProjectionsOp, hardDeleteDecayedOp, hasEncryptionKey, ingestPublishedPhotoMemoriesOp, injectionSignatureCatalog, isPiiRedactor, isRerankerAvailable, moveMemoriesToFolderOp, noopLogger, onKeyAvailable, parseMedia, preEmbedVaultMemories, quantizeEmbedding, queueManager, rankProfileCandidates, recall, reflect, refreshEncryptionKeyIfMatches, refreshNotionAccessToken, registerNotionClient, relinkMemoryTopicsOp, requestEncryptionKey, resolvePiiRedactor, restoreVaultMemoryOp, resumeStream, retain, scoreProfileSalience, screenCandidatesForInjection, sdkMigrations, sdkModelClasses, sdkSchema, searchVaultMemories, seedEncryptionKeys, setLogger, setMemoryVisibilityOp, shouldChunkMessage, stampTopicsExtractedAtOp, streamCancelPath, streamReplayPath, summarizeObservationTrends, supersedeVaultMemoryOp, synthesizeProfile, traverseGraphLane, ttlForType, updateVaultFolderContextOp, updateVaultFolderOp, updateVaultMemoryEmbeddingOp, updateVaultMemoryOp, upsertMessageOp, useChat, useChatStorage, useCredits, useEncryption, useModels, verifyMemoriesForPublish, xhrTransport };