dsh-mnemon-provider-openviking 0.5.4 → 0.5.6

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
@@ -2,12 +2,18 @@
2
2
 
3
3
  An adapter for an existing OpenViking HTTP service and its filesystem-shaped memory resources.
4
4
 
5
- Requires a reachable OpenViking endpoint and configured resource scope. Extraction can be asynchronous; acceptance is not durable completion.
5
+ Requires a reachable OpenViking endpoint supporting `POST /api/v1/content/write` with `mode: "create"`, `wait: true`, and tags. Agent-authored memories use unique Markdown files; the adapter verifies completed indexing and exact full-content readback before returning `stored` with a reversible `id`. It does not create extraction sessions.
6
+
7
+ The supported scope is `viking://user/<user>/memories`. Existing `viking://user/memories` settings resolve through the configured user or authenticated `/api/v1/system/status` identity, without rewriting the local registry. A failed response, timeout, or mismatched readback produces an error instead of a committed receipt. The error includes the requested URI because remote content may remain; inspect it before retrying. Existing memories remain readable, and downgrading does not remove files written by this adapter.
6
8
 
7
9
  ## Use
8
10
 
9
11
  The default `dsh-mnemon` Starter already installs this package. Enable and configure the service in **Settings → Memory System**, then inspect its synchronized Memory Spaces.
10
12
 
13
+ For a user API key without Admin API access, including managed OpenViking Service endpoints, fill `endpoint`, `apiKey`, `account`, and **User key owner (skip admin)** (`discoveryUser`) with the supplied account/user identifiers. The adapter validates `viking://user/<discoveryUser>/memories` through the read-only `/api/v1/fs/ls` data API and synchronizes that one space. It sends no account/user identity headers in this mode: the key determines the authenticated tenant, and `account` identifies the local projection rather than overriding that identity. Use an existing accessible memory root; an absent root, rejected key, invalid response, or denied owner fails the save and preserves previous settings. Health-only success is insufficient. This path does not verify write permission or certify a particular cloud deployment; exact writes still require the content API above.
14
+
15
+ Leave `discoveryUser` empty for the existing admin discovery flow. There is no automatic fallback after an admin error. Nonempty `discoveryUser` requires a safe user ID, an explicit account, and an API key; manually configured memory owners must match it. The new setting uses the existing service registry format. Before downgrading to an adapter without this field, clear it using the current version and use admin-capable configuration, or disable the service and restore an older compatible configuration. Reconnection and downgrade never delete remote memories.
16
+
11
17
  For a custom composition, install this package alongside `dsh-mnemon-source-memory-spaces` and include it in that Source's `config.providers`:
12
18
 
13
19
  ```yaml
@@ -24,4 +30,6 @@ This is a **Memory Spaces child module**, not a top-level Source or a complete S
24
30
 
25
31
  From a source checkout with the declared dependencies installed, run `pnpm verify`. Tests, build and public exports belong to this package, without importing another package's controllers or repository configuration. Use the Source's public `/testing` fixtures for child registration and driver conformance; live service tests require a separately authorized environment.
26
32
 
33
+ To test a disposable local OpenViking service (never a personal store), run `MNEMON_OPENVIKING_TEST_ENDPOINT=http://127.0.0.1:1933 pnpm exec vitest run tests/integration.spec.ts`. Supply `MNEMON_OPENVIKING_TEST_API_KEY` when the service requires authentication. It creates one synthetic canary in the default user's namespace, reads/searches/browses it, and deletes its exact URI. Ordinary verification skips this optional integration test. Admin discovery requires a key allowed to enumerate users; ROOT keys cannot access tenant data in `api_key` mode. The user-key regression uses deterministic responses, not a live cloud account.
34
+
27
35
  [Plugin author guide](https://github.com/omdsh-dev/dsh-mnemon/blob/main/docs/en/development/extensions.md)
@@ -10,7 +10,7 @@ const descriptor = {
10
10
  },
11
11
  "kind": "remote",
12
12
  "workspaceBinding": "provider-global",
13
- "summary": "Filesystem-shaped shared memory with tiered reads and automatic semantic extraction.",
13
+ "summary": "Filesystem-shaped shared memory with verified exact writes and semantic retrieval.",
14
14
  "summaryI18nKey": "overview.providerSummary.openviking",
15
15
  "origin": "third-party",
16
16
  "capabilities": {
@@ -22,7 +22,7 @@ const descriptor = {
22
22
  "remember": true,
23
23
  "link": false,
24
24
  "forget": true,
25
- "writeMode": "async-extracting",
25
+ "writeMode": "exact",
26
26
  "deletionMode": "hard"
27
27
  },
28
28
  "fields": [
@@ -44,7 +44,7 @@ const descriptor = {
44
44
  "required": true,
45
45
  "defaultValue": "viking://user/memories",
46
46
  "placeholder": "viking://user/memories",
47
- "pattern": "^viking://user(?:/[^/]+)?/memories$",
47
+ "pattern": "^viking://user(?:/(?!\\.{1,2}/)[a-zA-Z0-9_.@-]+)?/memories$",
48
48
  "normalize": "trim-trailing-slash",
49
49
  "validationMessage": "OpenViking memory URI must be a viking://user/.../memories root",
50
50
  "i18nKey": "overview.providerTargetUri"
@@ -65,6 +65,17 @@ const descriptor = {
65
65
  "required": false,
66
66
  "i18nKey": "overview.providerAccount"
67
67
  },
68
+ {
69
+ "key": "discoveryUser",
70
+ "label": "User key owner (skip admin)",
71
+ "scope": "service",
72
+ "input": "text",
73
+ "required": false,
74
+ "maxLength": 200,
75
+ "pattern": "^(?!\\.{1,2}$)(?!.*@.*@)[a-zA-Z0-9_.@\\-]+$",
76
+ "validationMessage": "OpenViking discovery user must be a safe user ID",
77
+ "i18nKey": "overview.providerDiscoveryUser"
78
+ },
68
79
  {
69
80
  "key": "user",
70
81
  "label": "User",
package/lib/descriptor.js CHANGED
@@ -1,2 +1,2 @@
1
- import { t as descriptor } from "./descriptor-OAMVgT8m.js";
1
+ import { t as descriptor } from "./descriptor-1h1ZrvkP.js";
2
2
  export { descriptor };
package/lib/index.d.ts CHANGED
@@ -4,8 +4,6 @@ import { Insight, JsonValue, MemoryBody, MemoryGraphSnapshot, MemoryListRequest,
4
4
  interface OpenVikingProviderOptions {
5
5
  fetch?: typeof fetch;
6
6
  requestTimeoutMs?: number;
7
- settlementTimeoutMs?: number;
8
- pollIntervalMs?: number;
9
7
  }
10
8
  declare class OpenVikingProvider implements MemoryProviderAdapter {
11
9
  private readonly memorySpaces;
@@ -13,8 +11,6 @@ declare class OpenVikingProvider implements MemoryProviderAdapter {
13
11
  readonly scoreSemantics: import("dsh-mnemon-source-memory-spaces/provider-sdk").ProviderScoreSemantics;
14
12
  private readonly requestFetch;
15
13
  private readonly requestTimeoutMs;
16
- private readonly settlementTimeoutMs;
17
- private readonly pollIntervalMs;
18
14
  constructor(memorySpaces: MemorySpaceAuthority, options?: OpenVikingProviderOptions);
19
15
  discover(connection: MemoryProviderConnection, signal?: AbortSignal): Promise<ProviderMemorySpace[]>;
20
16
  status(body: MemoryBody, signal?: AbortSignal): Promise<ProviderBodyStatus>;
@@ -24,7 +20,9 @@ declare class OpenVikingProvider implements MemoryProviderAdapter {
24
20
  remember(body: MemoryBody, request: RememberRequest, signal?: AbortSignal): Promise<JsonValue>;
25
21
  forget(body: MemoryBody, id: string, signal?: AbortSignal): Promise<JsonValue>;
26
22
  private connection;
27
- private settleTask;
23
+ private validateUserNamespace;
24
+ private memoryRoot;
25
+ private readContent;
28
26
  private request;
29
27
  private requestConnection;
30
28
  }
package/lib/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as descriptor } from "./descriptor-OAMVgT8m.js";
1
+ import { t as descriptor } from "./descriptor-1h1ZrvkP.js";
2
2
  import { MEMORY_SPACE_PROVIDER_API_VERSION, NORMALIZED_RELEVANCE_SCORE, defineMemorySpaceProvider, defineMemorySpaceProviderDefinition } from "dsh-mnemon-source-memory-spaces/provider-sdk";
3
3
  import { randomUUID } from "node:crypto";
4
4
  //#region src/driver.ts
@@ -11,18 +11,38 @@ function string(value) {
11
11
  function number(value) {
12
12
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
13
13
  }
14
- function delay(ms, signal) {
15
- if (signal?.aborted === true) return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("OpenViking request aborted"));
16
- return new Promise((resolve, reject) => {
17
- const aborted = () => {
18
- clearTimeout(timer);
19
- reject(signal?.reason ?? /* @__PURE__ */ new Error("OpenViking request aborted"));
20
- };
21
- const timer = setTimeout(() => {
22
- signal?.removeEventListener("abort", aborted);
23
- resolve();
24
- }, ms);
25
- signal?.addEventListener("abort", aborted, { once: true });
14
+ const MEMORY_FOLDERS = {
15
+ preference: "preferences",
16
+ insight: "experiences",
17
+ decision: "experiences",
18
+ context: "events",
19
+ fact: "entities",
20
+ general: "entities"
21
+ };
22
+ function memoryUri(root, category, content) {
23
+ const folder = Object.hasOwn(MEMORY_FOLDERS, category) ? MEMORY_FOLDERS[category] : "entities";
24
+ const firstLine = content.split("\n").find((line) => line.trim().length > 0) ?? "memory";
25
+ const slug = Array.from(firstLine.replace(/^#+\s*/u, "").replace(/[^\p{L}\p{N}]+/gu, "-").replace(/^-+|-+$/gu, "")).slice(0, 48).join("").toLowerCase() || "memory";
26
+ return `${root}/${folder}/${(/* @__PURE__ */ new Date()).toISOString().replace(/[-:T]/gu, "").slice(0, 14)}-${slug}-${randomUUID()}.md`;
27
+ }
28
+ function safeUser(user) {
29
+ return /^[a-zA-Z0-9_.@-]+$/u.test(user) && user !== "." && user !== ".." && (user.match(/@/gu)?.length ?? 0) <= 1;
30
+ }
31
+ function discoveryUser(connection) {
32
+ const user = String(connection.discoveryUser ?? "").trim();
33
+ if (user === "") return void 0;
34
+ if (!safeUser(user) || !safeUser(String(connection.account ?? "").trim())) throw new Error("OpenViking user-key discovery requires an explicit account and a safe discovery user");
35
+ if (String(connection.apiKey ?? "").trim() === "") throw new Error("OpenViking user-key discovery requires a user API key");
36
+ return user;
37
+ }
38
+ function isMemoryFile(uri, root) {
39
+ if (!uri.startsWith(`${root}/`) || !uri.endsWith(".md") || /[%?#\\\u0000-\u001f\u007f]/u.test(uri)) return false;
40
+ return uri.slice(root.length + 1).split("/").every((part) => part !== "" && !part.startsWith(".") && part.trim() === part);
41
+ }
42
+ function queueFailed(value) {
43
+ return Object.values(object(value) ?? {}).some((entry) => {
44
+ const queue = object(entry);
45
+ return (number(queue?.error_count) ?? 0) > 0 || Array.isArray(queue?.errors) && queue.errors.length > 0;
26
46
  });
27
47
  }
28
48
  function categoryFromUri(uri) {
@@ -35,17 +55,28 @@ var OpenVikingProvider = class {
35
55
  scoreSemantics = NORMALIZED_RELEVANCE_SCORE;
36
56
  requestFetch;
37
57
  requestTimeoutMs;
38
- settlementTimeoutMs;
39
- pollIntervalMs;
40
58
  constructor(memorySpaces, options = {}) {
41
59
  this.memorySpaces = memorySpaces;
42
60
  this.requestFetch = options.fetch ?? globalThis.fetch;
43
61
  this.requestTimeoutMs = options.requestTimeoutMs ?? 15e3;
44
- this.settlementTimeoutMs = options.settlementTimeoutMs ?? 12e4;
45
- this.pollIntervalMs = options.pollIntervalMs ?? 750;
46
62
  }
47
63
  async discover(connection, signal) {
64
+ signal?.throwIfAborted();
48
65
  let account = String(connection.account ?? "").trim();
66
+ const selectedUser = discoveryUser(connection);
67
+ if (selectedUser !== void 0) {
68
+ const targetUri = await this.validateUserNamespace(connection, selectedUser, signal);
69
+ return [{
70
+ externalId: `${account}:${selectedUser}`,
71
+ name: selectedUser,
72
+ description: `OpenViking memory namespace for ${selectedUser}`,
73
+ connection: {
74
+ targetUri,
75
+ user: selectedUser,
76
+ actorPeerId: "dsh"
77
+ }
78
+ }];
79
+ }
49
80
  if (account === "") {
50
81
  const accounts = await this.requestConnection(connection, "/api/v1/admin/accounts", {}, { signal });
51
82
  const ids = (Array.isArray(accounts) ? accounts : []).flatMap((value) => {
@@ -62,13 +93,13 @@ var OpenVikingProvider = class {
62
93
  return (Array.isArray(users) ? users : []).flatMap((value) => {
63
94
  const item = object(value);
64
95
  const user = string(item?.user_id) ?? string(item?.id) ?? string(item?.name);
65
- if (user === void 0) return [];
96
+ if (user === void 0 || !safeUser(user)) return [];
66
97
  return [{
67
98
  externalId: `${account}:${user}`,
68
99
  name: string(item?.display_name) ?? string(item?.name) ?? user,
69
100
  description: string(item?.description) ?? string(item?.role) ?? `OpenViking memory namespace for ${user}`,
70
101
  connection: {
71
- targetUri: "viking://user/memories",
102
+ targetUri: `viking://user/${user}/memories`,
72
103
  user,
73
104
  actorPeerId: "dsh"
74
105
  }
@@ -77,10 +108,16 @@ var OpenVikingProvider = class {
77
108
  }
78
109
  async status(body, signal) {
79
110
  try {
80
- await this.request(body, "/health", {}, {
111
+ const connection = this.connection(body);
112
+ const selectedUser = discoveryUser(connection);
113
+ if (selectedUser === void 0) await this.request(body, "/health", {}, {
81
114
  signal,
82
115
  timeoutMs: 5e3
83
116
  });
117
+ else {
118
+ await this.memoryRoot(body, signal);
119
+ await this.validateUserNamespace(connection, selectedUser, signal);
120
+ }
84
121
  return { healthy: true };
85
122
  } catch (error) {
86
123
  return {
@@ -90,20 +127,20 @@ var OpenVikingProvider = class {
90
127
  }
91
128
  }
92
129
  async search(body, request, signal) {
93
- const connection = this.connection(body);
130
+ const memoryRoot = await this.memoryRoot(body, signal);
94
131
  const root = object(await this.request(body, "/api/v1/search/find", {
95
132
  method: "POST",
96
133
  body: JSON.stringify({
97
134
  query: request.query,
98
- target_uri: connection.targetUri,
135
+ target_uri: memoryRoot,
99
136
  context_type: ["memory"],
100
137
  limit: request.limit
101
138
  })
102
139
  }, { signal }));
103
- return { results: (Array.isArray(root?.memories) ? root.memories : []).flatMap((value) => {
140
+ const matches = (Array.isArray(root?.memories) ? root.memories : []).flatMap((value) => {
104
141
  const item = object(value);
105
142
  const uri = string(item?.uri);
106
- if (uri === void 0) return [];
143
+ if (uri === void 0 || !isMemoryFile(uri, memoryRoot)) return [];
107
144
  const score = number(item?.score);
108
145
  return [{
109
146
  id: uri,
@@ -113,7 +150,11 @@ var OpenVikingProvider = class {
113
150
  source: "external",
114
151
  ...score === void 0 ? {} : { score }
115
152
  }];
116
- }) };
153
+ }).slice(0, request.limit);
154
+ return { results: await Promise.all(matches.map(async (item) => ({
155
+ ...item,
156
+ content: await this.readContent(body, item.id, signal)
157
+ }))) };
117
158
  }
118
159
  async graph(body, signal) {
119
160
  return {
@@ -126,9 +167,9 @@ var OpenVikingProvider = class {
126
167
  };
127
168
  }
128
169
  async list(body, request, signal) {
129
- const connection = this.connection(body);
170
+ const memoryRoot = await this.memoryRoot(body, signal);
130
171
  const query = new URLSearchParams({
131
- uri: connection.targetUri,
172
+ uri: memoryRoot,
132
173
  recursive: "true",
133
174
  output: "original"
134
175
  });
@@ -138,20 +179,13 @@ var OpenVikingProvider = class {
138
179
  const files = entries.flatMap((value) => {
139
180
  const item = object(value);
140
181
  const uri = string(item?.uri);
141
- const filename = uri?.slice(uri.lastIndexOf("/") + 1);
142
- return item === void 0 || uri === void 0 || item.isDir === true || filename?.startsWith(".") === true || !uri.endsWith(".md") ? [] : [{
182
+ return item === void 0 || uri === void 0 || item.isDir === true || !isMemoryFile(uri, memoryRoot) ? [] : [{
143
183
  item,
144
184
  uri
145
185
  }];
146
186
  }).slice(0, limit);
147
187
  return Promise.all(files.map(async ({ item, uri }) => {
148
- let content = string(item.abstract) ?? string(item.overview) ?? "";
149
- if (content === "") try {
150
- const read = await this.request(body, `/api/v1/content/abstract?uri=${encodeURIComponent(uri)}`, {}, { signal });
151
- content = string(read) ?? string(object(read)?.content) ?? string(object(read)?.abstract) ?? uri;
152
- } catch {
153
- content = uri;
154
- }
188
+ const content = await this.readContent(body, uri, signal);
155
189
  const createdAt = string(item.modTime);
156
190
  return {
157
191
  id: uri,
@@ -164,70 +198,57 @@ var OpenVikingProvider = class {
164
198
  }));
165
199
  }
166
200
  async remember(body, request, signal) {
167
- const sessionId = `dsh-mnemon-${Date.now()}-${randomUUID()}`;
168
- await this.request(body, "/api/v1/sessions", {
169
- method: "POST",
170
- body: JSON.stringify({ session_id: sessionId })
171
- }, { signal });
172
- await this.request(body, `/api/v1/sessions/${encodeURIComponent(sessionId)}/messages`, {
173
- method: "POST",
174
- body: JSON.stringify({
175
- role: "user",
176
- content: request.content
177
- })
178
- }, { signal });
179
- const committed = object(await this.request(body, `/api/v1/sessions/${encodeURIComponent(sessionId)}/commit`, {
180
- method: "POST",
181
- body: JSON.stringify({ keep_recent_count: 0 })
182
- }, {
183
- signal,
184
- timeoutMs: 3e4
185
- }));
186
- const taskId = string(committed?.task_id);
187
- const archiveUri = string(committed?.archive_uri);
188
- if (taskId === void 0) return {
189
- action: "skipped",
190
- provider: "openviking",
191
- summary: string(committed?.reason) ?? "OpenViking did not archive a memory candidate.",
192
- sessionId
193
- };
194
- const task = await this.settleTask(body, taskId, signal);
195
- if (task === void 0) return {
196
- action: "queued",
197
- provider: "openviking",
198
- summary: "OpenViking accepted the session and is extracting durable memories asynchronously.",
199
- status: "pending",
200
- taskId,
201
- sessionId,
202
- ...archiveUri === void 0 ? {} : { archiveUri }
203
- };
204
- const extracted = object(object(task.result)?.memories_extracted) ?? {};
205
- const total = Object.values(extracted).reduce((sum, value) => sum + (number(value) ?? 0), 0);
201
+ const root = await this.memoryRoot(body, signal);
202
+ const category = string(request.category) ?? "general";
203
+ const uri = memoryUri(root, category, request.content);
204
+ const tags = ["source=mnemon", `category=${category}`];
205
+ const importance = number(request.importance);
206
+ if (importance !== void 0) tags.push(`importance=${importance}`);
207
+ const writtenBytes = Buffer.byteLength(request.content, "utf8");
208
+ try {
209
+ const written = object(await this.request(body, "/api/v1/content/write", {
210
+ method: "POST",
211
+ body: JSON.stringify({
212
+ uri,
213
+ content: request.content,
214
+ mode: "create",
215
+ wait: true,
216
+ timeout: this.requestTimeoutMs / 1e3,
217
+ tags
218
+ })
219
+ }, { signal }));
220
+ if (written?.uri !== uri || written.content_updated !== true || written.written_bytes !== writtenBytes || written.mode !== "create" || written.context_type !== "memory" || written.vector_status !== "complete" || !["complete", "skipped"].includes(String(written.semantic_status)) || queueFailed(written.queue_status)) throw new Error("content API did not confirm this exact memory and completed indexing");
221
+ if (await this.readContent(body, uri, signal) !== request.content) throw new Error("stored content does not match the requested text");
222
+ signal?.throwIfAborted();
223
+ } catch (error) {
224
+ throw new Error(`OpenViking write was not verified at ${uri}; remote content may remain. Inspect this URI before retrying. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
225
+ }
206
226
  return {
207
- action: total > 0 ? "stored" : "skipped",
227
+ action: "stored",
208
228
  provider: "openviking",
209
- summary: total > 0 ? `OpenViking extracted ${total} durable ${total === 1 ? "memory" : "memories"}.` : "OpenViking completed extraction without a durable memory change.",
210
- taskId,
211
- sessionId,
212
- ...archiveUri === void 0 ? {} : { archiveUri },
213
- extracted
229
+ id: uri,
230
+ uri,
231
+ externalUri: uri,
232
+ summary: `OpenViking stored the memory at ${uri} (category ${category}).`,
233
+ writtenBytes,
234
+ vectorStatus: "complete"
214
235
  };
215
236
  }
216
237
  async forget(body, id, signal) {
217
- const connection = this.connection(body);
238
+ const root = await this.memoryRoot(body, signal);
218
239
  const uri = id.trim();
219
- const root = connection.targetUri.replace(/\/+$/u, "");
220
- const filename = uri.slice(uri.lastIndexOf("/") + 1);
221
- if (!uri.startsWith(`${root}/`) || !uri.endsWith(".md") || filename.startsWith(".")) throw new Error("OpenViking forget requires an exact non-generated .md memory URI inside this Memory Space");
240
+ if (!isMemoryFile(uri, root)) throw new Error("OpenViking forget requires an exact non-generated .md memory URI inside this Memory Space");
222
241
  const query = new URLSearchParams({
223
242
  uri,
224
243
  recursive: "false"
225
244
  });
226
245
  const result = object(await this.request(body, `/api/v1/fs?${query}`, { method: "DELETE" }, { signal })) ?? {};
246
+ if (result.uri !== uri) throw new Error("OpenViking did not confirm deletion of the requested memory URI");
227
247
  return {
228
248
  action: "deleted",
229
249
  provider: this.id,
230
- uri: string(result.uri) ?? uri,
250
+ id: uri,
251
+ uri,
231
252
  ...number(result.estimated_deleted_count) === void 0 ? {} : { estimatedDeletedCount: number(result.estimated_deleted_count) }
232
253
  };
233
254
  }
@@ -240,21 +261,41 @@ var OpenVikingProvider = class {
240
261
  apiKey: String(connection.apiKey ?? ""),
241
262
  account: String(connection.account ?? ""),
242
263
  user: String(connection.user ?? ""),
243
- actorPeerId: String(connection.actorPeerId ?? "")
264
+ actorPeerId: String(connection.actorPeerId ?? ""),
265
+ discoveryUser: String(connection.discoveryUser ?? "")
244
266
  };
245
267
  }
246
- async settleTask(body, taskId, signal) {
247
- const deadline = Date.now() + this.settlementTimeoutMs;
248
- while (Date.now() < deadline) {
249
- const task = object(await this.request(body, `/api/v1/tasks/${encodeURIComponent(taskId)}`, {}, {
250
- signal,
251
- timeoutMs: 1e4
252
- })) ?? {};
253
- const status = string(task.status);
254
- if (status === "completed") return task;
255
- if (status === "failed" || status === "cancelled") throw new Error(`OpenViking memory extraction ${status}: ${string(task.error) ?? taskId}`);
256
- await delay(this.pollIntervalMs, signal);
268
+ async validateUserNamespace(connection, user, signal) {
269
+ const root = `viking://user/${user}/memories`;
270
+ const query = new URLSearchParams({
271
+ uri: root,
272
+ recursive: "false",
273
+ output: "original"
274
+ });
275
+ const result = await this.requestConnection(connection, `/api/v1/fs/ls?${query}`, {}, { signal });
276
+ if (!Array.isArray(result) || result.some((item) => !string(object(item)?.uri)?.startsWith(`${root}/`))) throw new Error("OpenViking could not validate the selected memory namespace");
277
+ return root;
278
+ }
279
+ async memoryRoot(body, signal) {
280
+ signal?.throwIfAborted();
281
+ const connection = this.connection(body);
282
+ const root = connection.targetUri.replace(/\/+$/u, "");
283
+ const match = /^viking:\/\/user(?:\/([^/]+))?\/memories$/u.exec(root);
284
+ if (match === null || match[1] !== void 0 && !safeUser(match[1])) throw new Error("OpenViking memory URI must be a safe viking://user/<user>/memories root");
285
+ const selectedUser = discoveryUser(connection);
286
+ if (selectedUser !== void 0) {
287
+ if (match[1] !== void 0 && match[1] !== selectedUser || connection.user?.trim() && connection.user.trim() !== selectedUser) throw new Error("OpenViking memory owner must match the configured discovery user");
288
+ return `viking://user/${selectedUser}/memories`;
257
289
  }
290
+ if (match[1] !== void 0) return root;
291
+ const user = connection.user?.trim() || string(object(await this.request(body, "/api/v1/system/status", {}, { signal }))?.user) || "";
292
+ if (!safeUser(user)) throw new Error("OpenViking could not resolve the memory owner; configure an explicit user memory URI");
293
+ return `viking://user/${user}/memories`;
294
+ }
295
+ async readContent(body, uri, signal) {
296
+ const result = await this.request(body, `/api/v1/content/read?${new URLSearchParams({ uri })}`, {}, { signal });
297
+ if (typeof result !== "string") throw new Error("OpenViking content read did not return text");
298
+ return result;
258
299
  }
259
300
  async request(body, path, init = {}, options = {}) {
260
301
  const connection = this.connection(body);
@@ -262,6 +303,7 @@ var OpenVikingProvider = class {
262
303
  }
263
304
  async requestConnection(connection, path, init = {}, options = {}) {
264
305
  options.signal?.throwIfAborted();
306
+ const keyBound = discoveryUser(connection) !== void 0;
265
307
  const controller = new AbortController();
266
308
  const relay = () => controller.abort(options.signal?.reason);
267
309
  options.signal?.addEventListener("abort", relay, { once: true });
@@ -272,8 +314,8 @@ var OpenVikingProvider = class {
272
314
  headers: {
273
315
  "Content-Type": "application/json",
274
316
  ...connection.apiKey === void 0 || connection.apiKey === "" ? {} : { Authorization: `Bearer ${connection.apiKey}` },
275
- ...connection.account === void 0 || connection.account === "" ? {} : { "X-OpenViking-Account": String(connection.account) },
276
- ...connection.user === void 0 || connection.user === "" ? {} : { "X-OpenViking-User": String(connection.user) },
317
+ ...keyBound || connection.account === void 0 || connection.account === "" ? {} : { "X-OpenViking-Account": String(connection.account) },
318
+ ...keyBound || connection.user === void 0 || connection.user === "" ? {} : { "X-OpenViking-User": String(connection.user) },
277
319
  ...connection.actorPeerId === void 0 || connection.actorPeerId === "" ? {} : { "X-OpenViking-Actor-Peer": String(connection.actorPeerId) },
278
320
  ...init.headers
279
321
  },
@@ -302,7 +344,7 @@ const definition = defineMemorySpaceProviderDefinition({
302
344
  kind: "provider",
303
345
  typeId: descriptor.id,
304
346
  packageName: "dsh-mnemon-provider-openviking",
305
- version: "0.5.4",
347
+ version: "0.5.6",
306
348
  label: descriptor.label,
307
349
  icon: descriptor.icon,
308
350
  summary: descriptor.summary,
@@ -315,10 +357,7 @@ const definition = defineMemorySpaceProviderDefinition({
315
357
  secrets: descriptor.fields.filter((field) => field.input === "secret").map((field) => field.key),
316
358
  scoreSemantics: "normalized-relevance"
317
359
  },
318
- create: (context) => new OpenVikingProvider(context.memorySpaces ?? context.memoryBodies, {
319
- requestTimeoutMs: context.config.timeoutMs,
320
- settlementTimeoutMs: context.config.timeoutMs
321
- })
360
+ create: (context) => new OpenVikingProvider(context.memorySpaces ?? context.memoryBodies, { requestTimeoutMs: context.config.timeoutMs })
322
361
  });
323
362
  var src_default = defineMemorySpaceProvider({
324
363
  id: descriptor.id,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-mnemon-provider-openviking",
3
- "version": "0.5.4",
3
+ "version": "0.5.6",
4
4
  "description": "OpenViking Provider child for the Memory Spaces Source.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -34,7 +34,7 @@
34
34
  },
35
35
  "devDependencies": {
36
36
  "@types/node": "^22.0.0",
37
- "dsh-mnemon-source-memory-spaces": "^0.5.4",
37
+ "dsh-mnemon-source-memory-spaces": "^0.5.9",
38
38
  "tsdown": "^0.22.0",
39
39
  "typescript": "^5.9.0",
40
40
  "vitest": "^3.2.0"