@unblocklabs/unblock-memory 0.10.1 → 0.10.3
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 +10 -7
- package/dist/src/abortable.d.ts +2 -0
- package/dist/src/abortable.js +4 -0
- package/dist/src/agent-paths.d.ts +5 -0
- package/dist/src/agent-paths.js +10 -0
- package/dist/src/analysis.js +13 -18
- package/dist/src/cluster-review.js +9 -7
- package/dist/src/config.js +2 -2
- package/dist/src/curation.js +3 -10
- package/dist/src/diagnostics.d.ts +6 -1
- package/dist/src/diagnostics.js +1 -1
- package/dist/src/emotion-baselines.d.ts +0 -2
- package/dist/src/emotion-baselines.js +18 -39
- package/dist/src/evidence-review.js +2 -1
- package/dist/src/extraction-chunk.js +3 -4
- package/dist/src/extraction-index.d.ts +2 -0
- package/dist/src/extraction-index.js +4 -2
- package/dist/src/extraction-runtime.js +3 -3
- package/dist/src/extraction-store.js +7 -19
- package/dist/src/extraction-worker.js +3 -2
- package/dist/src/guards.d.ts +6 -0
- package/dist/src/guards.js +12 -0
- package/dist/src/inside-out-runtime.js +4 -3
- package/dist/src/inside-out-store.js +4 -10
- package/dist/src/inside-out.js +5 -3
- package/dist/src/json-hash.d.ts +2 -0
- package/dist/src/json-hash.js +6 -0
- package/dist/src/manager.d.ts +6 -1
- package/dist/src/manager.js +62 -91
- package/dist/src/memory-database.d.ts +3 -0
- package/dist/src/memory-database.js +18 -1
- package/dist/src/memory-search.d.ts +8 -2
- package/dist/src/memory-search.js +18 -2
- package/dist/src/people-hooks.js +3 -6
- package/dist/src/people-primer-tool.js +0 -2
- package/dist/src/people-primer.js +3 -6
- package/dist/src/people-store.d.ts +2 -1
- package/dist/src/people-store.js +29 -82
- package/dist/src/people-tools.js +4 -5
- package/dist/src/plugin.js +36 -27
- package/dist/src/quality-audit.js +2 -2
- package/dist/src/query-generator.js +1 -1
- package/dist/src/response-audit.js +7 -8
- package/dist/src/response-episodes.js +5 -8
- package/dist/src/response-judge.js +2 -3
- package/dist/src/response-reviews.js +8 -18
- package/dist/src/response-runtime.js +4 -3
- package/dist/src/response-stages.js +4 -4
- package/dist/src/response-store.js +15 -44
- package/dist/src/response-text.d.ts +1 -0
- package/dist/src/response-text.js +6 -4
- package/dist/src/retrieval-telemetry.d.ts +7 -2
- package/dist/src/retrieval-telemetry.js +3 -2
- package/dist/src/runtime.js +9 -8
- package/dist/src/safety-whisperer.js +4 -12
- package/dist/src/session-projector.js +7 -14
- package/dist/src/session-sync.d.ts +1 -0
- package/dist/src/session-sync.js +13 -17
- package/dist/src/skill-whisperer.js +3 -9
- package/dist/src/slack-directory.js +1 -5
- package/dist/src/sources.js +17 -37
- package/dist/src/tool-context.d.ts +2 -0
- package/dist/src/tool-context.js +5 -1
- package/dist/src/training-input.d.ts +0 -1
- package/dist/src/training-input.js +3 -6
- package/dist/src/training-queries.d.ts +1 -1
- package/dist/src/training-queries.js +9 -8
- package/dist/src/training-retrieval.js +2 -2
- package/dist/src/training-runtime.js +3 -3
- package/dist/src/training-store.js +14 -25
- package/dist/src/typesafe-client.d.ts +8 -0
- package/dist/src/typesafe-client.js +7 -1
- package/dist/src/typesafe-review.d.ts +1 -1
- package/dist/src/typesafe-review.js +1 -3
- package/dist/src/typesafe.js +4 -7
- package/docs/configuration.md +1 -1
- package/docs/retrieval.md +34 -7
- package/openclaw.plugin.json +1 -1
- package/package.json +6 -2
|
@@ -1,15 +1,13 @@
|
|
|
1
1
|
import { basename } from "node:path";
|
|
2
2
|
import { selectTypeSafeSkill } from "./typesafe.js";
|
|
3
|
-
import { resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
|
|
3
|
+
import { isTypeSafeTimeout, resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
|
|
4
4
|
import { buildSkillWhispererQuery, recentSkillMessages } from "./whisperer-context.js";
|
|
5
5
|
import { abortable } from "./abortable.js";
|
|
6
|
+
import { isRecord } from "./guards.js";
|
|
6
7
|
const CANDIDATE_LIMIT = 10;
|
|
7
8
|
const MAX_QUERY_CHARS = 12_000;
|
|
8
9
|
const TYPESAFE_CANDIDATE_LIMIT = 3;
|
|
9
10
|
export const SKILL_WHISPERER_TIMEOUT_MS = 3000;
|
|
10
|
-
function isRecord(value) {
|
|
11
|
-
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
12
|
-
}
|
|
13
11
|
function typeSafeConversation(prompt, messages) {
|
|
14
12
|
const currentRequest = prompt.trim().slice(-MAX_QUERY_CHARS);
|
|
15
13
|
let remaining = MAX_QUERY_CHARS - currentRequest.length;
|
|
@@ -67,12 +65,10 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
|
|
|
67
65
|
try {
|
|
68
66
|
const runtimeParams = active(agentId);
|
|
69
67
|
const apiKey = await abortable(resolveTypeSafeApiKey(typesafe), signal);
|
|
70
|
-
signal.throwIfAborted();
|
|
71
68
|
if (!apiKey)
|
|
72
69
|
diagnostics?.record(agentId, "skill", typesafe.enabled ? "missing_key" : "typesafe_disabled");
|
|
73
70
|
const recentMessages = recentSkillMessages(event.messages, config.historyMessages);
|
|
74
71
|
const candidates = await abortable(runtime.searchSkills(runtimeParams, buildSkillWhispererQuery(event.prompt, recentMessages), apiKey ? -1 : config.minScore, CANDIDATE_LIMIT), signal);
|
|
75
|
-
signal.throwIfAborted();
|
|
76
72
|
const resolvedCandidates = candidates.flatMap((candidate) => {
|
|
77
73
|
const canonicalPath = runtime.resolveSkillPath(runtimeParams, candidate.path);
|
|
78
74
|
return canonicalPath ? [{ candidate, canonicalPath }] : [];
|
|
@@ -138,9 +134,7 @@ export function registerSkillWhisperer(api, runtime, config, typesafe, diagnosti
|
|
|
138
134
|
};
|
|
139
135
|
}
|
|
140
136
|
catch (error) {
|
|
141
|
-
|
|
142
|
-
(signal.aborted && signal.reason instanceof Error && signal.reason.name === "TimeoutError");
|
|
143
|
-
diagnostics?.record(agentId, "skill", timedOut ? "timed_out" : signal.aborted ? "cancelled" : "failed");
|
|
137
|
+
diagnostics?.record(agentId, "skill", isTypeSafeTimeout(error, signal) ? "timed_out" : signal.aborted ? "cancelled" : "failed");
|
|
144
138
|
if (!signal.aborted)
|
|
145
139
|
api.logger.warn("unblock-memory skill whisperer failed; no hint emitted");
|
|
146
140
|
return;
|
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
import { inspectReadOnlyChannelAccount } from "openclaw/plugin-sdk/directory-runtime";
|
|
2
|
+
import { record } from "./guards.js";
|
|
2
3
|
function text(value, maxLength) {
|
|
3
4
|
return typeof value === "string" && value.trim() ? value.trim().slice(0, maxLength) : undefined;
|
|
4
5
|
}
|
|
5
|
-
function record(value) {
|
|
6
|
-
return value && typeof value === "object" && !Array.isArray(value)
|
|
7
|
-
? value
|
|
8
|
-
: undefined;
|
|
9
|
-
}
|
|
10
6
|
function slackToken(account) {
|
|
11
7
|
return text(account.userToken, 10_000) ?? text(account.botToken, 10_000);
|
|
12
8
|
}
|
package/dist/src/sources.js
CHANGED
|
@@ -10,14 +10,16 @@ function expandHome(value) {
|
|
|
10
10
|
function collectionName(source) {
|
|
11
11
|
return `source-${createHash("sha256").update(source).digest("hex").slice(0, 12)}`;
|
|
12
12
|
}
|
|
13
|
+
/** Whether a `relative()` result escapes its base directory. */
|
|
14
|
+
function escapes(relativePath) {
|
|
15
|
+
return relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath);
|
|
16
|
+
}
|
|
13
17
|
function assertWorkspaceSourceHasNoSymlinkRoot(workspaceDir, configuredPath, root) {
|
|
14
18
|
if (isAbsolute(expandHome(configuredPath)))
|
|
15
19
|
return;
|
|
16
20
|
const workspace = resolve(workspaceDir);
|
|
17
|
-
|
|
18
|
-
if (rootRelative === ".." || rootRelative.startsWith(`..${sep}`) || isAbsolute(rootRelative)) {
|
|
21
|
+
if (escapes(relative(workspace, root)))
|
|
19
22
|
return;
|
|
20
|
-
}
|
|
21
23
|
let current = root;
|
|
22
24
|
while (current !== workspace) {
|
|
23
25
|
if (existsSync(current) && lstatSync(current).isSymbolicLink()) {
|
|
@@ -32,25 +34,12 @@ function assertWorkspaceSourceHasNoSymlinkRoot(workspaceDir, configuredPath, roo
|
|
|
32
34
|
export function resolveSource(workspaceDir, configuredPath, corpus = "memory") {
|
|
33
35
|
const expanded = expandHome(configuredPath);
|
|
34
36
|
const absolute = isAbsolute(expanded) ? resolve(expanded) : resolve(workspaceDir, expanded);
|
|
35
|
-
|
|
36
|
-
const stat = statSync(absolute);
|
|
37
|
-
const root = stat.isDirectory() ? absolute : dirname(absolute);
|
|
38
|
-
const pattern = stat.isDirectory() ? "**/*.md" : basename(absolute);
|
|
39
|
-
assertWorkspaceSourceHasNoSymlinkRoot(workspaceDir, configuredPath, root);
|
|
40
|
-
return {
|
|
41
|
-
collection: collectionName(absolute),
|
|
42
|
-
corpus,
|
|
43
|
-
configuredPath,
|
|
44
|
-
kind: "files",
|
|
45
|
-
root,
|
|
46
|
-
pattern,
|
|
47
|
-
watchPath: absolute,
|
|
48
|
-
};
|
|
49
|
-
}
|
|
37
|
+
const exists = existsSync(absolute);
|
|
50
38
|
const magicIndex = absolute.search(GLOB_MAGIC);
|
|
51
|
-
if (magicIndex < 0) {
|
|
52
|
-
|
|
53
|
-
const
|
|
39
|
+
if (exists || magicIndex < 0) {
|
|
40
|
+
// An existing path is taken literally; a missing one is a file only when it names Markdown.
|
|
41
|
+
const isFile = exists ? !statSync(absolute).isDirectory() : basename(absolute).toLowerCase().endsWith(".md");
|
|
42
|
+
const root = isFile ? dirname(absolute) : absolute;
|
|
54
43
|
assertWorkspaceSourceHasNoSymlinkRoot(workspaceDir, configuredPath, root);
|
|
55
44
|
return {
|
|
56
45
|
collection: collectionName(absolute),
|
|
@@ -58,7 +47,7 @@ export function resolveSource(workspaceDir, configuredPath, corpus = "memory") {
|
|
|
58
47
|
configuredPath,
|
|
59
48
|
kind: "files",
|
|
60
49
|
root,
|
|
61
|
-
pattern:
|
|
50
|
+
pattern: isFile ? basename(absolute) : "**/*.md",
|
|
62
51
|
watchPath: absolute,
|
|
63
52
|
};
|
|
64
53
|
}
|
|
@@ -110,21 +99,14 @@ export function resolveConfiguredSkillPath(workspaceDir, inputPath, sources) {
|
|
|
110
99
|
catch {
|
|
111
100
|
return undefined;
|
|
112
101
|
}
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const relativePath = relative(source.root, target);
|
|
117
|
-
if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || isAbsolute(relativePath))
|
|
118
|
-
continue;
|
|
119
|
-
if (picomatch.isMatch(relativePath.split(sep).join("/"), source.pattern, { dot: true }))
|
|
120
|
-
return canonicalTarget;
|
|
121
|
-
}
|
|
122
|
-
return undefined;
|
|
102
|
+
return sources.some((source) => source.kind === "skills" && sourceMatchesPath(source, target))
|
|
103
|
+
? canonicalTarget
|
|
104
|
+
: undefined;
|
|
123
105
|
}
|
|
124
106
|
export function sourceMatchesPath(source, inputPath) {
|
|
125
107
|
const target = resolve(inputPath);
|
|
126
108
|
const relativePath = relative(source.root, target);
|
|
127
|
-
if (
|
|
109
|
+
if (escapes(relativePath))
|
|
128
110
|
return false;
|
|
129
111
|
return picomatch.isMatch(relativePath.split(sep).join("/"), source.pattern, { dot: true });
|
|
130
112
|
}
|
|
@@ -140,16 +122,14 @@ export function parseSafeVirtualPath(virtualPath, sources) {
|
|
|
140
122
|
if (!picomatch.isMatch(portableRelativePath, source.pattern, { dot: true }))
|
|
141
123
|
return undefined;
|
|
142
124
|
const target = resolve(source.root, relativePath);
|
|
143
|
-
if (relative(source.root, target)
|
|
125
|
+
if (escapes(relative(source.root, target)))
|
|
144
126
|
return undefined;
|
|
145
|
-
}
|
|
146
127
|
if (!target.toLowerCase().endsWith(".md"))
|
|
147
128
|
return undefined;
|
|
148
129
|
try {
|
|
149
130
|
const realRoot = realpathSync(source.root);
|
|
150
131
|
const realTarget = realpathSync(target);
|
|
151
|
-
|
|
152
|
-
if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))
|
|
132
|
+
if (escapes(relative(realRoot, realTarget)))
|
|
153
133
|
return undefined;
|
|
154
134
|
}
|
|
155
135
|
catch {
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import type { OpenClawConfig, OpenClawPluginToolContext } from "openclaw/plugin-sdk/plugin-entry";
|
|
2
2
|
import type { MemoryRequestContext } from "./contracts.js";
|
|
3
|
+
/** The freshest config the host offers for this tool call. */
|
|
4
|
+
export declare function runtimeConfig(ctx: OpenClawPluginToolContext): OpenClawConfig | undefined;
|
|
3
5
|
export declare function getContext(ctx: OpenClawPluginToolContext): {
|
|
4
6
|
cfg: OpenClawConfig;
|
|
5
7
|
agentId: string;
|
package/dist/src/tool-context.js
CHANGED
|
@@ -1,5 +1,9 @@
|
|
|
1
|
+
/** The freshest config the host offers for this tool call. */
|
|
2
|
+
export function runtimeConfig(ctx) {
|
|
3
|
+
return ctx.getRuntimeConfig?.() ?? ctx.runtimeConfig ?? ctx.config;
|
|
4
|
+
}
|
|
1
5
|
export function getContext(ctx) {
|
|
2
|
-
const cfg = ctx
|
|
6
|
+
const cfg = runtimeConfig(ctx);
|
|
3
7
|
if (!cfg || !ctx.agentId)
|
|
4
8
|
return undefined;
|
|
5
9
|
return {
|
|
@@ -13,7 +13,6 @@ type Row = {
|
|
|
13
13
|
eventJson: string;
|
|
14
14
|
createdAt: number;
|
|
15
15
|
};
|
|
16
|
-
export declare const trainingHash: (value: unknown) => string;
|
|
17
16
|
/** The following answer establishes eligibility, but is never part of that example's input. */
|
|
18
17
|
export declare function trainingExamples(rows: Iterable<Row>, renew?: () => void): {
|
|
19
18
|
examples: TrainingExample[];
|
|
@@ -1,15 +1,12 @@
|
|
|
1
|
-
import { createHash } from "node:crypto";
|
|
2
1
|
import { DatabaseSync } from "node:sqlite";
|
|
3
2
|
import { AgentTranscriptReader } from "./agent-transcript.js";
|
|
4
3
|
import { messageText } from "./whisperer-context.js";
|
|
5
4
|
import { conversationUserText } from "./response-text.js";
|
|
6
5
|
import { prepareQueryConversation, QUERY_CONTRACT, QueryInputBudgetError } from "./query-contract.js";
|
|
6
|
+
import { jsonHash } from "./json-hash.js";
|
|
7
|
+
import { record } from "./guards.js";
|
|
7
8
|
// Window/tokenizer changes must never reuse a previous recipe's checkpoints.
|
|
8
9
|
export const TRAINING_PREPARATION = `${QUERY_CONTRACT.version}-visible-history-${QUERY_CONTRACT.revision}`;
|
|
9
|
-
export const trainingHash = (value) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
|
|
10
|
-
function record(value) {
|
|
11
|
-
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
|
|
12
|
-
}
|
|
13
10
|
/** The following answer establishes eligibility, but is never part of that example's input. */
|
|
14
11
|
export function trainingExamples(rows, renew) {
|
|
15
12
|
const examples = [];
|
|
@@ -98,7 +95,7 @@ export function trainingExamples(rows, renew) {
|
|
|
98
95
|
// A delayed database append must not move the historical retrieval boundary forward.
|
|
99
96
|
const timestamp = Number.isFinite(eventTime) ? Math.min(row.createdAt, eventTime) : row.createdAt;
|
|
100
97
|
pending = { seq: row.seq, timestamp, input,
|
|
101
|
-
inputHash:
|
|
98
|
+
inputHash: jsonHash([TRAINING_PREPARATION, input]), contextLimited };
|
|
102
99
|
remember("user", visible.text);
|
|
103
100
|
continue;
|
|
104
101
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { UnblockMemoryConfig } from "./config.js";
|
|
2
2
|
import type { QueryPair } from "./query-contract.js";
|
|
3
|
-
import {
|
|
3
|
+
import type { TrainingInput } from "./training-input.js";
|
|
4
4
|
import { historicalTrainingSearch } from "./training-retrieval.js";
|
|
5
5
|
import type { QueryEvaluation, TrainingStore } from "./training-store.js";
|
|
6
6
|
type Source = {
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { collectTraining } from "./training.js";
|
|
2
|
-
import { trainingHash } from "./training-input.js";
|
|
3
2
|
import { TRAINING_GATE_THRESHOLD } from "./training-gate.js";
|
|
4
3
|
import { resolveTypeSafeApiKey, TypeSafeRequestError } from "./typesafe-client.js";
|
|
5
4
|
import { trainingTeacher, trainingTeacherMessage, trainingTeacherPrompt, TRAINING_TEACHER_MODEL, TRAINING_TEACHER_VERSION } from "./training-models.js";
|
|
6
|
-
import {
|
|
5
|
+
import { historicalTrainingSource, HistoricalCorpusUnavailableError, TRAINING_RETRIEVAL_VERSION, TRAINING_SEARCH_OPTIONS } from "./training-retrieval.js";
|
|
7
6
|
import { contextJudgeRequest, judgeTrainingPassage, CONTEXT_JUDGE_VERSION } from "./training-judge.js";
|
|
7
|
+
import { jsonHash } from "./json-hash.js";
|
|
8
8
|
const LANES = ["lex", "vec"];
|
|
9
9
|
const SELECTION_VERSION = "independent-lanes-top3-mean-v2";
|
|
10
10
|
const TARGET_POLICY = "best-per-lane-no-minimum-v1";
|
|
@@ -154,7 +154,7 @@ export function selectTrainingQueries(queries) {
|
|
|
154
154
|
};
|
|
155
155
|
return { lex: winner("lex"), vec: winner("vec") };
|
|
156
156
|
}
|
|
157
|
-
export async function evaluateTrainingQueries(source, store, config, runtime, options, createSearch
|
|
157
|
+
export async function evaluateTrainingQueries(source, store, config, runtime, options, createSearch) {
|
|
158
158
|
bounds(options);
|
|
159
159
|
const corpus = config.corpora.find(c => c.kind === "sessions");
|
|
160
160
|
if (!corpus)
|
|
@@ -215,9 +215,10 @@ export async function evaluateTrainingQueries(source, store, config, runtime, op
|
|
|
215
215
|
store.renew();
|
|
216
216
|
let snapshot;
|
|
217
217
|
try {
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
218
|
+
// By default one source capture serves the whole run; an injected search owns its own capture.
|
|
219
|
+
snapshot = createSearch
|
|
220
|
+
? await createSearch(source.stateDir, corpus.chatTypes, example.timestamp)
|
|
221
|
+
: await (await (historicalSource ??= historicalTrainingSource(source.stateDir, corpus.chatTypes)))(example.timestamp);
|
|
221
222
|
}
|
|
222
223
|
catch (error) {
|
|
223
224
|
if (!(error instanceof HistoricalCorpusUnavailableError))
|
|
@@ -251,7 +252,7 @@ export async function evaluateTrainingQueries(source, store, config, runtime, op
|
|
|
251
252
|
const problems = new Set();
|
|
252
253
|
const judge = (hit) => {
|
|
253
254
|
const request = contextJudgeRequest(input, snapshot.maxDate, hit);
|
|
254
|
-
const identity =
|
|
255
|
+
const identity = jsonHash([CONTEXT_JUDGE_VERSION, request]);
|
|
255
256
|
let pending = judgments.get(identity);
|
|
256
257
|
if (!pending) {
|
|
257
258
|
pending = (async () => {
|
|
@@ -415,7 +416,7 @@ export function* exportQueryTraining(store, threshold = TRAINING_GATE_THRESHOLD)
|
|
|
415
416
|
const provenance = [...evaluation.teacherIds, ...evaluation.queries.flatMap(q => [q.retrievalId, ...q.judgments])];
|
|
416
417
|
yield { stage: "query-training", input: JSON.parse(source.inputJson), inputHash: source.inputHash,
|
|
417
418
|
recallProbability: source.recallProbability, threshold, target: selected, targetPolicy: TARGET_POLICY,
|
|
418
|
-
source: store.sourceDetails(source.id), evaluation: { ...evaluation, selected, review: [] }, splitGroup:
|
|
419
|
+
source: store.sourceDetails(source.id), evaluation: { ...evaluation, selected, review: [] }, splitGroup: jsonHash(source.sessionId),
|
|
419
420
|
provenance: [...new Set(provenance)].map(id => store.stepRecord(id)) };
|
|
420
421
|
}
|
|
421
422
|
}
|
|
@@ -3,7 +3,7 @@ import { statSync } from "node:fs";
|
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { createRequire } from "node:module";
|
|
5
5
|
import { setImmediate as yieldToEventLoop } from "node:timers/promises";
|
|
6
|
-
import { readSessionManifest } from "./session-sync.js";
|
|
6
|
+
import { projectionHash, readSessionManifest } from "./session-sync.js";
|
|
7
7
|
import { resolveSessionSource } from "./sources.js";
|
|
8
8
|
import { trainingCandidates } from "./training-candidates.js";
|
|
9
9
|
import { MEMORY_PASSAGE_VERSION, renderMemoryPassage, duplicateMemoryPassage } from "./memory-passage.js";
|
|
@@ -98,7 +98,7 @@ export async function historicalTrainingSource(stateDir, chatTypes) {
|
|
|
98
98
|
continue;
|
|
99
99
|
}
|
|
100
100
|
const row = document.get(source.collection, session.documentPath);
|
|
101
|
-
if (!row ||
|
|
101
|
+
if (!row || projectionHash(row.doc) !== session.projectionHash) {
|
|
102
102
|
excluded++;
|
|
103
103
|
continue;
|
|
104
104
|
}
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import { existsSync, openSync, writeSync, closeSync } from "node:fs";
|
|
2
2
|
import { join, resolve } from "node:path";
|
|
3
|
-
import { resolveAgentDir, resolveStateDir } from "openclaw/plugin-sdk/memory-core-host-engine-foundation";
|
|
4
3
|
import { listAgentIds } from "openclaw/plugin-sdk/agent-runtime";
|
|
5
4
|
import { normalizeAgentIdStrict } from "openclaw/plugin-sdk/routing";
|
|
6
5
|
import { TrainingStore } from "./training-store.js";
|
|
@@ -8,6 +7,7 @@ import { TRAINING_GATE_THRESHOLD } from "./training-gate.js";
|
|
|
8
7
|
import { collectTraining, runTraining } from "./training.js";
|
|
9
8
|
import { generateTrainingQueries, evaluateTrainingQueries, exportQueryTraining, TRAINING_EVALUATION_CONCURRENCY } from "./training-queries.js";
|
|
10
9
|
import { dateOption } from "./date-option.js";
|
|
10
|
+
import { agentStateDir, agentTranscriptDatabase } from "./agent-paths.js";
|
|
11
11
|
function thresholdOption(value) {
|
|
12
12
|
const result = Number(value);
|
|
13
13
|
if (!value.trim() || !Number.isFinite(result) || result < 0 || result > 1)
|
|
@@ -21,8 +21,8 @@ export function registerMemoryTraining(api, config) {
|
|
|
21
21
|
if (!normalized.ok || !listAgentIds(cfg).includes(normalized.value))
|
|
22
22
|
throw new Error("Unknown memory-training agent");
|
|
23
23
|
const agentId = normalized.value;
|
|
24
|
-
const stateDir =
|
|
25
|
-
return { agentId, databasePath:
|
|
24
|
+
const stateDir = agentStateDir(agentId);
|
|
25
|
+
return { agentId, databasePath: agentTranscriptDatabase(cfg, agentId),
|
|
26
26
|
stateDir, storePath: join(stateDir, "training.sqlite") };
|
|
27
27
|
};
|
|
28
28
|
api.registerCli(({ program, config: cfg }) => {
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { openMemoryDatabase } from "./memory-database.js";
|
|
3
|
-
import {
|
|
2
|
+
import { immediateTransaction, openMemoryDatabase } from "./memory-database.js";
|
|
3
|
+
import { TRAINING_PREPARATION } from "./training-input.js";
|
|
4
4
|
import { TRAINING_GATE_MODEL, TRAINING_GATE_THRESHOLD, TRAINING_GATE_VERSION } from "./training-gate.js";
|
|
5
5
|
import { TRAINING_RECIPE_VERSION } from "./training-models.js";
|
|
6
|
+
import { jsonHash } from "./json-hash.js";
|
|
6
7
|
const LEASE_MS = 120_000;
|
|
7
8
|
export class TrainingStore {
|
|
8
9
|
#db;
|
|
@@ -65,25 +66,13 @@ export class TrainingStore {
|
|
|
65
66
|
throw error;
|
|
66
67
|
}
|
|
67
68
|
}
|
|
68
|
-
#transaction(fn) {
|
|
69
|
-
this.#db.exec("BEGIN IMMEDIATE");
|
|
70
|
-
try {
|
|
71
|
-
const result = fn();
|
|
72
|
-
this.#db.exec("COMMIT");
|
|
73
|
-
return result;
|
|
74
|
-
}
|
|
75
|
-
catch (error) {
|
|
76
|
-
this.#db.exec("ROLLBACK");
|
|
77
|
-
throw error;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
69
|
#checkLease() {
|
|
81
70
|
const lease = this.#db.prepare("SELECT owner,expires FROM training_lock WHERE singleton=1").get();
|
|
82
71
|
if (lease?.owner !== this.#owner || Number(lease.expires) <= Date.now())
|
|
83
72
|
throw new Error("Training lease lost; no further API requests permitted");
|
|
84
73
|
}
|
|
85
74
|
async locked(fn) {
|
|
86
|
-
this.#
|
|
75
|
+
immediateTransaction(this.#db, () => {
|
|
87
76
|
const lock = this.#db.prepare(`INSERT INTO training_lock VALUES (1,?,?) ON CONFLICT(singleton)
|
|
88
77
|
DO UPDATE SET owner=excluded.owner,expires=excluded.expires WHERE training_lock.expires<=?`)
|
|
89
78
|
.run(this.#owner, Date.now() + LEASE_MS, Date.now());
|
|
@@ -122,14 +111,14 @@ export class TrainingStore {
|
|
|
122
111
|
}
|
|
123
112
|
}
|
|
124
113
|
renew() {
|
|
125
|
-
this.#
|
|
114
|
+
immediateTransaction(this.#db, () => {
|
|
126
115
|
this.#checkLease();
|
|
127
116
|
this.#db.prepare("UPDATE training_lock SET expires=? WHERE owner=?").run(Date.now() + LEASE_MS, this.#owner);
|
|
128
117
|
});
|
|
129
118
|
}
|
|
130
119
|
sessions() { return this.#db.prepare("SELECT DISTINCT session_id FROM training_examples").all().map(r => String(r.session_id)); }
|
|
131
120
|
syncSession(sessionId, examples, since, until, existingOnly) {
|
|
132
|
-
return this.#
|
|
121
|
+
return immediateTransaction(this.#db, () => {
|
|
133
122
|
this.#checkLease();
|
|
134
123
|
const previous = new Map(this.#db.prepare("SELECT event_seq,input_hash,active FROM training_examples WHERE session_id=?").all(sessionId)
|
|
135
124
|
.map(row => [Number(row.event_seq), row]));
|
|
@@ -148,8 +137,8 @@ export class TrainingStore {
|
|
|
148
137
|
continue;
|
|
149
138
|
retained.add(example.seq);
|
|
150
139
|
input.run(example.inputHash, TRAINING_PREPARATION, JSON.stringify(example.input));
|
|
151
|
-
source.run(
|
|
152
|
-
const id =
|
|
140
|
+
source.run(jsonHash([this.#nodeId, this.#agentId, sessionId, example.seq]), sessionId, example.seq, example.timestamp, example.inputHash, Number(example.contextLimited));
|
|
141
|
+
const id = jsonHash([example.inputHash, TRAINING_GATE_VERSION, TRAINING_GATE_MODEL]);
|
|
153
142
|
gate.run(id, example.inputHash, TRAINING_GATE_VERSION, TRAINING_GATE_MODEL);
|
|
154
143
|
if (!old)
|
|
155
144
|
counts.added++;
|
|
@@ -177,7 +166,7 @@ export class TrainingStore {
|
|
|
177
166
|
.all(TRAINING_GATE_VERSION, TRAINING_GATE_MODEL, TRAINING_PREPARATION, limit ?? -1);
|
|
178
167
|
}
|
|
179
168
|
start(id) {
|
|
180
|
-
return this.#
|
|
169
|
+
return immediateTransaction(this.#db, () => {
|
|
181
170
|
this.#checkLease();
|
|
182
171
|
if (!this.#db.prepare("UPDATE training_gates SET status='attempted',error=NULL WHERE id=? AND status='pending'").run(id).changes) {
|
|
183
172
|
throw new Error("Training gate is not pending");
|
|
@@ -187,7 +176,7 @@ export class TrainingStore {
|
|
|
187
176
|
});
|
|
188
177
|
}
|
|
189
178
|
finish(id, attempt, result) {
|
|
190
|
-
this.#
|
|
179
|
+
immediateTransaction(this.#db, () => {
|
|
191
180
|
this.#checkLease();
|
|
192
181
|
const ok = "probability" in result;
|
|
193
182
|
const status = ok ? "complete" : result.status, error = ok ? null : result.error;
|
|
@@ -201,7 +190,7 @@ export class TrainingStore {
|
|
|
201
190
|
if (!ids.length || ids.some(id => !/^[a-f0-9]{64}$/u.test(id)))
|
|
202
191
|
throw new Error("Specify exact training gate or step hashes to retry");
|
|
203
192
|
this.#checkLease();
|
|
204
|
-
return this.#
|
|
193
|
+
return immediateTransaction(this.#db, () => ids.reduce((count, id) => {
|
|
205
194
|
const statuses = includeAmbiguous ? "('failed','ambiguous')" : "('failed')";
|
|
206
195
|
const gates = this.#db.prepare(`UPDATE training_gates SET status='pending',error=NULL WHERE id=?
|
|
207
196
|
AND prompt_version=? AND requested_model=? AND status IN ${statuses}
|
|
@@ -224,7 +213,7 @@ export class TrainingStore {
|
|
|
224
213
|
}
|
|
225
214
|
step(stage, parameters) {
|
|
226
215
|
const request = { ...parameters, recipe: TRAINING_RECIPE_VERSION };
|
|
227
|
-
const id =
|
|
216
|
+
const id = jsonHash([stage, request]);
|
|
228
217
|
const row = this.#db.prepare("SELECT status,result_json FROM training_steps WHERE id=? AND stage=?").get(id, stage);
|
|
229
218
|
return { id, stage, request, status: (row?.status ?? "pending"),
|
|
230
219
|
result: row?.status === "complete" ? JSON.parse(String(row.result_json)) : undefined };
|
|
@@ -250,7 +239,7 @@ export class TrainingStore {
|
|
|
250
239
|
reason: String(row.reason), details: JSON.parse(String(row.details)), updatedAt: Number(row.updatedAt) }));
|
|
251
240
|
}
|
|
252
241
|
startStep(stage, id, request) {
|
|
253
|
-
return this.#
|
|
242
|
+
return immediateTransaction(this.#db, () => {
|
|
254
243
|
this.#checkLease();
|
|
255
244
|
this.#db.prepare("INSERT OR IGNORE INTO training_steps (id,stage,request_json,status) VALUES (?,?,?,'pending')")
|
|
256
245
|
.run(id, stage, JSON.stringify(request));
|
|
@@ -262,7 +251,7 @@ export class TrainingStore {
|
|
|
262
251
|
});
|
|
263
252
|
}
|
|
264
253
|
finishStep(stage, id, attempt, outcome) {
|
|
265
|
-
this.#
|
|
254
|
+
immediateTransaction(this.#db, () => {
|
|
266
255
|
this.#checkLease();
|
|
267
256
|
const ok = "result" in outcome, status = ok ? "complete" : outcome.status;
|
|
268
257
|
const json = ok ? JSON.stringify(outcome.result) : null, error = ok ? null : outcome.error;
|
|
@@ -5,6 +5,12 @@ export declare const TYPESAFE_NOUL_SCHEMA: Type.TObject<{
|
|
|
5
5
|
type: Type.TLiteral<"noul">;
|
|
6
6
|
noul: Type.TNumber;
|
|
7
7
|
}>;
|
|
8
|
+
export declare const TYPESAFE_NOUL_ANSWERS_SCHEMA: Type.TObject<{
|
|
9
|
+
answers: Type.TRecord<"^.*$", Type.TObject<{
|
|
10
|
+
type: Type.TLiteral<"noul">;
|
|
11
|
+
noul: Type.TNumber;
|
|
12
|
+
}>>;
|
|
13
|
+
}>;
|
|
8
14
|
/** A conservative estimate of serialized size, not Jev's tokenizer. Non-ASCII is budgeted separately. */
|
|
9
15
|
export declare function estimateJevTokens(value: unknown): number;
|
|
10
16
|
export declare class TypeSafeRequestError extends Error {
|
|
@@ -12,6 +18,8 @@ export declare class TypeSafeRequestError extends Error {
|
|
|
12
18
|
readonly status?: number | undefined;
|
|
13
19
|
constructor(message: string, code: "timeout" | "cancelled" | "http_error" | "invalid_response" | "network_error", status?: number | undefined);
|
|
14
20
|
}
|
|
21
|
+
/** A TypeSafe deadline: the request's own timeout, or the caller's timed-out signal. */
|
|
22
|
+
export declare function isTypeSafeTimeout(error: unknown, signal: AbortSignal): boolean;
|
|
15
23
|
/** Explicit credentials take precedence; a missing explicit file never selects another key. */
|
|
16
24
|
export declare function resolveTypeSafeApiKey(config: UnblockMemoryConfig["typesafe"]): Promise<string | undefined>;
|
|
17
25
|
/** One TypeSafe request. The caller owns the response schema and failure policy. */
|
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import { readFile } from "node:fs/promises";
|
|
2
2
|
import { parseEnv } from "node:util";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
|
+
import { abortedByTimeout } from "./abortable.js";
|
|
4
5
|
export const TYPESAFE_MODEL = "jev-1.13.0";
|
|
5
6
|
export const TYPESAFE_NOUL_SCHEMA = Type.Object({
|
|
6
7
|
type: Type.Literal("noul"), noul: Type.Number({ minimum: 0, maximum: 1 }),
|
|
7
8
|
});
|
|
9
|
+
export const TYPESAFE_NOUL_ANSWERS_SCHEMA = Type.Object({ answers: Type.Record(Type.String(), TYPESAFE_NOUL_SCHEMA) });
|
|
8
10
|
/** A conservative estimate of serialized size, not Jev's tokenizer. Non-ASCII is budgeted separately. */
|
|
9
11
|
export function estimateJevTokens(value) {
|
|
10
12
|
let n = 0;
|
|
@@ -21,6 +23,10 @@ export class TypeSafeRequestError extends Error {
|
|
|
21
23
|
this.status = status;
|
|
22
24
|
}
|
|
23
25
|
}
|
|
26
|
+
/** A TypeSafe deadline: the request's own timeout, or the caller's timed-out signal. */
|
|
27
|
+
export function isTypeSafeTimeout(error, signal) {
|
|
28
|
+
return (error instanceof TypeSafeRequestError && error.code === "timeout") || abortedByTimeout(signal);
|
|
29
|
+
}
|
|
24
30
|
/** Explicit credentials take precedence; a missing explicit file never selects another key. */
|
|
25
31
|
export async function resolveTypeSafeApiKey(config) {
|
|
26
32
|
if (!config.enabled)
|
|
@@ -78,7 +84,7 @@ export async function requestTypeSafe(params, state, questions) {
|
|
|
78
84
|
if (error instanceof TypeSafeRequestError)
|
|
79
85
|
throw error;
|
|
80
86
|
if (signal?.aborted) {
|
|
81
|
-
const timedOut = signal
|
|
87
|
+
const timedOut = abortedByTimeout(signal);
|
|
82
88
|
throw new TypeSafeRequestError(timedOut ? "TypeSafe request timed out" : "TypeSafe request cancelled", timedOut ? "timeout" : "cancelled");
|
|
83
89
|
}
|
|
84
90
|
throw new TypeSafeRequestError("TypeSafe request failed", "network_error");
|
|
@@ -3,7 +3,6 @@ type RequestOptions = {
|
|
|
3
3
|
timeoutMs: number;
|
|
4
4
|
signal: AbortSignal;
|
|
5
5
|
};
|
|
6
|
-
export { TYPESAFE_MODEL as TYPESAFE_REVIEW_MODEL } from "./typesafe-client.js";
|
|
7
6
|
/** The source is an indexed snapshot, not proof of current truth or permission to write. */
|
|
8
7
|
export declare function reviewTypeSafeClaim(params: RequestOptions & {
|
|
9
8
|
claim: string;
|
|
@@ -46,3 +45,4 @@ export declare function reviewClusterDefects(params: RequestOptions & {
|
|
|
46
45
|
defect: "encoding" | "wrapper" | "boilerplate" | "none_or_uncertain";
|
|
47
46
|
confidence: number;
|
|
48
47
|
}[]>;
|
|
48
|
+
export {};
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import { Value } from "typebox/value";
|
|
3
3
|
import { backgroundWordCount, PEOPLE_BACKGROUND_MAX_WORDS } from "./people-background.js";
|
|
4
|
-
import { requestTypeSafe, TYPESAFE_NOUL_SCHEMA } from "./typesafe-client.js";
|
|
5
|
-
export { TYPESAFE_MODEL as TYPESAFE_REVIEW_MODEL } from "./typesafe-client.js";
|
|
4
|
+
import { requestTypeSafe, TYPESAFE_NOUL_ANSWERS_SCHEMA as nouls, TYPESAFE_NOUL_SCHEMA } from "./typesafe-client.js";
|
|
6
5
|
const relationSchema = Type.Object({ answers: Type.Object({ relation: Type.Object({
|
|
7
6
|
type: Type.Literal("choice"),
|
|
8
7
|
choice: Type.Union([Type.Literal("supports"), Type.Literal("contradicts"), Type.Literal("insufficient_evidence")]),
|
|
@@ -73,7 +72,6 @@ export async function reviewTypeSafeClaim(params) {
|
|
|
73
72
|
needsReview: answer.choice !== "supports" || answer.confidence < 0.9 ||
|
|
74
73
|
(background !== undefined && (background.backgroundOnly < 0.9 || background.explicitSupport < 0.9)) };
|
|
75
74
|
}
|
|
76
|
-
const nouls = Type.Object({ answers: Type.Record(Type.String(), TYPESAFE_NOUL_SCHEMA) });
|
|
77
75
|
/** Directional coverage, not topic similarity. Bounded at six comparisons of four ranked candidates. */
|
|
78
76
|
export async function reviewMemoryRedundancy(params) {
|
|
79
77
|
if (params.excerpts.length > 4)
|
package/dist/src/typesafe.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
2
|
import { Value } from "typebox/value";
|
|
3
|
-
import { requestTypeSafe, TypeSafeRequestError, TYPESAFE_MODEL, TYPESAFE_NOUL_SCHEMA } from "./typesafe-client.js";
|
|
3
|
+
import { requestTypeSafe, TypeSafeRequestError, TYPESAFE_MODEL, TYPESAFE_NOUL_ANSWERS_SCHEMA, TYPESAFE_NOUL_SCHEMA } from "./typesafe-client.js";
|
|
4
4
|
import { MEMORY_PASSAGE_CHARS } from "./memory-passage.js";
|
|
5
5
|
const SKILL_MIN_USEFULNESS = 0.7;
|
|
6
6
|
/** Select from trusted candidates; never accept a provider-generated path or skill name. */
|
|
@@ -46,14 +46,11 @@ async function judgeTypeSafeSkill(params) {
|
|
|
46
46
|
criteria: { true: "This skill's specific workflow materially helps with the actual requested work.",
|
|
47
47
|
false: "The workflow is unnecessary, inapplicable, excluded by its description, or only topically related." },
|
|
48
48
|
} });
|
|
49
|
-
if (!Value.Check(
|
|
49
|
+
if (!Value.Check(TYPESAFE_NOUL_ANSWERS_SCHEMA, payload) || Object.keys(payload.answers).length !== 1 || !payload.answers.useful)
|
|
50
50
|
throw new TypeSafeRequestError("TypeSafe returned an invalid selection", "invalid_response");
|
|
51
51
|
return payload.answers.useful.noul;
|
|
52
52
|
}
|
|
53
|
-
const
|
|
54
|
-
answers: Type.Record(Type.String(), TYPESAFE_NOUL_SCHEMA),
|
|
55
|
-
});
|
|
56
|
-
export const QUALITY_JUDGE_VERSION = "jev-1.13.0:quality-v3-isolated";
|
|
53
|
+
export const QUALITY_JUDGE_VERSION = `${TYPESAFE_MODEL}:quality-v3-isolated`;
|
|
57
54
|
/** These are indicators for review, never authorization to delete or rewrite. */
|
|
58
55
|
export async function judgeTypeSafeQuality(params) {
|
|
59
56
|
if (!params.chunks.length)
|
|
@@ -94,7 +91,7 @@ export async function judgeTypeSafeQuality(params) {
|
|
|
94
91
|
};
|
|
95
92
|
let payload;
|
|
96
93
|
payload = await requestTypeSafe({ apiKey: params.apiKey, signal: params.signal, timeoutMs: params.timeoutMs }, { chunks: [chunk] }, questions);
|
|
97
|
-
if (!Value.Check(
|
|
94
|
+
if (!Value.Check(TYPESAFE_NOUL_ANSWERS_SCHEMA, payload) ||
|
|
98
95
|
Object.keys(payload.answers).length !== Object.keys(questions).length ||
|
|
99
96
|
Object.keys(questions).some(key => !Object.hasOwn(payload.answers, key))) {
|
|
100
97
|
throw new Error("TypeSafe returned invalid quality judgments");
|
package/docs/configuration.md
CHANGED
|
@@ -11,7 +11,7 @@ settings; a rotated credential file is reread without a restart.
|
|
|
11
11
|
|
|
12
12
|
| Feature | Required settings/dependencies | TypeSafe disabled / no key | Provider or unreadable-key failure |
|
|
13
13
|
| --- | --- | --- | --- |
|
|
14
|
-
| `memory_search` | Installed/enabled memory slot; configured corpora
|
|
14
|
+
| `memory_search` | Installed/enabled memory slot; configured corpora | Local retrieval-ranked leads with degraded warning | Successful judged siblings returned with a partial warning; total judging failure or unreadable key uses local retrieval fallback |
|
|
15
15
|
| `memory_get` | Installed/enabled memory slot; configured corpora | Unchanged local indexed reads | Unchanged; its own indexing errors still matter |
|
|
16
16
|
| Skill Whisperer | `skillWhisperer.enabled`, skills corpus, host hooks | Best local vector candidate meeting `minScore` | Exclude failed candidates; successful siblings may qualify; no vector fallback |
|
|
17
17
|
| Memory Whisperer | `memoryWhisperer.enabled`, explicit approved corpora, host hooks | No hints | Exclude failed candidates; recall/deadline failures still suppress the turn |
|