kagura-memory 0.8.0 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -265,7 +265,7 @@ snake_case; optional fields are omitted from the request when `undefined`.
265
265
  | Method | What it does |
266
266
  |--------|--------------|
267
267
  | `remember` | Store a memory. `details` accepts arbitrary JSON (including `location`, see below); `supersedes` declares this the newer version of an existing memory, shadowing the old one from default recall without destroying it; `deliveryMode: "always"` pins it. |
268
- | `recall` | Hybrid semantic + keyword search. Takes `filters` (`type`, `tags`, `tags_match`, date bounds, `trust_tier`), `searchMode`, `useRerank`, `includeExploreHints`, `includeSuperseded` (read back what `supersedes` shadowed, annotated with `superseded_by`), and `contextIds` for 2–20-context search. |
268
+ | `recall` | Hybrid semantic + keyword search. Takes `filters` (`type`, `tags`, `tags_match`, date bounds, `trust_tier`), `searchMode`, `useRerank`, `includeExploreHints`, `includeSuperseded` (read back what `supersedes` shadowed, annotated with `superseded_by`), and `contextIds` for 2–20-context search. `useRerank` is tri-state (memory-cloud v0.69.0+): omit it to follow the context's search config (the first context's, with `contextIds`), `true` requests reranking where the context allows it, `false` skips it for the call. |
269
269
  | `reference` | Full detail for one memory, under `result.memory`. |
270
270
  | `updateMemory` | Update in place by `memoryId`, or upsert by `externalId`. `details` **replaces** the stored object wholesale — round-trip keys you want to keep. |
271
271
  | `forget` | Soft-delete (30-day retention) by `memoryId` or by `query`. |
@@ -303,7 +303,7 @@ the counterpart to `recall`'s probabilistic search.
303
303
  | `updateContext` | Change display name, summary, usage guide, visibility, lock. |
304
304
  | `deleteContext` | Delete by id. Locked contexts are refused. |
305
305
  | `mergeContexts` | Move memories between contexts. Both must share an embedding model and workspace. |
306
- | `updateSearchConfig` | Hybrid-search weights (must sum to 1.0 ±0.01). Owner/editor only. |
306
+ | `updateSearchConfig` | Hybrid-search weights (must sum to 1.0 ±0.01) and reranking; the `useRerank` set here is what a `recall` that omits it follows. Owner/editor only. |
307
307
  | `setupResource` | Context + resource entity + ingestion token in one transaction. The returned token is plaintext and shown once. |
308
308
 
309
309
  ### Agent run-state
package/dist/cli.js CHANGED
@@ -57,12 +57,16 @@ var KaguraCryptoError = class extends KaguraSecretError {
57
57
  };
58
58
 
59
59
  // src/version.ts
60
- var SDK_VERSION = "0.8.0";
60
+ var SDK_VERSION = "0.8.1";
61
61
 
62
62
  // src/http.ts
63
63
  function baseUrlFromMcp(mcpUrl) {
64
- const m = /\/mcp(?=\/|$)/.exec(mcpUrl);
65
- return m ? mcpUrl.slice(0, m.index) : mcpUrl;
64
+ const end = mcpUrl.search(/[?#]/);
65
+ const path8 = end === -1 ? mcpUrl : mcpUrl.slice(0, end).replace(/\/+$/, "");
66
+ const authority = /^[a-z][a-z0-9+.-]*:\/\/[^/]*/i.exec(path8);
67
+ const from = authority ? authority[0].length : 0;
68
+ const m = /\/mcp(?=\/|$)/.exec(path8.slice(from));
69
+ return m ? path8.slice(0, from + m.index) : path8;
66
70
  }
67
71
  function formatValidationErrors(errors) {
68
72
  const parts = [];
@@ -84,6 +88,13 @@ function formatValidationErrors(errors) {
84
88
  }
85
89
  return parts.join("; ");
86
90
  }
91
+ function jsonRpcError(body) {
92
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
93
+ return null;
94
+ }
95
+ const error = body.error;
96
+ return typeof error === "object" && error !== null && !Array.isArray(error) ? error : null;
97
+ }
87
98
  function extractDetail(bodyText) {
88
99
  let body;
89
100
  try {
@@ -116,8 +127,28 @@ function extractDetail(bodyText) {
116
127
  }
117
128
  return message;
118
129
  }
130
+ const rpcMessage = jsonRpcError(rec)?.message;
131
+ if (typeof rpcMessage === "string" && rpcMessage) {
132
+ return rpcMessage;
133
+ }
119
134
  return "";
120
135
  }
136
+ function mcpSessionHeader(sessionId) {
137
+ return sessionId ? { "mcp-session-id": sessionId } : {};
138
+ }
139
+ var JSONRPC_METHOD_NOT_FOUND = -32601;
140
+ function mcpSessionExpired(status, bodyText, sessionId) {
141
+ if (!sessionId || status !== 404) {
142
+ return false;
143
+ }
144
+ let body;
145
+ try {
146
+ body = JSON.parse(bodyText);
147
+ } catch {
148
+ return true;
149
+ }
150
+ return jsonRpcError(body)?.code !== JSONRPC_METHOD_NOT_FOUND;
151
+ }
121
152
  function sanitizeServerDetail(detail) {
122
153
  if (!detail) {
123
154
  return null;
@@ -4392,6 +4423,10 @@ var KaguraClient = class _KaguraClient {
4392
4423
  auth;
4393
4424
  fetchImpl;
4394
4425
  sessionId = null;
4426
+ /** The in-flight `initialize`, shared by every caller (see initializeSession). */
4427
+ sessionOpening = null;
4428
+ /** Bumped by close(), so a handshake it interrupted cannot re-adopt its session. */
4429
+ sessionEpoch = 0;
4395
4430
  requestIdCounter = 1;
4396
4431
  constructor(options = {}) {
4397
4432
  const resolved = resolveAuth({
@@ -4437,11 +4472,38 @@ var KaguraClient = class _KaguraClient {
4437
4472
  throw new KaguraConnectionError(`Connection failed: ${excMessage(e)}`, { cause: e });
4438
4473
  }
4439
4474
  }
4440
- /** Initialize the MCP session if not already initialized. */
4475
+ /**
4476
+ * Initialize the MCP session if not already initialized, and return its id.
4477
+ *
4478
+ * Single-flight: calls that find no session at the same time (on first
4479
+ * use, or after all hitting one expired session) share one `initialize`
4480
+ * instead of each opening, and orphaning, a session of their own.
4481
+ *
4482
+ * Callers send the id returned here rather than re-reading `sessionId`:
4483
+ * a concurrent expired-session 404 can clear the field in the tick the
4484
+ * `await` yields, which would send the request with no session at all.
4485
+ */
4441
4486
  async initializeSession() {
4442
4487
  if (this.sessionId) {
4443
- return;
4488
+ return this.sessionId;
4444
4489
  }
4490
+ if (!this.sessionOpening) {
4491
+ const opening = this.openSession().finally(() => {
4492
+ if (this.sessionOpening === opening) {
4493
+ this.sessionOpening = null;
4494
+ }
4495
+ });
4496
+ this.sessionOpening = opening;
4497
+ }
4498
+ return this.sessionOpening;
4499
+ }
4500
+ /**
4501
+ * Run the `initialize` handshake and keep the session id it returns —
4502
+ * unless close() ran meanwhile, in which case the id serves only the
4503
+ * calls already waiting on it.
4504
+ */
4505
+ async openSession() {
4506
+ const epoch = this.sessionEpoch;
4445
4507
  const body = {
4446
4508
  jsonrpc: "2.0",
4447
4509
  id: this.nextRequestId(),
@@ -4460,7 +4522,10 @@ var KaguraClient = class _KaguraClient {
4460
4522
  if (!sessionId) {
4461
4523
  throw new KaguraConnectionError("No session ID returned from server");
4462
4524
  }
4463
- this.sessionId = sessionId;
4525
+ if (epoch === this.sessionEpoch) {
4526
+ this.sessionId = sessionId;
4527
+ }
4528
+ return sessionId;
4464
4529
  }
4465
4530
  async safeText(response) {
4466
4531
  try {
@@ -4469,18 +4534,42 @@ var KaguraClient = class _KaguraClient {
4469
4534
  return "";
4470
4535
  }
4471
4536
  }
4472
- /** Make a JSON-RPC 2.0 request to the MCP server. */
4537
+ /**
4538
+ * Make a JSON-RPC 2.0 request to the MCP server.
4539
+ *
4540
+ * MCP Streamable HTTP answers a request naming a session the server has
4541
+ * dropped (idle hour, restart) with a 404 and requires a new `initialize`;
4542
+ * without recovery a long-lived client would fail every call from then on
4543
+ * (#39). The session is re-opened and the request retried exactly once.
4544
+ * The server rejects it before dispatch, which makes that retry safe even
4545
+ * for a non-idempotent `tools/call`. (As deployed, server v0.75.0
4546
+ * re-adopts an unknown session id instead, so against it this never
4547
+ * fires.)
4548
+ */
4473
4549
  async makeJsonRpcRequest(method, params) {
4474
- await this.initializeSession();
4550
+ const sessionId = await this.initializeSession();
4475
4551
  const body = {
4476
4552
  jsonrpc: "2.0",
4477
4553
  id: this.nextRequestId(),
4478
4554
  method,
4479
4555
  params
4480
4556
  };
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);
4557
+ let response = await this.post(this.mcpUrl, body, mcpSessionHeader(sessionId));
4558
+ let text = await this.safeText(response);
4559
+ if (mcpSessionExpired(response.status, text, sessionId)) {
4560
+ if (this.sessionId === sessionId) {
4561
+ this.sessionId = null;
4562
+ }
4563
+ const retrySessionId = await this.initializeSession();
4564
+ response = await this.post(this.mcpUrl, body, mcpSessionHeader(retrySessionId));
4565
+ text = await this.safeText(response);
4566
+ if (mcpSessionExpired(response.status, text, retrySessionId)) {
4567
+ const detail = extractDetail(text);
4568
+ throw new KaguraConnectionError(
4569
+ "MCP session expired; the client re-initialized once and the retry still got " + (detail ? `HTTP 404: ${detail}` : "HTTP 404")
4570
+ );
4571
+ }
4572
+ }
4484
4573
  if (!response.ok) {
4485
4574
  throwForKaguraStatus(response.status, response.headers, text);
4486
4575
  }
@@ -4688,8 +4777,8 @@ var KaguraClient = class _KaguraClient {
4688
4777
  } else {
4689
4778
  args.context_id = contextId;
4690
4779
  }
4691
- if (options.useRerank) {
4692
- args.use_rerank = true;
4780
+ if (options.useRerank !== void 0) {
4781
+ args.use_rerank = options.useRerank;
4693
4782
  }
4694
4783
  if (options.filters && Object.keys(options.filters).length > 0) {
4695
4784
  args.filters = options.filters;
@@ -5468,7 +5557,7 @@ var KaguraClient = class _KaguraClient {
5468
5557
  return this.restGet(
5469
5558
  `/api/v1/contexts/${options.contextId}/memory-stats`,
5470
5559
  {
5471
- sort_by: options.sortBy ?? "use_count",
5560
+ sort_by: options.sortBy ?? "access_count",
5472
5561
  sort_order: options.sortOrder ?? "desc",
5473
5562
  limit: options.limit ?? 50,
5474
5563
  offset: options.offset ?? 0
@@ -5567,7 +5656,9 @@ var KaguraClient = class _KaguraClient {
5567
5656
  }
5568
5657
  /** Release resources. (fetch has no persistent connection to close; kept for API parity.) */
5569
5658
  async close() {
5659
+ this.sessionEpoch++;
5570
5660
  this.sessionId = null;
5661
+ this.sessionOpening = null;
5571
5662
  }
5572
5663
  };
5573
5664
 
@@ -5639,7 +5730,8 @@ var KaguraRestClient = class {
5639
5730
  * Precedence: explicit `apiKey` > `KAGURA_API_KEY` env > OAuth profile
5640
5731
  * from `~/.kagura/credentials.json` > `.kagura.json`. The REST
5641
5732
  * `baseUrl` is derived from the resolved MCP URL (strips `/mcp` and any
5642
- * `/mcp/w/{workspaceId}` suffix); a static key bakes the Bearer header
5733
+ * `/mcp/w/{workspaceId}` suffix, and drops any query such as
5734
+ * `?profile=core`); a static key bakes the Bearer header
5643
5735
  * once, an OAuth profile installs an auto-refreshing `AuthProvider`.
5644
5736
  *
5645
5737
  * Declared with a polymorphic `this` so every subclass inherits a