-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathconfig.ts
More file actions
387 lines (373 loc) · 13.5 KB
/
config.ts
File metadata and controls
387 lines (373 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
import { homedir } from "node:os";
import { join } from "node:path";
import { resolve as resolvePath } from "node:path";
export type MemoryOpenVikingConfig = {
/** "local" = plugin starts OpenViking server as child process (like Claude Code); "remote" = use existing HTTP server */
mode?: "local" | "remote";
/** Path to ov.conf; used when mode is "local". Default ~/.openviking/ov.conf */
configPath?: string;
/** Port for local server when mode is "local". Ignored when mode is "remote". */
port?: number;
baseUrl?: string;
agentId?: string;
apiKey?: string;
targetUri?: string;
timeoutMs?: number;
autoCapture?: boolean;
captureMode?: "semantic" | "keyword";
/** Minimum sanitized text length (chars) required to trigger auto-capture. Default 50. */
captureMinLength?: number;
captureMaxLength?: number;
autoRecall?: boolean;
recallLimit?: number;
recallScoreThreshold?: number;
recallMaxContentChars?: number;
recallPreferAbstract?: boolean;
recallTokenBudget?: number;
commitTokenThreshold?: number;
ingestReplyAssist?: boolean;
ingestReplyAssistMinSpeakerTurns?: number;
ingestReplyAssistMinChars?: number;
/**
* When true (default), emit structured `openviking: diag {...}` lines (and any future
* standard-diagnostics file writes) for assemble/afterTurn. Set false to disable.
*/
emitStandardDiagnostics?: boolean;
/** When true, log tenant routing for semantic find and session writes (messages/commit) to the plugin logger. */
logFindRequests?: boolean;
};
const DEFAULT_BASE_URL = "http://127.0.0.1:1933";
const DEFAULT_PORT = 1933;
const DEFAULT_TARGET_URI = "viking://user/memories";
const DEFAULT_TIMEOUT_MS = 15000;
const DEFAULT_CAPTURE_MODE = "semantic";
const DEFAULT_CAPTURE_MIN_LENGTH = 50;
const DEFAULT_CAPTURE_MAX_LENGTH = 24000;
const DEFAULT_RECALL_LIMIT = 6;
const DEFAULT_RECALL_SCORE_THRESHOLD = 0.15;
const DEFAULT_RECALL_MAX_CONTENT_CHARS = 500;
const DEFAULT_RECALL_PREFER_ABSTRACT = true;
const DEFAULT_RECALL_TOKEN_BUDGET = 2000;
const DEFAULT_COMMIT_TOKEN_THRESHOLD = 20000;
const DEFAULT_INGEST_REPLY_ASSIST = true;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_SPEAKER_TURNS = 2;
const DEFAULT_INGEST_REPLY_ASSIST_MIN_CHARS = 120;
const DEFAULT_EMIT_STANDARD_DIAGNOSTICS = false;
const DEFAULT_LOCAL_CONFIG_PATH = join(homedir(), ".openviking", "ov.conf");
const DEFAULT_AGENT_ID = "default";
function resolveAgentId(configured: unknown): string {
if (typeof configured === "string" && configured.trim()) {
return configured.trim();
}
return DEFAULT_AGENT_ID;
}
function resolveEnvVars(value: string): string {
return value.replace(/\$\{([^}]+)\}/g, (_, envVar) => {
const envValue = process.env[envVar];
if (!envValue) {
throw new Error(`Environment variable ${envVar} is not set`);
}
return envValue;
});
}
function toNumber(value: unknown, fallback: number): number {
if (typeof value === "number" && Number.isFinite(value)) {
return value;
}
if (typeof value === "string" && value.trim() !== "") {
const parsed = Number(value);
if (Number.isFinite(parsed)) {
return parsed;
}
}
return fallback;
}
/** True when env is 1 / true / yes (case-insensitive). Used for debug flags without editing plugin JSON. */
function envFlag(name: string): boolean {
const v = process.env[name];
if (v == null || v === "") {
return false;
}
const t = String(v).trim().toLowerCase();
return t === "1" || t === "true" || t === "yes";
}
function assertAllowedKeys(value: Record<string, unknown>, allowed: string[], label: string) {
const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
if (unknown.length === 0) {
return;
}
throw new Error(`${label} has unknown keys: ${unknown.join(", ")}`);
}
function resolveDefaultBaseUrl(): string {
const fromEnv = process.env.OPENVIKING_BASE_URL || process.env.OPENVIKING_URL;
if (fromEnv) {
return fromEnv;
}
return DEFAULT_BASE_URL;
}
export const memoryOpenVikingConfigSchema = {
parse(value: unknown): Required<MemoryOpenVikingConfig> {
if (!value || typeof value !== "object" || Array.isArray(value)) {
value = {};
}
const cfg = value as Record<string, unknown>;
assertAllowedKeys(
cfg,
[
"mode",
"configPath",
"port",
"baseUrl",
"agentId",
"apiKey",
"targetUri",
"timeoutMs",
"autoCapture",
"captureMode",
"captureMinLength",
"captureMaxLength",
"autoRecall",
"recallLimit",
"recallScoreThreshold",
"recallMaxContentChars",
"recallPreferAbstract",
"recallTokenBudget",
"commitTokenThreshold",
"ingestReplyAssist",
"ingestReplyAssistMinSpeakerTurns",
"ingestReplyAssistMinChars",
"emitStandardDiagnostics",
"logFindRequests",
],
"openviking config",
);
const mode = (cfg.mode === "local" || cfg.mode === "remote" ? cfg.mode : "local") as
| "local"
| "remote";
const port = Math.max(1, Math.min(65535, Math.floor(toNumber(cfg.port, DEFAULT_PORT))));
const rawConfigPath =
typeof cfg.configPath === "string" && cfg.configPath.trim()
? cfg.configPath.trim()
: DEFAULT_LOCAL_CONFIG_PATH;
const configPath = resolvePath(
resolveEnvVars(rawConfigPath).replace(/^~/, homedir()),
);
const localBaseUrl = `http://127.0.0.1:${port}`;
const rawBaseUrl =
mode === "local" ? localBaseUrl : (typeof cfg.baseUrl === "string" ? cfg.baseUrl : resolveDefaultBaseUrl());
const resolvedBaseUrl = resolveEnvVars(rawBaseUrl).replace(/\/+$/, "");
const rawApiKey = typeof cfg.apiKey === "string" ? cfg.apiKey : process.env.OPENVIKING_API_KEY;
const captureMode = cfg.captureMode;
if (
typeof captureMode !== "undefined" &&
captureMode !== "semantic" &&
captureMode !== "keyword"
) {
throw new Error(`openviking captureMode must be "semantic" or "keyword"`);
}
return {
mode,
configPath,
port,
baseUrl: resolvedBaseUrl,
agentId: resolveAgentId(cfg.agentId),
apiKey: rawApiKey ? resolveEnvVars(rawApiKey) : "",
targetUri: typeof cfg.targetUri === "string" ? cfg.targetUri : DEFAULT_TARGET_URI,
timeoutMs: Math.max(1000, Math.floor(toNumber(cfg.timeoutMs, DEFAULT_TIMEOUT_MS))),
autoCapture: cfg.autoCapture !== false,
captureMode: captureMode ?? DEFAULT_CAPTURE_MODE,
captureMinLength: Math.max(
1,
Math.min(1000, Math.floor(toNumber(cfg.captureMinLength, DEFAULT_CAPTURE_MIN_LENGTH))),
),
captureMaxLength: Math.max(
200,
Math.min(200_000, Math.floor(toNumber(cfg.captureMaxLength, DEFAULT_CAPTURE_MAX_LENGTH))),
),
autoRecall: cfg.autoRecall !== false,
recallLimit: Math.max(1, Math.floor(toNumber(cfg.recallLimit, DEFAULT_RECALL_LIMIT))),
recallScoreThreshold: Math.min(
1,
Math.max(0, toNumber(cfg.recallScoreThreshold, DEFAULT_RECALL_SCORE_THRESHOLD)),
),
recallMaxContentChars: Math.max(
50,
Math.min(10000, Math.floor(toNumber(cfg.recallMaxContentChars, DEFAULT_RECALL_MAX_CONTENT_CHARS))),
),
recallPreferAbstract: cfg.recallPreferAbstract !== false,
recallTokenBudget: Math.max(
100,
Math.min(50000, Math.floor(toNumber(cfg.recallTokenBudget, DEFAULT_RECALL_TOKEN_BUDGET))),
),
commitTokenThreshold: Math.max(
0,
Math.min(100_000, Math.floor(toNumber(cfg.commitTokenThreshold, DEFAULT_COMMIT_TOKEN_THRESHOLD))),
),
ingestReplyAssist: cfg.ingestReplyAssist !== false,
ingestReplyAssistMinSpeakerTurns: Math.max(
1,
Math.min(
12,
Math.floor(
toNumber(
cfg.ingestReplyAssistMinSpeakerTurns,
DEFAULT_INGEST_REPLY_ASSIST_MIN_SPEAKER_TURNS,
),
),
),
),
ingestReplyAssistMinChars: Math.max(
32,
Math.min(
10000,
Math.floor(toNumber(cfg.ingestReplyAssistMinChars, DEFAULT_INGEST_REPLY_ASSIST_MIN_CHARS)),
),
),
emitStandardDiagnostics:
typeof cfg.emitStandardDiagnostics === "boolean"
? cfg.emitStandardDiagnostics
: DEFAULT_EMIT_STANDARD_DIAGNOSTICS,
logFindRequests:
cfg.logFindRequests === true ||
envFlag("OPENVIKING_LOG_ROUTING") ||
envFlag("OPENVIKING_DEBUG"),
};
},
uiHints: {
mode: {
label: "Mode",
help: "local = plugin starts OpenViking server (like Claude Code); remote = use existing HTTP server",
},
configPath: {
label: "Config path (local)",
placeholder: DEFAULT_LOCAL_CONFIG_PATH,
help: "Path to ov.conf when mode is local",
},
port: {
label: "Port (local)",
placeholder: String(DEFAULT_PORT),
help: "Port for local OpenViking server",
advanced: true,
},
baseUrl: {
label: "OpenViking Base URL (remote)",
placeholder: DEFAULT_BASE_URL,
help: "HTTP URL when mode is remote (or use ${OPENVIKING_BASE_URL})",
},
agentId: {
label: "Agent ID",
placeholder: "auto-generated",
help: 'OpenViking X-OpenViking-Agent: non-default values combine with OpenClaw ctx.agentId as "<config>_<sessionAgent>" (then sanitized to [a-zA-Z0-9_-]). Use "default" to send only ctx.agentId.',
},
apiKey: {
label: "OpenViking API Key",
sensitive: true,
placeholder: "${OPENVIKING_API_KEY}",
help: "Optional API key for OpenViking server",
},
targetUri: {
label: "Search Target URI",
placeholder: DEFAULT_TARGET_URI,
help: "Default OpenViking target URI for memory search",
},
timeoutMs: {
label: "Request Timeout (ms)",
placeholder: String(DEFAULT_TIMEOUT_MS),
advanced: true,
},
autoCapture: {
label: "Auto-Capture",
help: "Extract memories from recent conversation messages via OpenViking sessions",
},
captureMode: {
label: "Capture Mode",
placeholder: DEFAULT_CAPTURE_MODE,
advanced: true,
help: '"semantic" captures all eligible user text and relies on OpenViking extraction; "keyword" uses trigger regex first.',
},
captureMinLength: {
label: "Capture Min Length",
placeholder: String(DEFAULT_CAPTURE_MIN_LENGTH),
advanced: true,
help: "Minimum sanitized text length (chars) required to trigger auto-capture. Shorter messages are skipped to save VLM tokens.",
},
captureMaxLength: {
label: "Capture Max Length",
placeholder: String(DEFAULT_CAPTURE_MAX_LENGTH),
advanced: true,
help: "Maximum sanitized user text length allowed for auto-capture.",
},
autoRecall: {
label: "Auto-Recall",
help: "Inject relevant OpenViking memories into agent context",
},
recallLimit: {
label: "Recall Limit",
placeholder: String(DEFAULT_RECALL_LIMIT),
advanced: true,
},
recallScoreThreshold: {
label: "Recall Score Threshold",
placeholder: String(DEFAULT_RECALL_SCORE_THRESHOLD),
advanced: true,
},
recallMaxContentChars: {
label: "Recall Max Content Chars",
placeholder: String(DEFAULT_RECALL_MAX_CONTENT_CHARS),
advanced: true,
help: "Maximum characters per memory content in auto-recall injection. Content exceeding this is truncated.",
},
recallPreferAbstract: {
label: "Recall Prefer Abstract",
advanced: true,
help: "Use memory abstract instead of fetching full content when abstract is available. Reduces token usage.",
},
recallTokenBudget: {
label: "Recall Token Budget",
placeholder: String(DEFAULT_RECALL_TOKEN_BUDGET),
advanced: true,
help: "Maximum estimated tokens for auto-recall memory injection. Injection stops when budget is exhausted.",
},
commitTokenThreshold: {
label: "Commit Token Threshold",
placeholder: String(DEFAULT_COMMIT_TOKEN_THRESHOLD),
advanced: true,
help: "Minimum estimated pending tokens before auto-commit triggers. Set to 0 to commit every turn.",
},
ingestReplyAssist: {
label: "Ingest Reply Assist",
help: "When transcript-like memory ingestion is detected, add a lightweight reply instruction to reduce NO_REPLY.",
advanced: true,
},
ingestReplyAssistMinSpeakerTurns: {
label: "Ingest Min Speaker Turns",
placeholder: String(DEFAULT_INGEST_REPLY_ASSIST_MIN_SPEAKER_TURNS),
help: "Minimum speaker-tag turns (e.g. Name:) to detect transcript-like ingest text.",
advanced: true,
},
ingestReplyAssistMinChars: {
label: "Ingest Min Chars",
placeholder: String(DEFAULT_INGEST_REPLY_ASSIST_MIN_CHARS),
help: "Minimum sanitized text length required before ingest reply assist can trigger.",
advanced: true,
},
emitStandardDiagnostics: {
label: "Standard diagnostics (diag JSON lines)",
advanced: true,
help: "When enabled, emit structured openviking: diag {...} lines for assemble and afterTurn. Disable to reduce log noise.",
},
logFindRequests: {
label: "Log find requests",
help:
"Log tenant routing: POST /api/v1/search/find (query, target_uri) and session POST .../messages + .../commit (sessionId, X-OpenViking-*). Never logs apiKey. " +
"Or set env OPENVIKING_LOG_ROUTING=1 or OPENVIKING_DEBUG=1 (no JSON edit). When on, local-mode OpenViking subprocess stderr is also logged at info.",
advanced: true,
},
},
};
export const DEFAULT_MEMORY_OPENVIKING_DATA_DIR = join(
homedir(),
".openclaw",
"memory",
"openviking",
);