kagura-memory 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -7,6 +7,16 @@ import { readFileSync as readFileSync7 } from "fs";
7
7
  import * as readline from "readline/promises";
8
8
 
9
9
  // src/errors.ts
10
+ function secondsUntil(iso) {
11
+ if (iso === null) {
12
+ return null;
13
+ }
14
+ const at = Date.parse(iso);
15
+ if (Number.isNaN(at)) {
16
+ return null;
17
+ }
18
+ return Math.max(0, Math.ceil((at - Date.now()) / 1e3));
19
+ }
10
20
  function excMessage(e) {
11
21
  if (e instanceof Error) {
12
22
  return e.message || e.constructor.name;
@@ -37,16 +47,97 @@ var KaguraNotFoundError = class extends KaguraError {
37
47
  };
38
48
  var KaguraRateLimitError = class extends KaguraError {
39
49
  retryAfter;
40
- constructor(message, retryAfter = null, options) {
50
+ gate;
51
+ quotaType;
52
+ current;
53
+ limit;
54
+ usedToday;
55
+ resetsAt;
56
+ feature;
57
+ requiredPlan;
58
+ requiredPlanDisplay;
59
+ currentPlan;
60
+ constructor(message, retryAfter = null, options = {}) {
41
61
  super(message, options);
42
- this.retryAfter = retryAfter;
62
+ this.gate = options.gate ?? null;
63
+ this.quotaType = options.quotaType ?? null;
64
+ this.usedToday = options.usedToday ?? null;
65
+ this.current = options.current ?? this.usedToday;
66
+ this.limit = options.limit ?? null;
67
+ this.resetsAt = options.resetsAt ?? null;
68
+ this.feature = options.feature ?? null;
69
+ this.requiredPlan = options.requiredPlan ?? null;
70
+ this.requiredPlanDisplay = options.requiredPlanDisplay ?? null;
71
+ this.currentPlan = options.currentPlan ?? null;
72
+ this.retryAfter = retryAfter ?? secondsUntil(this.resetsAt);
43
73
  }
44
74
  };
45
75
  var KaguraQuotaError = class extends KaguraError {
46
76
  retryAfter;
47
- constructor(message, retryAfter = null, options) {
77
+ gate;
78
+ quotaType;
79
+ /**
80
+ * Count already used. A server older than v0.75.0 sent no `current`, so
81
+ * the SDK reads the refusal's legacy count instead: `used_today`,
82
+ * `owned_count` or `active_connectors`. An error built by hand falls back
83
+ * to `usedToday`.
84
+ */
85
+ current;
86
+ /**
87
+ * The cap that was hit. When the refusal has no `limit`, the SDK reads
88
+ * its legacy name instead: `limit_today`, `cap` or `max_connectors`.
89
+ */
90
+ limit;
91
+ usedToday;
92
+ resetsAt;
93
+ feature;
94
+ requiredPlan;
95
+ requiredPlanDisplay;
96
+ currentPlan;
97
+ constructor(message, retryAfter = null, options = {}) {
98
+ super(message, options);
99
+ this.gate = options.gate ?? null;
100
+ this.quotaType = options.quotaType ?? null;
101
+ this.usedToday = options.usedToday ?? null;
102
+ this.current = options.current ?? this.usedToday;
103
+ this.limit = options.limit ?? null;
104
+ this.resetsAt = options.resetsAt ?? null;
105
+ this.feature = options.feature ?? null;
106
+ this.requiredPlan = options.requiredPlan ?? null;
107
+ this.requiredPlanDisplay = options.requiredPlanDisplay ?? null;
108
+ this.currentPlan = options.currentPlan ?? null;
109
+ this.retryAfter = retryAfter ?? secondsUntil(this.resetsAt);
110
+ }
111
+ };
112
+ var KaguraFeatureNotAvailableError = class extends KaguraError {
113
+ gate;
114
+ feature;
115
+ requiredPlan;
116
+ requiredPlanDisplay;
117
+ currentPlan;
118
+ constructor(message, options = {}) {
119
+ super(message, options);
120
+ this.gate = options.gate ?? null;
121
+ this.feature = options.feature ?? null;
122
+ this.requiredPlan = options.requiredPlan ?? null;
123
+ this.requiredPlanDisplay = options.requiredPlanDisplay ?? null;
124
+ this.currentPlan = options.currentPlan ?? null;
125
+ }
126
+ };
127
+ var KaguraPartialRollbackError = class extends KaguraError {
128
+ reportId;
129
+ summary;
130
+ constructor(message, reportId = null, summary = {}, options) {
48
131
  super(message, options);
49
- this.retryAfter = retryAfter;
132
+ this.reportId = reportId;
133
+ this.summary = summary;
134
+ }
135
+ };
136
+ var KaguraPermissionError = class extends KaguraError {
137
+ requiredRole;
138
+ constructor(message, requiredRole = null, options) {
139
+ super(message, options);
140
+ this.requiredRole = requiredRole;
50
141
  }
51
142
  };
52
143
  var KaguraIntegrityError = class extends KaguraError {
@@ -57,12 +148,16 @@ var KaguraCryptoError = class extends KaguraSecretError {
57
148
  };
58
149
 
59
150
  // src/version.ts
60
- var SDK_VERSION = "0.8.0";
151
+ var SDK_VERSION = "0.9.0";
61
152
 
62
153
  // src/http.ts
63
154
  function baseUrlFromMcp(mcpUrl) {
64
- const m = /\/mcp(?=\/|$)/.exec(mcpUrl);
65
- return m ? mcpUrl.slice(0, m.index) : mcpUrl;
155
+ const end = mcpUrl.search(/[?#]/);
156
+ const path8 = end === -1 ? mcpUrl : mcpUrl.slice(0, end).replace(/\/+$/, "");
157
+ const authority = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i.exec(path8);
158
+ const from = authority ? authority[0].length : 0;
159
+ const m = /\/mcp(?=\/|$)/.exec(path8.slice(from));
160
+ return m ? path8.slice(0, from + m.index) : path8;
66
161
  }
67
162
  function formatValidationErrors(errors) {
68
163
  const parts = [];
@@ -84,6 +179,13 @@ function formatValidationErrors(errors) {
84
179
  }
85
180
  return parts.join("; ");
86
181
  }
182
+ function jsonRpcError(body) {
183
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
184
+ return null;
185
+ }
186
+ const error = body.error;
187
+ return typeof error === "object" && error !== null && !Array.isArray(error) ? error : null;
188
+ }
87
189
  function extractDetail(bodyText) {
88
190
  let body;
89
191
  try {
@@ -116,8 +218,28 @@ function extractDetail(bodyText) {
116
218
  }
117
219
  return message;
118
220
  }
221
+ const rpcMessage = jsonRpcError(rec)?.message;
222
+ if (typeof rpcMessage === "string" && rpcMessage) {
223
+ return rpcMessage;
224
+ }
119
225
  return "";
120
226
  }
227
+ function mcpSessionHeader(sessionId) {
228
+ return sessionId ? { "mcp-session-id": sessionId } : {};
229
+ }
230
+ var JSONRPC_METHOD_NOT_FOUND = -32601;
231
+ function mcpSessionExpired(status, bodyText, sessionId) {
232
+ if (!sessionId || status !== 404) {
233
+ return false;
234
+ }
235
+ let body;
236
+ try {
237
+ body = JSON.parse(bodyText);
238
+ } catch {
239
+ return true;
240
+ }
241
+ return jsonRpcError(body)?.code !== JSONRPC_METHOD_NOT_FOUND;
242
+ }
121
243
  function sanitizeServerDetail(detail) {
122
244
  if (!detail) {
123
245
  return null;
@@ -136,15 +258,111 @@ function retryAfterSeconds(headers) {
136
258
  const trimmed = raw.trim();
137
259
  return /^\d+$/.test(trimmed) ? parseInt(trimmed, 10) : null;
138
260
  }
261
+ var MCP_GATE_CODES = {
262
+ plan: ["plan_required", "feature_not_available"],
263
+ quota: ["quota_exceeded", "CONNECTOR-001"]
264
+ };
265
+ var REST_GATE_CODES = {
266
+ plan: ["FEAT-001"],
267
+ quota: ["QUOTA-001", "QUOTA-002", "CONNECTOR-001"]
268
+ };
269
+ function stringField(block, key) {
270
+ const value = block[key];
271
+ return typeof value === "string" ? value : null;
272
+ }
273
+ function numberField(block, key) {
274
+ const value = block[key];
275
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
276
+ }
277
+ function firstNumberField(block, keys) {
278
+ for (const key of keys) {
279
+ const value = numberField(block, key);
280
+ if (value !== null) {
281
+ return value;
282
+ }
283
+ }
284
+ return null;
285
+ }
286
+ function bodyRetryAfter(block, key) {
287
+ const value = numberField(block, key);
288
+ return value === null || value < 0 ? null : Math.ceil(value);
289
+ }
290
+ function responseRetryAfter(headers, bodyText) {
291
+ const header = retryAfterSeconds(headers);
292
+ if (header !== null) {
293
+ return header;
294
+ }
295
+ const envelope = parseErrorEnvelope(bodyText);
296
+ return envelope === null ? null : bodyRetryAfter(envelope.details, "retry_after");
297
+ }
298
+ function gateKind(block, code2, codes) {
299
+ const gate = stringField(block, "gate");
300
+ if (gate === "quota") {
301
+ return "quota";
302
+ }
303
+ if (gate === "plan" || gate === "allowlist" || gate === "deployment") {
304
+ return "plan";
305
+ }
306
+ if (code2 !== null && codes.quota.includes(code2)) {
307
+ return "quota";
308
+ }
309
+ if (code2 !== null && codes.plan.includes(code2)) {
310
+ return "plan";
311
+ }
312
+ return null;
313
+ }
314
+ var LEGACY_CURRENT_KEYS = ["used_today", "owned_count", "active_connectors"];
315
+ var LEGACY_LIMIT_KEYS = ["limit_today", "cap", "max_connectors"];
316
+ function gateOptions(block) {
317
+ return {
318
+ gate: stringField(block, "gate"),
319
+ feature: stringField(block, "feature"),
320
+ requiredPlan: stringField(block, "required_plan"),
321
+ requiredPlanDisplay: stringField(block, "required_plan_display"),
322
+ currentPlan: stringField(block, "current_plan"),
323
+ quotaType: stringField(block, "quota_type"),
324
+ current: firstNumberField(block, ["current", ...LEGACY_CURRENT_KEYS]),
325
+ limit: firstNumberField(block, ["limit", ...LEGACY_LIMIT_KEYS]),
326
+ usedToday: numberField(block, "used_today"),
327
+ resetsAt: stringField(block, "resets_at")
328
+ };
329
+ }
330
+ function gateError(block, code2, codes, message, retryAfter = null) {
331
+ const kind = gateKind(block, code2, codes);
332
+ if (kind === null) {
333
+ return null;
334
+ }
335
+ const options = gateOptions(block);
336
+ return kind === "plan" ? new KaguraFeatureNotAvailableError(message, options) : new KaguraQuotaError(message, retryAfter, options);
337
+ }
338
+ function parseErrorEnvelope(bodyText) {
339
+ let body;
340
+ try {
341
+ body = JSON.parse(bodyText);
342
+ } catch {
343
+ return null;
344
+ }
345
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
346
+ return null;
347
+ }
348
+ const rec = body;
349
+ const details = rec.details;
350
+ return {
351
+ code: typeof rec.error === "string" ? rec.error : null,
352
+ details: typeof details === "object" && details !== null && !Array.isArray(details) ? details : {}
353
+ };
354
+ }
139
355
  function throwForKaguraStatus(status, headers, bodyText, fallbackMessage) {
140
356
  if (status === 401) {
141
357
  throw new KaguraAuthError("Authentication failed. Check your API key.");
142
358
  }
143
359
  const detail = extractDetail(bodyText) || fallbackMessage || "";
144
360
  if (status === 429) {
361
+ const envelope = parseErrorEnvelope(bodyText);
145
362
  throw new KaguraRateLimitError(
146
363
  `Rate limit exceeded (HTTP 429): ${detail || `HTTP ${status}`}`,
147
- retryAfterSeconds(headers)
364
+ responseRetryAfter(headers, bodyText),
365
+ envelope !== null && gateKind(envelope.details, envelope.code, REST_GATE_CODES) === "quota" ? gateOptions(envelope.details) : {}
148
366
  );
149
367
  }
150
368
  throw new KaguraConnectionError(detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}`);
@@ -1734,7 +1952,7 @@ var FETCH_FACTOR = {
1734
1952
  var RERANKER = {
1735
1953
  name: "reranker",
1736
1954
  type: "value",
1737
- metavar: "[voyage|cohere]",
1955
+ metavar: "[voyage|cohere|self_hosted]",
1738
1956
  help: "Reranker provider"
1739
1957
  };
1740
1958
  var searchConfig = {
@@ -1766,7 +1984,7 @@ var searchConfig = {
1766
1984
  "--no-rerank"
1767
1985
  ]);
1768
1986
  const rawReranker = args.values.reranker;
1769
- const rerankerProvider = rawReranker === void 0 ? void 0 : parseChoice(RERANKER, rawReranker, ["voyage", "cohere"]);
1987
+ const rerankerProvider = rawReranker === void 0 ? void 0 : parseChoice(RERANKER, rawReranker, ["voyage", "cohere", "self_hosted"]);
1770
1988
  const rerankerModel = args.values["reranker-model"];
1771
1989
  const patch = {
1772
1990
  ...semanticWeight !== void 0 ? { semanticWeight } : {},
@@ -2633,7 +2851,7 @@ var reference = {
2633
2851
  };
2634
2852
  var FORGET_K = kFlag("Max memories to delete in query mode", "10");
2635
2853
  var forget = {
2636
- summary: "Delete memories (soft delete, recoverable for 30 days).",
2854
+ summary: "Delete memories (soft delete; kept until the server's retention window passes, default 30 days).",
2637
2855
  spec: {
2638
2856
  flags: [
2639
2857
  CONTEXT_ID2,
@@ -4383,7 +4601,7 @@ function buildBootstrapPayload(options) {
4383
4601
  }
4384
4602
 
4385
4603
  // src/client.ts
4386
- var MIN_SERVER_VERSION = "0.17.1";
4604
+ var MIN_SERVER_VERSION = "0.75.0";
4387
4605
  var MIN_SERVER_VERSION_TUPLE = MIN_SERVER_VERSION.split(".").slice(0, 3).map(Number);
4388
4606
  var KaguraClient = class _KaguraClient {
4389
4607
  mcpUrl;
@@ -4392,6 +4610,10 @@ var KaguraClient = class _KaguraClient {
4392
4610
  auth;
4393
4611
  fetchImpl;
4394
4612
  sessionId = null;
4613
+ /** The in-flight `initialize`, shared by every caller (see initializeSession). */
4614
+ sessionOpening = null;
4615
+ /** Bumped by close(), so a handshake it interrupted cannot re-adopt its session. */
4616
+ sessionEpoch = 0;
4395
4617
  requestIdCounter = 1;
4396
4618
  constructor(options = {}) {
4397
4619
  const resolved = resolveAuth({
@@ -4437,11 +4659,38 @@ var KaguraClient = class _KaguraClient {
4437
4659
  throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });
4438
4660
  }
4439
4661
  }
4440
- /** Initialize the MCP session if not already initialized. */
4662
+ /**
4663
+ * Initialize the MCP session if not already initialized, and return its id.
4664
+ *
4665
+ * Single-flight: calls that find no session at the same time (on first
4666
+ * use, or after all hitting one expired session) share one `initialize`
4667
+ * instead of each opening, and orphaning, a session of their own.
4668
+ *
4669
+ * Callers send the id returned here rather than re-reading `sessionId`:
4670
+ * a concurrent expired-session 404 can clear the field in the tick the
4671
+ * `await` yields, which would send the request with no session at all.
4672
+ */
4441
4673
  async initializeSession() {
4442
4674
  if (this.sessionId) {
4443
- return;
4675
+ return this.sessionId;
4444
4676
  }
4677
+ if (!this.sessionOpening) {
4678
+ const opening = this.openSession().finally(() => {
4679
+ if (this.sessionOpening === opening) {
4680
+ this.sessionOpening = null;
4681
+ }
4682
+ });
4683
+ this.sessionOpening = opening;
4684
+ }
4685
+ return this.sessionOpening;
4686
+ }
4687
+ /**
4688
+ * Run the `initialize` handshake and keep the session id it returns —
4689
+ * unless close() ran meanwhile, in which case the id serves only the
4690
+ * calls already waiting on it.
4691
+ */
4692
+ async openSession() {
4693
+ const epoch = this.sessionEpoch;
4445
4694
  const body = {
4446
4695
  jsonrpc: "2.0",
4447
4696
  id: this.nextRequestId(),
@@ -4460,7 +4709,10 @@ var KaguraClient = class _KaguraClient {
4460
4709
  if (!sessionId) {
4461
4710
  throw new KaguraConnectionError("No session ID returned from server");
4462
4711
  }
4463
- this.sessionId = sessionId;
4712
+ if (epoch === this.sessionEpoch) {
4713
+ this.sessionId = sessionId;
4714
+ }
4715
+ return sessionId;
4464
4716
  }
4465
4717
  async safeText(response) {
4466
4718
  try {
@@ -4469,18 +4721,42 @@ var KaguraClient = class _KaguraClient {
4469
4721
  return "";
4470
4722
  }
4471
4723
  }
4472
- /** Make a JSON-RPC 2.0 request to the MCP server. */
4724
+ /**
4725
+ * Make a JSON-RPC 2.0 request to the MCP server.
4726
+ *
4727
+ * MCP Streamable HTTP answers a request naming a session the server has
4728
+ * dropped (idle hour, restart) with a 404 and requires a new `initialize`;
4729
+ * without recovery a long-lived client would fail every call from then on
4730
+ * (#39). The session is re-opened and the request retried exactly once.
4731
+ * The server rejects it before dispatch, which makes that retry safe even
4732
+ * for a non-idempotent `tools/call`. (As deployed, server v0.75.0
4733
+ * re-adopts an unknown session id instead, so against it this never
4734
+ * fires.)
4735
+ */
4473
4736
  async makeJsonRpcRequest(method, params) {
4474
- await this.initializeSession();
4737
+ const sessionId = await this.initializeSession();
4475
4738
  const body = {
4476
4739
  jsonrpc: "2.0",
4477
4740
  id: this.nextRequestId(),
4478
4741
  method,
4479
4742
  params
4480
4743
  };
4481
- const headers = this.sessionId ? { "mcp-session-id": this.sessionId } : {};
4482
- const response = await this.post(this.mcpUrl, body, headers);
4483
- const text = await this.safeText(response);
4744
+ let response = await this.post(this.mcpUrl, body, mcpSessionHeader(sessionId));
4745
+ let text = await this.safeText(response);
4746
+ if (mcpSessionExpired(response.status, text, sessionId)) {
4747
+ if (this.sessionId === sessionId) {
4748
+ this.sessionId = null;
4749
+ }
4750
+ const retrySessionId = await this.initializeSession();
4751
+ response = await this.post(this.mcpUrl, body, mcpSessionHeader(retrySessionId));
4752
+ text = await this.safeText(response);
4753
+ if (mcpSessionExpired(response.status, text, retrySessionId)) {
4754
+ const detail = extractDetail(text);
4755
+ throw new KaguraConnectionError(
4756
+ "MCP session expired; the client re-initialized once and the retry still got " + (detail ? `HTTP 404: ${detail}` : "HTTP 404")
4757
+ );
4758
+ }
4759
+ }
4484
4760
  if (!response.ok) {
4485
4761
  throwForKaguraStatus(response.status, response.headers, text);
4486
4762
  }
@@ -4589,7 +4865,9 @@ var KaguraClient = class _KaguraClient {
4589
4865
  * recognizes get a specific class. A code from a tool with no wrapper
4590
4866
  * (`secret_not_found`, say) lands on the generic {@link KaguraError}, so
4591
4867
  * match on the message or add the code to `raiseForMcpError` when you
4592
- * confirm it against the server.
4868
+ * confirm it against the server. Plan and quota refusals are the
4869
+ * exception: a v0.75.0+ server tags them with a `gate`, so they get
4870
+ * {@link KaguraFeatureNotAvailableError} / {@link KaguraQuotaError} from any tool.
4593
4871
  *
4594
4872
  * Use `getToolDefinitions()` to discover what the connected server offers.
4595
4873
  *
@@ -4607,6 +4885,13 @@ var KaguraClient = class _KaguraClient {
4607
4885
  * The server's MCP tools return `{"status": "error", "error": <code>,
4608
4886
  * "message": <str>, ...}` for domain errors the JSON-RPC transport
4609
4887
  * cannot represent. HTTP-level errors are handled by the request layer.
4888
+ *
4889
+ * Classes are keyed on the code and the envelope's own fields, never on
4890
+ * the message, whose wording the server has changed before. Plan and
4891
+ * quota refusals go by the envelope's `gate` first (server v0.75.0+),
4892
+ * then by the code; their message stays the generic one, so matching on
4893
+ * it keeps working. A quota's `retry_after_seconds` (the resource
4894
+ * events-per-hour quota on `ingest_events`) becomes its `retryAfter`.
4610
4895
  */
4611
4896
  static raiseForMcpError(result, operation) {
4612
4897
  if (result.status !== "error") {
@@ -4617,7 +4902,32 @@ var KaguraClient = class _KaguraClient {
4617
4902
  if (code2 === "report_not_found" || code2 === "context_not_found" || code2 === "memory_not_found" || code2 === "agent_not_found" || code2 === "binding_not_found") {
4618
4903
  throw new KaguraNotFoundError(`${operation}: ${message}`);
4619
4904
  }
4620
- throw new KaguraError(`${operation} failed (${code2}): ${message}`);
4905
+ const failure = `${operation} failed (${code2}): ${message}`;
4906
+ const gated = gateError(
4907
+ result,
4908
+ code2,
4909
+ MCP_GATE_CODES,
4910
+ failure,
4911
+ bodyRetryAfter(result, "retry_after_seconds")
4912
+ );
4913
+ if (gated !== null) {
4914
+ throw gated;
4915
+ }
4916
+ if (code2 === "partial_rollback") {
4917
+ const summary = result.rollback_summary;
4918
+ throw new KaguraPartialRollbackError(
4919
+ failure,
4920
+ typeof result.report_id === "string" ? result.report_id : null,
4921
+ typeof summary === "object" && summary !== null && !Array.isArray(summary) ? summary : {}
4922
+ );
4923
+ }
4924
+ if (code2 === "permission_denied") {
4925
+ throw new KaguraPermissionError(
4926
+ failure,
4927
+ typeof result.required_role === "string" ? result.required_role : null
4928
+ );
4929
+ }
4930
+ throw new KaguraError(failure);
4621
4931
  }
4622
4932
  /** Store a memory. Returns the API response with `memory_id`. */
4623
4933
  async remember(options) {
@@ -4663,6 +4973,14 @@ var KaguraClient = class _KaguraClient {
4663
4973
  /**
4664
4974
  * Search memories. Returns the API response with a `results` list.
4665
4975
  *
4976
+ * When the semantic half of a hybrid search (the default `searchMode`)
4977
+ * is unavailable, server v0.66.0+ falls back to keyword-only search —
4978
+ * `searchMode: "semantic"` still fails — and adds `degraded: true` and
4979
+ * `degraded_reason` (`"embedding_unavailable"` or
4980
+ * `"vector_search_unavailable"`) instead of failing. Both keys are absent
4981
+ * on a normal search. A degraded result has a different `confidence`
4982
+ * basis, and an empty one means "search impaired", not "nothing stored".
4983
+ *
4666
4984
  * @throws Error if `query` is empty/whitespace; if neither `contextId`
4667
4985
  * nor `contextIds` is provided; if `contextIds` has fewer than 2 or
4668
4986
  * more than 20 IDs; or if `searchMode` is invalid.
@@ -4688,8 +5006,8 @@ var KaguraClient = class _KaguraClient {
4688
5006
  } else {
4689
5007
  args.context_id = contextId;
4690
5008
  }
4691
- if (options.useRerank) {
4692
- args.use_rerank = true;
5009
+ if (options.useRerank !== void 0) {
5010
+ args.use_rerank = options.useRerank;
4693
5011
  }
4694
5012
  if (options.filters && Object.keys(options.filters).length > 0) {
4695
5013
  args.filters = options.filters;
@@ -4712,6 +5030,11 @@ var KaguraClient = class _KaguraClient {
4712
5030
  * List Time Memories whose scheduled window overlaps a range, soonest
4713
5031
  * first. A deterministic time query over `type="time"` memories — not
4714
5032
  * semantic search, no Hebbian side-effects.
5033
+ *
5034
+ * Since server v0.73.0 each item carries `trigger` (the memory's
5035
+ * `details.trigger`) instead of the full `details` object, so
5036
+ * `item.details` is `undefined` by default. Pass `includeDetails: true`
5037
+ * to get `details` back, or call {@link reference} for one memory.
4715
5038
  */
4716
5039
  async recallUpcoming(options) {
4717
5040
  const args = {
@@ -4724,6 +5047,9 @@ var KaguraClient = class _KaguraClient {
4724
5047
  if (options.until !== void 0) {
4725
5048
  args.until = options.until;
4726
5049
  }
5050
+ if (options.includeDetails) {
5051
+ args.include_details = true;
5052
+ }
4727
5053
  return this.callToolChecked("recall_upcoming", args);
4728
5054
  }
4729
5055
  /**
@@ -4779,6 +5105,27 @@ var KaguraClient = class _KaguraClient {
4779
5105
  }
4780
5106
  return this.callToolChecked("load_pinned", args);
4781
5107
  }
5108
+ /**
5109
+ * Deterministically load a context's guardrail set for a client-side
5110
+ * hook — {@link loadPinned}'s twin (server v0.74.0+).
5111
+ *
5112
+ * Two lanes, each capped on its own: `pinned` (`delivery_mode="always"`)
5113
+ * and `tool_triggered`, every memory carrying `details.tool_trigger`
5114
+ * ({@link ToolTrigger}). `cap` bounds the tool-triggered lane only, so a
5115
+ * large pinned set never crowds guardrails out. Trusted-tier rows only;
5116
+ * the patterns come back as data — the server never runs them.
5117
+ *
5118
+ * Never silently dropped: check `tool_triggered_truncated` /
5119
+ * `pinned_truncated` before treating the set as complete.
5120
+ */
5121
+ async loadGuardrails(options) {
5122
+ const args = { context_id: options.contextId };
5123
+ if (options.cap !== void 0) {
5124
+ args.cap = options.cap;
5125
+ }
5126
+ const result = await this.callToolChecked("load_guardrails", args);
5127
+ return result;
5128
+ }
4782
5129
  /**
4783
5130
  * Record whether a recalled memory was useful for a query — an
4784
5131
  * append-only usefulness signal, kept in a separate lane from knowledge
@@ -4856,8 +5203,8 @@ var KaguraClient = class _KaguraClient {
4856
5203
  * `enforcement_mode="enforce"`.
4857
5204
  *
4858
5205
  * Requires memory-cloud v0.49.0+ — older servers return an MCP
4859
- * "tool not found" error ({@link MIN_SERVER_VERSION} is deliberately
4860
- * not bumped; only the agent control plane needs the newer server).
5206
+ * "tool not found" error. That predates {@link MIN_SERVER_VERSION}, so
5207
+ * any server {@link checkServerVersion} does not warn about has it.
4861
5208
  *
4862
5209
  * @throws KaguraError on name conflict, agent quota, or insufficient
4863
5210
  * role (owner/admin required).
@@ -4959,9 +5306,9 @@ var KaguraClient = class _KaguraClient {
4959
5306
  /**
4960
5307
  * Build the omit-when-undefined binding scope trio shared by
4961
5308
  * {@link bindAgentContext} and {@link updateAgentBinding} — the port of
4962
- * the Python SDK's `_binding_scope_payload`. When memory-cloud #1286
4963
- * ships the reserved filters, extend {@link AgentBindingScopeOptions}
4964
- * and map the new fields here.
5309
+ * the Python SDK's `_binding_scope_payload`. To expose the per-memory
5310
+ * filters (server v0.51.0+), extend {@link AgentBindingScopeOptions} and
5311
+ * map the new fields here.
4965
5312
  */
4966
5313
  static bindingScopeArgs(options) {
4967
5314
  const args = {};
@@ -5055,7 +5402,10 @@ var KaguraClient = class _KaguraClient {
5055
5402
  * Components are **fail-soft**: a failing component reports
5056
5403
  * `{"status": "error", ...}` under `components` while the rest still
5057
5404
  * return, with the top-level `degraded` flag set. Identity and
5058
- * authorization failures are total and throw instead.
5405
+ * authorization failures are total and throw instead. A keyword-only
5406
+ * recall (see {@link recall}) sets the top-level flag too (server
5407
+ * v0.66.0+), along with `components.recall.degraded`; its
5408
+ * `degraded_reason` tells an impaired recall from a failed component.
5059
5409
  *
5060
5410
  * The REST companion (`POST /api/v1/agents/{agent_id}/bootstrap`) is
5061
5411
  * available via `AgentsClient` for API-key-only callers such as
@@ -5073,9 +5423,35 @@ var KaguraClient = class _KaguraClient {
5073
5423
  });
5074
5424
  return result;
5075
5425
  }
5076
- /** List available contexts. */
5077
- async listContexts() {
5078
- return this.callToolChecked("list_contexts", {});
5426
+ /**
5427
+ * List the contexts the caller can see, most recently used first.
5428
+ *
5429
+ * Since server v0.73.0 this is a slim name→id directory: each item is
5430
+ * `{id, name, is_private, is_locked, last_used_at}` and carries no
5431
+ * `summary` or `embedding_model` unless asked for. Narrow a large
5432
+ * workspace with `listContexts({ nameContains, includeDetails: true })`,
5433
+ * or read one context in full with {@link getContextInfo}.
5434
+ *
5435
+ * `count` is workspace quota usage, not the number returned — that is
5436
+ * `total`. When the caller can see no context at all, `hint` says how
5437
+ * to create one or get access.
5438
+ */
5439
+ async listContexts(options = {}) {
5440
+ const args = {};
5441
+ if (options.nameContains !== void 0) {
5442
+ args.name_contains = options.nameContains;
5443
+ }
5444
+ if (options.includeSummary) {
5445
+ args.include_summary = true;
5446
+ }
5447
+ if (options.includeDetails) {
5448
+ args.include_details = true;
5449
+ }
5450
+ if (options.includeStats) {
5451
+ args.include_stats = true;
5452
+ }
5453
+ const result = await this.callToolChecked("list_contexts", args);
5454
+ return result;
5079
5455
  }
5080
5456
  /**
5081
5457
  * List the tag vocabulary in a context with usage counts and recency.
@@ -5142,7 +5518,11 @@ var KaguraClient = class _KaguraClient {
5142
5518
  * Update an existing memory in-place (memoryId) or upsert by external
5143
5519
  * ID (externalId — requires summary, content, and type).
5144
5520
  *
5145
- * @throws Error unless exactly one of memoryId/externalId is provided.
5521
+ * Reject a `supersede_candidate` the server suggested with
5522
+ * `updateMemory({ memoryId, dismissSupersedeCandidate: true })`.
5523
+ *
5524
+ * @throws Error unless exactly one of memoryId/externalId is provided,
5525
+ * or if `dismissSupersedeCandidate` is combined with `externalId`.
5146
5526
  */
5147
5527
  async updateMemory(options) {
5148
5528
  if (!options.memoryId && !options.externalId) {
@@ -5151,6 +5531,11 @@ var KaguraClient = class _KaguraClient {
5151
5531
  if (options.memoryId && options.externalId) {
5152
5532
  throw new Error("Provide exactly one of memoryId or externalId");
5153
5533
  }
5534
+ if (options.dismissSupersedeCandidate && options.externalId !== void 0) {
5535
+ throw new Error(
5536
+ "dismissSupersedeCandidate requires memoryId; an externalId upsert replaces the memory and its suggestion"
5537
+ );
5538
+ }
5154
5539
  const args = { context_id: options.contextId };
5155
5540
  if (options.memoryId !== void 0) {
5156
5541
  args.memory_id = options.memoryId;
@@ -5182,12 +5567,30 @@ var KaguraClient = class _KaguraClient {
5182
5567
  if (options.deliveryMode !== void 0) {
5183
5568
  args.delivery_mode = options.deliveryMode;
5184
5569
  }
5570
+ if (options.dismissSupersedeCandidate) {
5571
+ args.dismiss_supersede_candidate = true;
5572
+ }
5185
5573
  return this.callToolChecked("update_memory", args);
5186
5574
  }
5187
5575
  /**
5188
- * Soft-delete memories (30-day retention) by specific memoryId or by
5189
- * search query.
5576
+ * Soft-delete memories by specific memoryId or by search query. The
5577
+ * rows are kept, but not restorable through the API, until the
5578
+ * deployment's cleanup window passes
5579
+ * (`CLEANUP_DELETED_MEMORIES_RETENTION_DAYS`, default 30 days; Sleep
5580
+ * retention can purge sooner, and `0` turns the sweep off).
5581
+ *
5582
+ * The silent skip is per target, for a caller who may write to the
5583
+ * workspace: a target that caller may not delete, or one already gone,
5584
+ * is skipped rather than refused. Since server v0.74.0 that includes
5585
+ * every tool guardrail when the caller is below context editor or on an
5586
+ * agent credential. Check `deleted_count`, which can be 0 even for an
5587
+ * explicit `memoryId`.
5588
+ *
5589
+ * A caller who may not write to the workspace at all is refused before
5590
+ * any target is looked at, so nothing is skipped silently for it.
5190
5591
  *
5592
+ * @throws KaguraPermissionError for a workspace viewer, which has
5593
+ * read-only access (`requiredRole: "member"`).
5191
5594
  * @throws Error if neither memoryId nor query is provided.
5192
5595
  */
5193
5596
  async forget(options) {
@@ -5207,16 +5610,35 @@ var KaguraClient = class _KaguraClient {
5207
5610
  /**
5208
5611
  * Create a new context in the current workspace.
5209
5612
  *
5613
+ * Checks the workspace's context limit first, with {@link listContexts},
5614
+ * and throws without calling `create_context` when `can_create` is false
5615
+ * — unless `limit` is 0, which is how the server reports that it could
5616
+ * not read the quota; `create_context` then decides.
5617
+ * That error comes from the SDK, not the server: it carries
5618
+ * `quotaType: "contexts"` with `current` / `limit`, but `gate` and the
5619
+ * plan fields stay `null` because `list_contexts` does not send them. A
5620
+ * `null` `requiredPlan` there means the plan is unknown, not that no plan
5621
+ * lifts the cap. The server's own refusal, which names the plan that
5622
+ * lifts it, only arrives when a concurrent create gets past the check.
5623
+ *
5210
5624
  * @throws KaguraQuotaError when the workspace context limit is reached.
5625
+ * @throws KaguraFeatureNotAvailableError for a shared context (`isPrivate: false`) on a
5626
+ * plan without `shared_contexts` (server v0.75.0+).
5211
5627
  */
5212
5628
  async createContext(options) {
5213
5629
  const contexts = await this.listContexts();
5214
5630
  const canCreate = "can_create" in contexts ? contexts.can_create : true;
5215
- if (!canCreate) {
5631
+ if (!canCreate && contexts.limit !== 0) {
5216
5632
  const count = contexts.count ?? null;
5217
5633
  const limit = contexts.limit ?? null;
5218
5634
  throw new KaguraQuotaError(
5219
- `Context limit reached (${count === null ? "?" : String(count)}/${limit === null ? "?" : String(limit)}). Delete unused contexts or upgrade your plan.`
5635
+ `Context limit reached (${count === null ? "?" : String(count)}/${limit === null ? "?" : String(limit)}). Delete unused contexts or upgrade your plan.`,
5636
+ null,
5637
+ {
5638
+ quotaType: "contexts",
5639
+ current: typeof count === "number" ? count : null,
5640
+ limit: typeof limit === "number" ? limit : null
5641
+ }
5220
5642
  );
5221
5643
  }
5222
5644
  const args = {
@@ -5277,6 +5699,13 @@ var KaguraClient = class _KaguraClient {
5277
5699
  * Atomically create Context + Resource entity + ingestion token in a
5278
5700
  * single server-side transaction. The returned `token` is plaintext and
5279
5701
  * shown once.
5702
+ *
5703
+ * Plan-gated on the `resources` feature (server v0.68.0+): a plan
5704
+ * without it is refused with nothing created.
5705
+ *
5706
+ * @throws KaguraFeatureNotAvailableError when the plan lacks `resources`;
5707
+ * `requiredPlanDisplay` names the plan that has it.
5708
+ * @throws KaguraQuotaError at the workspace's context or token cap.
5280
5709
  */
5281
5710
  async setupResource(options) {
5282
5711
  const args = {
@@ -5404,8 +5833,20 @@ var KaguraClient = class _KaguraClient {
5404
5833
  return result;
5405
5834
  }
5406
5835
  /**
5407
- * Update hybrid search configuration for a context. Weights must sum
5408
- * to 1.0 (±0.01). Requires owner or editor permission.
5836
+ * Update a context's search configuration: hybrid weights, reranker,
5837
+ * reinforce re-rank, and query routing. Weights must sum to 1.0
5838
+ * (±0.01). Requires owner or editor permission. Omitted fields keep
5839
+ * their current values.
5840
+ *
5841
+ * The result echoes the whole configuration after the update under
5842
+ * `config`. That is the only place the reinforce and routing fields
5843
+ * come back: {@link getContextInfo}'s `search_config` leaves them out.
5844
+ *
5845
+ * @throws KaguraPermissionError when the caller may not write to the
5846
+ * context, and also when the context does not exist or the caller
5847
+ * cannot see it: the server answers every access failure here with
5848
+ * `permission_denied`, never `context_not_found`, and sends no
5849
+ * `required_role`, so `requiredRole` is `null` whatever the cause.
5409
5850
  */
5410
5851
  async updateSearchConfig(options) {
5411
5852
  const args = { context_id: options.contextId };
@@ -5427,9 +5868,25 @@ var KaguraClient = class _KaguraClient {
5427
5868
  if (options.rerankerModel !== void 0) {
5428
5869
  args.reranker_model = options.rerankerModel;
5429
5870
  }
5430
- return this.callToolChecked("update_search_config", args);
5871
+ if (options.reinforceEnabled !== void 0) {
5872
+ args.reinforce_enabled = options.reinforceEnabled;
5873
+ }
5874
+ if (options.reinforceMaxBoost !== void 0) {
5875
+ args.reinforce_max_boost = options.reinforceMaxBoost;
5876
+ }
5877
+ if (options.reinforceRequireHostArbitration !== void 0) {
5878
+ args.reinforce_require_host_arbitration = options.reinforceRequireHostArbitration;
5879
+ }
5880
+ if (options.routingMode !== void 0) {
5881
+ args.routing_mode = options.routingMode;
5882
+ }
5883
+ const result = await this.callToolChecked("update_search_config", args);
5884
+ return result;
5431
5885
  }
5432
- /** Get server name, version, environment, and feature flags. */
5886
+ /**
5887
+ * Get server name, version, environment, feature flags, and (server
5888
+ * v0.69.0+) the reranker defaults new contexts start with.
5889
+ */
5433
5890
  async getServerInfo() {
5434
5891
  return this.restGet("/api/v1/system/info");
5435
5892
  }
@@ -5468,7 +5925,7 @@ var KaguraClient = class _KaguraClient {
5468
5925
  return this.restGet(
5469
5926
  `/api/v1/contexts/${options.contextId}/memory-stats`,
5470
5927
  {
5471
- sort_by: options.sortBy ?? "use_count",
5928
+ sort_by: options.sortBy ?? "access_count",
5472
5929
  sort_order: options.sortOrder ?? "desc",
5473
5930
  limit: options.limit ?? 50,
5474
5931
  offset: options.offset ?? 0
@@ -5550,9 +6007,26 @@ var KaguraClient = class _KaguraClient {
5550
6007
  };
5551
6008
  }
5552
6009
  /**
5553
- * Reverse the effects of a completed Sleep Maintenance run. The server
5554
- * processes actions in reverse order with per-step commits — a partial
5555
- * failure means SOME actions may have been reversed before the error.
6010
+ * Reverse the effects of a `completed` or `degraded` Sleep Maintenance
6011
+ * run; any other status is refused. The server processes actions in
6012
+ * reverse order with per-step commits — a partial failure means SOME
6013
+ * actions may have been reversed before the error.
6014
+ *
6015
+ * A partial rollback throws {@link KaguraPartialRollbackError} rather
6016
+ * than returning, and its `summary` is the {@link RollbackSummary} a
6017
+ * clean run would have returned: the counts say what was reversed, and
6018
+ * `summary.errors` names each action that was not (a merge a later write
6019
+ * changed is counted in `merges_unreversible` and listed there too). The
6020
+ * reversed steps stay committed and the report is marked `failed`.
6021
+ *
6022
+ * There is no retry: the server rolls back only a `completed` or
6023
+ * `degraded` report, so calling this again on a `failed` one is refused
6024
+ * with a plain {@link KaguraError} (`invalid_status`). The actions in
6025
+ * `err.summary.errors` stay unreversed and need handling some other way.
6026
+ *
6027
+ * @throws KaguraPartialRollbackError when some actions could not be
6028
+ * reversed.
6029
+ * @throws KaguraNotFoundError when the report or context does not exist.
5556
6030
  */
5557
6031
  async rollbackSleepRun(options) {
5558
6032
  const result = await this.callToolChecked("rollback_sleep_run", {
@@ -5567,7 +6041,9 @@ var KaguraClient = class _KaguraClient {
5567
6041
  }
5568
6042
  /** Release resources. (fetch has no persistent connection to close; kept for API parity.) */
5569
6043
  async close() {
6044
+ this.sessionEpoch++;
5570
6045
  this.sessionId = null;
6046
+ this.sessionOpening = null;
5571
6047
  }
5572
6048
  };
5573
6049
 
@@ -5639,7 +6115,8 @@ var KaguraRestClient = class {
5639
6115
  * Precedence: explicit `apiKey` > `KAGURA_API_KEY` env > OAuth profile
5640
6116
  * from `~/.kagura/credentials.json` > `.kagura.json`. The REST
5641
6117
  * `baseUrl` is derived from the resolved MCP URL (strips `/mcp` and any
5642
- * `/mcp/w/{workspaceId}` suffix); a static key bakes the Bearer header
6118
+ * `/mcp/w/{workspaceId}` suffix, and drops any query such as
6119
+ * `?profile=core`); a static key bakes the Bearer header
5643
6120
  * once, an OAuth profile installs an auto-refreshing `AuthProvider`.
5644
6121
  *
5645
6122
  * Declared with a polymorphic `this` so every subclass inherits a
@@ -5797,17 +6274,63 @@ var KaguraRestClient = class {
5797
6274
  return new KaguraAuthError(`Authentication failed. ${hint}`);
5798
6275
  }
5799
6276
  /**
5800
- * 403 → generic mapping by default; clients with a richer story
5801
- * (workspace hints, secret existence-hiding) override this.
6277
+ * 403 → a plan or quota refusal's typed error, else the generic
6278
+ * mapping; clients with a richer story (workspace hints, secret
6279
+ * existence-hiding) override this, asking {@link gateRefusal} first.
5802
6280
  */
5803
6281
  error403(response, context) {
5804
- return this.genericError(response);
6282
+ return this.gateRefusal(response) ?? this.genericError(response);
5805
6283
  }
5806
- /** 429 → quota error with a tolerant `Retry-After` parse. */
6284
+ /**
6285
+ * 429 → quota error with a tolerant `Retry-After` parse, falling back to
6286
+ * the body's `details.retry_after` when there is no header. A typed
6287
+ * refusal (the member seat cap, a daily quota) keeps the server's
6288
+ * message and adds its gate payload. A `RATE-001` body (the resource
6289
+ * events-per-hour quota, which sends its retry hint only in the body)
6290
+ * keeps the server's message too, scrubbed of credential markers; any
6291
+ * other 429 gets the fixed text. A 429 stays a {@link KaguraQuotaError}
6292
+ * even when its body reads as a plan refusal.
6293
+ */
5807
6294
  error429(response) {
6295
+ const gated = this.gateRefusal(response);
6296
+ if (gated instanceof KaguraQuotaError) {
6297
+ return gated;
6298
+ }
6299
+ const serverMessage = parseErrorEnvelope(response.text)?.code === "RATE-001" ? sanitizeServerDetail(extractDetail(response.text)) : null;
5808
6300
  return new KaguraQuotaError(
5809
- "Quota exceeded. Try again later.",
5810
- retryAfterSeconds(response.headers)
6301
+ serverMessage ?? "Quota exceeded. Try again later.",
6302
+ responseRetryAfter(response.headers, response.text)
6303
+ );
6304
+ }
6305
+ /**
6306
+ * A plan or quota refusal → its typed error; `null` for any other body.
6307
+ *
6308
+ * memory-cloud v0.75.0 annotates every such refusal with `details.gate`,
6309
+ * and the class follows the gate rather than the status: the
6310
+ * resource-token cap is a quota that answers 403. An older server sends
6311
+ * no gate, so the `FEAT-001` / `QUOTA-001` / `QUOTA-002` /
6312
+ * `CONNECTOR-001` code decides. A body that is neither (a role denial, a
6313
+ * pre-v0.75 `HTTP-403` plan message) gets `null`, and the hook maps it
6314
+ * as it always did.
6315
+ *
6316
+ * Every 403 hook, the subclass overrides included, asks this first, so
6317
+ * a plan refusal never reads as a credential problem; so does every 429
6318
+ * hook but SecretClient's, which keeps 429 generic by design, and a 429
6319
+ * hook keeps only a {@link KaguraQuotaError}. The message is the
6320
+ * server's own, scrubbed of credential markers: it names the feature or
6321
+ * cap and the plan that lifts it.
6322
+ */
6323
+ gateRefusal(response) {
6324
+ const envelope = parseErrorEnvelope(response.text);
6325
+ if (envelope === null) {
6326
+ return null;
6327
+ }
6328
+ return gateError(
6329
+ envelope.details,
6330
+ envelope.code,
6331
+ REST_GATE_CODES,
6332
+ sanitizeServerDetail(extractDetail(response.text)) ?? `HTTP ${response.status}`,
6333
+ responseRetryAfter(response.headers, response.text)
5811
6334
  );
5812
6335
  }
5813
6336
  /** Any other status → `HTTP <status>: <detail>` connection error. */
@@ -6031,9 +6554,10 @@ var FilesClient = class extends KaguraRestClient {
6031
6554
  /**
6032
6555
  * 403 → a workspace-mismatch hint (issue #115): surface the credential
6033
6556
  * source and requested workspace prefix without leaking the api_key.
6557
+ * A plan or quota refusal is typed first — no workspace is wrong there.
6034
6558
  */
6035
6559
  error403(response, context) {
6036
- return new KaguraConnectionError(
6560
+ return this.gateRefusal(response) ?? new KaguraConnectionError(
6037
6561
  formatWorkspace403Hint({
6038
6562
  authSource: this.authSource,
6039
6563
  sourceWorkspaceHint: this.workspaceIdHint,
@@ -6215,6 +6739,10 @@ var ResourceClient = class extends KaguraRestClient {
6215
6739
  * Create a new resource token.
6216
6740
  *
6217
6741
  * @returns Created token including plaintext token (shown only once).
6742
+ * @throws KaguraFeatureNotAvailableError when the plan lacks the `resources` feature.
6743
+ * @throws KaguraQuotaError at the plan's active-token cap — a 403, not a
6744
+ * 429; `limit` is the cap. Revoke a token or upgrade. Server v0.75.0+;
6745
+ * older servers answer 403 `HTTP-403`, a KaguraConnectionError.
6218
6746
  */
6219
6747
  async createToken(options) {
6220
6748
  const body = { resource_id: options.resourceId };
@@ -6287,6 +6815,9 @@ var ResourceClient = class extends KaguraRestClient {
6287
6815
  * {@link SETUP_OAUTH_NOT_SUPPORTED_MSG}).
6288
6816
  * @throws KaguraAuthError if the Authorization header is missing or
6289
6817
  * malformed in the static path.
6818
+ * @throws KaguraFeatureNotAvailableError when the plan lacks the `resources` feature,
6819
+ * and KaguraQuotaError at the context or token cap — see
6820
+ * `KaguraClient.setupResource`.
6290
6821
  *
6291
6822
  * Note: Idempotency for repeated calls with the same `resourceId` is
6292
6823
  * not guaranteed; server-side behavior may evolve. Avoid retrying
@@ -6472,9 +7003,14 @@ var SecretClient = class extends KaguraRestClient {
6472
7003
  * The server answers 403, not 404, for a secret the caller may not read,
6473
7004
  * so that the response does not reveal whether the secret exists. That
6474
7005
  * means a 403 here has three possible causes and the message has to name
6475
- * all of them rather than guess.
7006
+ * all of them rather than guess. A plan or quota refusal is none of the
7007
+ * three, so it gets its typed error instead.
6476
7008
  */
6477
7009
  error403(response, _context) {
7010
+ const gated = this.gateRefusal(response);
7011
+ if (gated !== null) {
7012
+ return gated;
7013
+ }
6478
7014
  const detail = extractDetail(response.text);
6479
7015
  const base = "Access denied (HTTP 403): you may not have a grant on this secret, it may not exist, or you lack permission for this operation.";
6480
7016
  return new KaguraConnectionError(detail ? `${base} (${detail})` : base);
@@ -6485,7 +7021,9 @@ var SecretClient = class extends KaguraRestClient {
6485
7021
  * Deliberate divergence from the base class, preserved from the Python
6486
7022
  * port: the secret surface has always rendered 429 through the generic
6487
7023
  * branch, and changing it would silently reclassify errors for existing
6488
- * callers on a file both SDKs share.
7024
+ * callers on a file both SDKs share. That holds for a 429 carrying a
7025
+ * quota gate too (the daily REST quota covers this surface): the
7026
+ * divergence is about the status, and the gate does not override it.
6489
7027
  */
6490
7028
  error429(response) {
6491
7029
  return this.genericError(response);