kagura-memory 0.10.0 → 0.10.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
@@ -460,6 +460,7 @@ per-minute limit. `SecretClient` renders a 429 as `KaguraConnectionError`.
460
460
  import { KaguraFeatureNotAvailableError, KaguraQuotaError } from "kagura-memory";
461
461
 
462
462
  try {
463
+ // The context is named after the resource unless you pass `name`.
463
464
  await client.setupResource({ resourceId: "crm" });
464
465
  } catch (e) {
465
466
  if (e instanceof KaguraFeatureNotAvailableError) {
@@ -509,7 +510,7 @@ the counterpart to `recall`'s probabilistic search.
509
510
 
510
511
  | Method | What it does |
511
512
  |--------|--------------|
512
- | `listTags` | Tag vocabulary with counts and recency. `prefix` narrows by spelling; `withTags` is a multi-tag AND drill-down that also excludes those tags from the result — the two compose into server-side faceted browsing with no local index. |
513
+ | `listTags` | Tag vocabulary with counts and recency. `prefix` narrows by spelling; `withTags` is a multi-tag AND drill-down that also excludes those tags from the result — the two compose into server-side faceted browsing with no local index. A drill-down calls the REST tags endpoint, because the MCP tool ignores `withTags` (through server v0.76.0); the result has the same shape. Its values are trimmed and blank ones dropped, and at most 50 of up to 200 characters each are accepted. |
513
514
  | `explore` | Graph traversal from a seed memory (`depth` 1–5, `minWeight`). |
514
515
  | `listEdges` | Edges touching a memory, incoming and outgoing, deduplicated. |
515
516
  | `createEdge` / `updateEdge` / `deleteEdge` | Manual edge curation. `(sourceId, targetId)` is the identity; self-loops are rejected. |
@@ -521,13 +522,13 @@ the counterpart to `recall`'s probabilistic search.
521
522
  | Method | What it does |
522
523
  |--------|--------------|
523
524
  | `listContexts` | The contexts you can see, most recently used first, as a slim name→id directory (`id`, `name`, `is_private`, `is_locked`, `last_used_at`; server v0.73.0+). `nameContains` filters (server v0.73.0+; older servers ignore it and return every context); `includeSummary` (capped at 300 chars), `includeDetails` (full `summary` + `embedding_model`) and `includeStats` (`memory_count`) add fields. `count` is quota usage and `total` the number returned; `can_create` is the quota flag, and `hint` appears when you can see no context. |
524
- | `createContext` | New context. Throws `KaguraQuotaError` when the workspace limit is reached: the SDK checks `listContexts()` first, so that error carries `quotaType`, `current` and `limit` but no `gate` or plan fields (`requiredPlan` `null` means unknown). Also throws `KaguraFeatureNotAvailableError` for a shared one (`isPrivate: false`) on a plan without shared contexts (server v0.75.0+). `embeddingModel` cannot be changed through the API afterwards (an operator can migrate it server-side, v0.66.0+). |
525
+ | `createContext` | New context. Throws `KaguraQuotaError` when the workspace limit is reached: the SDK checks `listContexts()` first, so that error carries `quotaType`, `current` and `limit` but no `gate` or plan fields (`requiredPlan` `null` means unknown). Also throws `KaguraFeatureNotAvailableError` for a shared one (`isPrivate: false`) on a plan without shared contexts (server v0.75.0+). `embeddingModel` cannot be changed through the API afterwards (an operator can migrate it server-side, v0.66.0+). `resourceId` is deprecated and no longer sent, since the server ignores it: set it with `updateContext`, or use `setupResource`. |
525
526
  | `getContextInfo` | Metadata plus, by default, a memory-count breakdown. On server v0.74.0+ also a trimmed `guardrails` block: absent when the MCP URL carries `?guardrails=off`, `null` when the server's read failed. |
526
527
  | `updateContext` | Change display name, summary, usage guide, visibility, lock. `isPublic: true` is plan-gated and throws `KaguraFeatureNotAvailableError` on a plan without public contexts. |
527
528
  | `deleteContext` | Delete by id. Locked contexts are refused. |
528
529
  | `mergeContexts` | Move memories between contexts. Both must share an embedding model and workspace. |
529
530
  | `updateSearchConfig` | Hybrid-search weights (must sum to 1.0 ±0.01), reranking (`useRerank`, which a `recall` that omits it follows) and the reranker (`voyage`, `cohere` or `self_hosted`), reinforce re-rank (`reinforceEnabled`, `reinforceMaxBoost`, `reinforceRequireHostArbitration`) and query routing (`routingMode`). Owner/editor only; a context that does not exist, or that the caller cannot see, also throws `KaguraPermissionError`. Returns the whole updated `config`, the only place the reinforce and routing fields come back. |
530
- | `setupResource` | Context + resource entity + ingestion token in one transaction. The returned token is plaintext and shown once. Plan-gated: throws `KaguraFeatureNotAvailableError` on a plan without resources. |
531
+ | `setupResource` | Context + resource entity + ingestion token in one transaction. The returned token is plaintext and shown once. The context is named `name`, or `resourceId` when that is omitted. `summary` is deprecated and no longer sent, since the server ignores it: set it afterwards with `updateContext`. Plan-gated: throws `KaguraFeatureNotAvailableError` on a plan without resources. |
531
532
 
532
533
  ### Agent run-state
533
534
 
package/dist/cli.js CHANGED
@@ -148,7 +148,7 @@ var KaguraCryptoError = class extends KaguraSecretError {
148
148
  };
149
149
 
150
150
  // src/version.ts
151
- var SDK_VERSION = "0.10.0";
151
+ var SDK_VERSION = "0.10.1";
152
152
 
153
153
  // src/http.ts
154
154
  function baseUrlFromMcp(mcpUrl) {
@@ -4640,12 +4640,18 @@ function parseSince(raw) {
4640
4640
  }
4641
4641
  return parsed;
4642
4642
  }
4643
+ var SETUP_SUMMARY_IGNORED_NOTE = "Note: --summary is ignored, since the server's setup_resource has no summary. Set it after setup with `kagura-memory context update <context_id> --summary ...`.";
4643
4644
  var setup = {
4644
4645
  summary: "One-shot resource setup: create context + token.",
4645
4646
  spec: {
4646
4647
  flags: [
4647
- { ...RESOURCE_ID, help: "Resource identifier" },
4648
- { name: "summary", short: "s", type: "value", help: "Context summary" },
4648
+ { ...RESOURCE_ID, help: "Resource identifier (also the context name)" },
4649
+ {
4650
+ name: "summary",
4651
+ short: "s",
4652
+ type: "value",
4653
+ help: "Deprecated and ignored by the server; use `context update` after setup"
4654
+ },
4649
4655
  { ...DESCRIPTION2, help: "Token description" },
4650
4656
  { ...QUOTA, help: "Events/hour (1-10000)", defaultLabel: "1000" }
4651
4657
  ]
@@ -4653,16 +4659,17 @@ var setup = {
4653
4659
  run: async (deps, args) => {
4654
4660
  rejectExtraArgs(args);
4655
4661
  const resourceId = requiredValue(args, RESOURCE_ID);
4656
- const summary = args.values.summary;
4657
4662
  const description = args.values.description;
4658
4663
  const raw = args.values.quota;
4659
4664
  const quotaEventsPerHour = raw === void 0 ? 1e3 : parseRanged(QUOTA, raw, { min: 1, max: 1e4, rangeLabel: "1<=x<=10000", integer: true });
4660
4665
  const { config } = resolveConfig(deps, void 0, false);
4666
+ if (args.values.summary !== void 0) {
4667
+ deps.writeError(SETUP_SUMMARY_IGNORED_NOTE);
4668
+ }
4661
4669
  return runAndPrint(
4662
4670
  deps,
4663
4671
  () => deps.makeResourceClient().setupResource({
4664
4672
  resourceId,
4665
- ...summary !== void 0 ? { summary } : {},
4666
4673
  ...description !== void 0 ? { description } : {},
4667
4674
  quotaEventsPerHour
4668
4675
  })
@@ -5909,6 +5916,12 @@ var KaguraClient = class _KaguraClient {
5909
5916
  /** Bumped by close(), so a handshake it interrupted cannot re-adopt its session. */
5910
5917
  sessionEpoch = 0;
5911
5918
  requestIdCounter = 1;
5919
+ /**
5920
+ * Context id (lower case) → name, for the `listTags` drill-down, whose
5921
+ * REST route sends no name (#47). Safe to keep: the server has no way to
5922
+ * rename a context (`update_context` cannot change `name`).
5923
+ */
5924
+ contextNames = /* @__PURE__ */ new Map();
5912
5925
  constructor(options = {}) {
5913
5926
  const resolved = resolveAuth({
5914
5927
  apiKey: options.apiKey ?? null,
@@ -6068,13 +6081,28 @@ var KaguraClient = class _KaguraClient {
6068
6081
  const result = data.result;
6069
6082
  return typeof result === "object" && result !== null ? result : {};
6070
6083
  }
6071
- /** GET a REST endpoint and parse the JSON body. */
6072
- async restGet(path9, params) {
6084
+ /**
6085
+ * GET a REST endpoint and parse the JSON body.
6086
+ *
6087
+ * An array param is sent as one repeated key per item (`?k=a&k=b`), which
6088
+ * is how FastAPI reads a `list[str]` query; joined, `a,b` is one value.
6089
+ *
6090
+ * Without `operation`, every non-2xx goes through the standard status
6091
+ * mapping (a 404 is a {@link KaguraConnectionError}). With it, a 404 and a
6092
+ * 422 get the classes and messages the MCP path gives that tool's
6093
+ * `*_not_found` and `invalid_argument` errors, so a method that moved
6094
+ * from MCP to REST throws what it always threw.
6095
+ */
6096
+ async restGet(path9, params, operation) {
6073
6097
  let url = `${this.baseUrl}${path9}`;
6074
6098
  if (params) {
6075
6099
  const query = new URLSearchParams();
6076
6100
  for (const [key, value] of Object.entries(params)) {
6077
- if (value !== void 0 && value !== null) {
6101
+ if (Array.isArray(value)) {
6102
+ for (const item of value) {
6103
+ query.append(key, String(item));
6104
+ }
6105
+ } else if (value !== void 0 && value !== null) {
6078
6106
  query.set(key, String(value));
6079
6107
  }
6080
6108
  }
@@ -6098,6 +6126,15 @@ var KaguraClient = class _KaguraClient {
6098
6126
  }
6099
6127
  const text = await this.safeText(response);
6100
6128
  if (!response.ok) {
6129
+ if (operation !== void 0) {
6130
+ const detail = extractDetail(text);
6131
+ if (response.status === 404) {
6132
+ throw new KaguraNotFoundError(`${operation}: ${detail || "Not found"}`);
6133
+ }
6134
+ if (response.status === 422) {
6135
+ throw new KaguraError(`${operation} failed (invalid_argument): ${detail || "HTTP 422"}`);
6136
+ }
6137
+ }
6101
6138
  throwForKaguraStatus(response.status, response.headers, text);
6102
6139
  }
6103
6140
  try {
@@ -6752,6 +6789,13 @@ var KaguraClient = class _KaguraClient {
6752
6789
  *
6753
6790
  * Call before remember() to reuse existing tag spellings, or before
6754
6791
  * recall() with tag filters. Requires memory-cloud server v0.15.4+.
6792
+ * A `withTags` drill-down is sent to the REST tags route rather than MCP
6793
+ * (see {@link ListTagsOptions.withTags}); the result has the same shape.
6794
+ *
6795
+ * @throws Error if `limit`, `minCount`, `prefix` or `withTags` is out of
6796
+ * range, before any request.
6797
+ * @throws KaguraNotFoundError if the context does not exist or the caller
6798
+ * cannot see it.
6755
6799
  */
6756
6800
  async listTags(options) {
6757
6801
  const limit = options.limit ?? 50;
@@ -6766,21 +6810,107 @@ var KaguraClient = class _KaguraClient {
6766
6810
  if (prefix.length > 200) {
6767
6811
  throw new Error(`prefix must be at most 200 characters, got ${prefix.length}`);
6768
6812
  }
6813
+ const withTags = (options.withTags ?? []).map((t) => t.trim()).filter((t) => t !== "");
6814
+ if (withTags.length > 50) {
6815
+ throw new Error(`withTags accepts at most 50 tags, got ${withTags.length}`);
6816
+ }
6817
+ const tooLong = withTags.map((t) => [...t].length).find((n) => n > 200);
6818
+ if (tooLong !== void 0) {
6819
+ throw new Error(`each withTags value must be at most 200 characters, got ${tooLong}`);
6820
+ }
6821
+ const sort = options.sort ?? "count";
6822
+ if (withTags.length > 0) {
6823
+ return this.listTagsViaRest(options.contextId, {
6824
+ limit,
6825
+ min_count: minCount,
6826
+ sort,
6827
+ prefix: prefix || void 0,
6828
+ with_tags: withTags
6829
+ });
6830
+ }
6769
6831
  const args = {
6770
6832
  context_id: options.contextId,
6771
6833
  limit,
6772
6834
  min_count: minCount,
6773
- sort: options.sort ?? "count"
6835
+ sort
6774
6836
  };
6775
6837
  if (prefix) {
6776
6838
  args.prefix = prefix;
6777
6839
  }
6778
- if (options.withTags !== void 0 && options.withTags.length > 0) {
6779
- args.with_tags = options.withTags;
6780
- }
6781
6840
  const result = await this.callToolChecked("list_tags", args);
6841
+ this.rememberContextName(result);
6782
6842
  return result;
6783
6843
  }
6844
+ /**
6845
+ * The `listTags` drill-down over `GET /api/v1/contexts/{id}/tags`,
6846
+ * reshaped to exactly what MCP `list_tags` returns: the route adds a
6847
+ * `sample_summary` (always null) but sends no `status` or `context_name`.
6848
+ */
6849
+ async listTagsViaRest(contextId, params) {
6850
+ const body = await this.restGet(
6851
+ `/api/v1/contexts/${encodeURIComponent(contextId)}/tags`,
6852
+ params,
6853
+ "list_tags"
6854
+ );
6855
+ const record = typeof body === "object" && body !== null && !Array.isArray(body) ? body : {};
6856
+ const rawTags = record.tags;
6857
+ if (typeof record.context_id !== "string" || !Array.isArray(rawTags) || typeof record.total !== "number") {
6858
+ throw new KaguraConnectionError(
6859
+ "Unexpected list_tags response: missing 'context_id', 'tags' or 'total'."
6860
+ );
6861
+ }
6862
+ const tags = rawTags.map((item) => {
6863
+ const tag = typeof item === "object" && item !== null ? item : {};
6864
+ if (typeof tag.tag !== "string" || typeof tag.count !== "number") {
6865
+ throw new KaguraConnectionError(
6866
+ "Unexpected list_tags response: a tag without 'tag' or 'count'."
6867
+ );
6868
+ }
6869
+ return {
6870
+ tag: tag.tag,
6871
+ count: tag.count,
6872
+ last_used_at: typeof tag.last_used_at === "string" ? tag.last_used_at : null
6873
+ };
6874
+ });
6875
+ const contextName = await this.contextNameFor(record.context_id);
6876
+ const result = {
6877
+ status: "success",
6878
+ context_id: record.context_id,
6879
+ context_name: contextName,
6880
+ tags,
6881
+ total: record.total
6882
+ };
6883
+ return result;
6884
+ }
6885
+ /**
6886
+ * A context's name, from the cache or from one `list_tags` call.
6887
+ *
6888
+ * `list_tags`, not `get_context_info`: it checks access exactly as the
6889
+ * REST tags route does, where `get_context_info` also applies an API
6890
+ * key's workspace scope and agent bindings and so can refuse a context
6891
+ * the route serves. It is also exempt from the MCP daily limit, and with
6892
+ * `limit: 1` it carries one tag.
6893
+ */
6894
+ async contextNameFor(contextId) {
6895
+ const key = contextId.toLowerCase();
6896
+ const cached = this.contextNames.get(key);
6897
+ if (cached !== void 0) {
6898
+ return cached;
6899
+ }
6900
+ const result = await this.callToolChecked("list_tags", { context_id: contextId, limit: 1 });
6901
+ const name = result.context_name;
6902
+ if (typeof name !== "string") {
6903
+ throw new KaguraConnectionError("Unexpected list_tags response: missing 'context_name'.");
6904
+ }
6905
+ this.contextNames.set(key, name);
6906
+ return name;
6907
+ }
6908
+ /** Keep the context name an MCP `list_tags` result carries. */
6909
+ rememberContextName(result) {
6910
+ if (typeof result.context_id === "string" && typeof result.context_name === "string") {
6911
+ this.contextNames.set(result.context_id.toLowerCase(), result.context_name);
6912
+ }
6913
+ }
6784
6914
  /**
6785
6915
  * Call tools/list to get available MCP tool definitions (names,
6786
6916
  * descriptions, parameter schemas).
@@ -6951,9 +7081,6 @@ var KaguraClient = class _KaguraClient {
6951
7081
  if (options.usageGuide !== void 0) {
6952
7082
  args.usage_guide = options.usageGuide;
6953
7083
  }
6954
- if (options.resourceId !== void 0) {
6955
- args.resource_id = options.resourceId;
6956
- }
6957
7084
  if (options.embeddingModel !== void 0) {
6958
7085
  args.embedding_model = options.embeddingModel;
6959
7086
  }
@@ -6997,6 +7124,9 @@ var KaguraClient = class _KaguraClient {
6997
7124
  * Plan-gated on the `resources` feature (server v0.68.0+): a plan
6998
7125
  * without it is refused with nothing created.
6999
7126
  *
7127
+ * The context is named `name`, or `resourceId` when `name` is omitted:
7128
+ * the server requires a name and refuses the call without one.
7129
+ *
7000
7130
  * @throws KaguraFeatureNotAvailableError when the plan lacks `resources`;
7001
7131
  * `requiredPlanDisplay` names the plan that has it.
7002
7132
  * @throws KaguraQuotaError at the workspace's context or token cap.
@@ -7004,14 +7134,9 @@ var KaguraClient = class _KaguraClient {
7004
7134
  async setupResource(options) {
7005
7135
  const args = {
7006
7136
  resource_id: options.resourceId,
7137
+ name: options.name ?? options.resourceId,
7007
7138
  quota_events_per_hour: options.quotaEventsPerHour ?? 1e3
7008
7139
  };
7009
- if (options.name !== void 0) {
7010
- args.name = options.name;
7011
- }
7012
- if (options.summary !== void 0) {
7013
- args.summary = options.summary;
7014
- }
7015
7140
  if (options.description !== void 0) {
7016
7141
  args.description = options.description;
7017
7142
  }
@@ -8069,7 +8194,8 @@ var ResourceClient = class extends KaguraRestClient {
8069
8194
  * Calls the server-side atomic `setup_resource` MCP tool which creates
8070
8195
  * Context + Resource entity + token in a single transaction. On
8071
8196
  * failure, no orphan Context rows are left on the server. Requires the
8072
- * client to be created via `fromMcpUrl()`.
8197
+ * client to be created via `fromMcpUrl()`. The context is named
8198
+ * `contextName`, or `resourceId` when that is omitted.
8073
8199
  *
8074
8200
  * @returns ResourceSetupResponse with plaintext token (shown only once).
8075
8201
  * @throws Error if the client was not created via `fromMcpUrl()`, or
@@ -8109,8 +8235,7 @@ var ResourceClient = class extends KaguraRestClient {
8109
8235
  try {
8110
8236
  const result = await mcp.setupResource({
8111
8237
  resourceId: options.resourceId,
8112
- name: options.contextName,
8113
- summary: options.summary,
8238
+ name: options.contextName ?? options.resourceId,
8114
8239
  description: options.description,
8115
8240
  quotaEventsPerHour: options.quotaEventsPerHour ?? 1e3
8116
8241
  });