dsh-memsys 0.2.0 → 0.2.2
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 +11 -5
- package/client.js +115 -24
- package/index.mjs +77 -25
- package/package.json +2 -2
- package/src/context/compile.mjs +6 -5
- package/src/context/delivery.mjs +1 -1
- package/src/context/snapshots.mjs +10 -2
- package/src/read/get.mjs +57 -6
- package/src/runtime/inject-round.mjs +138 -0
- package/src/runtime/inject.mjs +12 -3
- package/src/runtime/modules.mjs +20 -0
- package/src/runtime/summary.mjs +70 -90
- package/src/runtime/tools.mjs +21 -4
- package/src/runtime/ui-config.mjs +176 -0
- package/test/p4-p4-delivery.test.mjs +7 -1
- package/test/p6-c1c4.test.mjs +69 -0
- package/test/p6-c3-append.test.mjs +85 -0
- package/test/p6-inject-round.test.mjs +76 -0
- package/test/p6-modules.test.mjs +77 -0
- package/test/p6-ui-summary.test.mjs +368 -110
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { resolveConfig } from '../config.mjs';
|
|
2
|
+
import { openAll } from '../storage/open.mjs';
|
|
3
|
+
import { migrateAll } from '../storage/migrate.mjs';
|
|
4
|
+
import { systemClock } from '../clock.mjs';
|
|
5
|
+
import { withImmediate } from '../storage/open.mjs';
|
|
6
|
+
|
|
7
|
+
const TOOLS_ONLY_TEXT = '[memsys] 注入:tools-only(未取得宿主预算与回执,不作逐轮交付承诺)';
|
|
8
|
+
|
|
9
|
+
function sessionIdOf(turn) {
|
|
10
|
+
return turn?.session?.header?.id ?? turn?.sessionId ?? turn?.session?.id ?? null;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Runtime bridge between session turn events and the compile pipeline.
|
|
15
|
+
* Subscription is owned here (not the section), so a new turn refreshes text
|
|
16
|
+
* before the next prompt section read; no reply receipt means delivery=unknown.
|
|
17
|
+
*/
|
|
18
|
+
export function createRoundInjector({
|
|
19
|
+
ctx = null,
|
|
20
|
+
dataDir,
|
|
21
|
+
modules = null,
|
|
22
|
+
compileRound,
|
|
23
|
+
tokenizer = null,
|
|
24
|
+
H = null,
|
|
25
|
+
mode = 'work',
|
|
26
|
+
clock = systemClock,
|
|
27
|
+
logger = console,
|
|
28
|
+
handles = null,
|
|
29
|
+
} = {}) {
|
|
30
|
+
const ownedHandles = !handles;
|
|
31
|
+
const stores = handles ?? openAll(resolveConfig({ dataDir }));
|
|
32
|
+
if (ownedHandles) migrateAll(stores, { clock });
|
|
33
|
+
let state = {
|
|
34
|
+
text: '',
|
|
35
|
+
delivery: 'unknown',
|
|
36
|
+
delivery_level: 'empty',
|
|
37
|
+
manifest: null,
|
|
38
|
+
sessionId: null,
|
|
39
|
+
roundId: null,
|
|
40
|
+
refreshed_at: null,
|
|
41
|
+
};
|
|
42
|
+
let counter = 0;
|
|
43
|
+
let disposed = false;
|
|
44
|
+
|
|
45
|
+
const disabled = modules?.context === false;
|
|
46
|
+
|
|
47
|
+
function recordInjections(roundId, manifest) {
|
|
48
|
+
const ids = manifest?.eligible_ids ?? [];
|
|
49
|
+
if (!ids.length) return;
|
|
50
|
+
const at = clock.at().at;
|
|
51
|
+
withImmediate(stores.main, () => {
|
|
52
|
+
for (const memoryId of ids) {
|
|
53
|
+
stores.main
|
|
54
|
+
.prepare('INSERT OR IGNORE INTO injections (round_id, memory_id, slots, topic_hits, manifest_hash, receipt_id, at) VALUES (?, ?, ?, 0, ?, NULL, ?)')
|
|
55
|
+
.run(roundId, memoryId, JSON.stringify(['context']), manifest?.manifest_hash ?? null, at);
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function refresh(turn = {}) {
|
|
61
|
+
if (disposed) return state;
|
|
62
|
+
if (disabled) {
|
|
63
|
+
state = { text: '', delivery: 'unknown', delivery_level: 'disabled', manifest: null, sessionId: sessionIdOf(turn), roundId: null, refreshed_at: clock.at().at };
|
|
64
|
+
return state;
|
|
65
|
+
}
|
|
66
|
+
const sessionId = sessionIdOf(turn) ?? state.sessionId;
|
|
67
|
+
counter += 1;
|
|
68
|
+
const roundId = turn?.id ?? turn?.roundId ?? `turn-${counter}`;
|
|
69
|
+
let result;
|
|
70
|
+
try {
|
|
71
|
+
result = compileRound({
|
|
72
|
+
main: stores.main,
|
|
73
|
+
control: stores.control,
|
|
74
|
+
clock,
|
|
75
|
+
sessionId: sessionId ?? 'unknown-session',
|
|
76
|
+
roundId,
|
|
77
|
+
mode,
|
|
78
|
+
tokenizer,
|
|
79
|
+
H,
|
|
80
|
+
modules,
|
|
81
|
+
});
|
|
82
|
+
} catch (err) {
|
|
83
|
+
logger?.warn?.('[dsh-memsys] compile failed: ' + err.message);
|
|
84
|
+
result = null;
|
|
85
|
+
}
|
|
86
|
+
if (!result || result.delivery_level === 'unavailable') {
|
|
87
|
+
state = {
|
|
88
|
+
text: TOOLS_ONLY_TEXT,
|
|
89
|
+
delivery: 'unknown',
|
|
90
|
+
delivery_level: 'unavailable',
|
|
91
|
+
manifest: result?.manifest ?? null,
|
|
92
|
+
sessionId,
|
|
93
|
+
roundId,
|
|
94
|
+
refreshed_at: clock.at().at,
|
|
95
|
+
};
|
|
96
|
+
return state;
|
|
97
|
+
}
|
|
98
|
+
const text = result.section?.text ?? result.sectionText ?? '';
|
|
99
|
+
state = {
|
|
100
|
+
text,
|
|
101
|
+
delivery: 'unknown',
|
|
102
|
+
delivery_level: result.delivery_level,
|
|
103
|
+
manifest: result.manifest ?? null,
|
|
104
|
+
sessionId,
|
|
105
|
+
roundId,
|
|
106
|
+
refreshed_at: clock.at().at,
|
|
107
|
+
};
|
|
108
|
+
recordInjections(roundId, state.manifest);
|
|
109
|
+
return state;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function onSessionEvent(payload) {
|
|
113
|
+
const event = payload?.event ?? payload;
|
|
114
|
+
const type = event?.type ?? event?.name ?? event?.kind ?? null;
|
|
115
|
+
if (type !== 'turn/start') return;
|
|
116
|
+
refresh(payload?.turn ?? event?.turn ?? payload ?? {});
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (!disabled && typeof ctx?.on === 'function') {
|
|
120
|
+
ctx.on('session/event', onSessionEvent);
|
|
121
|
+
ctx.on('turn/start', (payload) => refresh(payload ?? {}));
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return {
|
|
125
|
+
refresh,
|
|
126
|
+
current: () => state,
|
|
127
|
+
dispose() {
|
|
128
|
+
disposed = true;
|
|
129
|
+
try {
|
|
130
|
+
if (typeof ctx?.off === 'function') {
|
|
131
|
+
ctx.off('session/event', onSessionEvent);
|
|
132
|
+
}
|
|
133
|
+
} catch {
|
|
134
|
+
// disposal must not throw
|
|
135
|
+
}
|
|
136
|
+
},
|
|
137
|
+
};
|
|
138
|
+
}
|
package/src/runtime/inject.mjs
CHANGED
|
@@ -7,8 +7,11 @@ export const SECTION_ORDER = 500;
|
|
|
7
7
|
* The only verified injection call shape (probe-p0):
|
|
8
8
|
* ctx.inject(['systemPrompt'], c => c.systemPrompt.section({name, order, text}))
|
|
9
9
|
* Static `export const inject` would leave the plugin pending forever.
|
|
10
|
+
*
|
|
11
|
+
* `dynamicText: true` registers the resolver itself so the host re-reads it per
|
|
12
|
+
* assembly; the default keeps the historical one-shot string.
|
|
10
13
|
*/
|
|
11
|
-
export function registerSection(ctx, { getText, diagnosticMarker = null } = {}) {
|
|
14
|
+
export function registerSection(ctx, { getText, diagnosticMarker = null, dynamicText = false } = {}) {
|
|
12
15
|
if (!ctx || typeof ctx.inject !== 'function') {
|
|
13
16
|
const err = new Error('invalid_ctx');
|
|
14
17
|
err.code = 'invalid_ctx';
|
|
@@ -20,7 +23,12 @@ export function registerSection(ctx, { getText, diagnosticMarker = null } = {})
|
|
|
20
23
|
err.code = 'system_prompt_unavailable';
|
|
21
24
|
throw err;
|
|
22
25
|
}
|
|
23
|
-
const
|
|
26
|
+
const resolve = () => (typeof getText === 'function' ? getText() : String(getText ?? ''));
|
|
27
|
+
// Dynamic text stays a function: the host re-evaluates it on every
|
|
28
|
+
// `systemPrompt.assemble()`, i.e. once per model step (verified on a probe
|
|
29
|
+
// profile: two assemblies produced probe-1 then probe-2). A static string
|
|
30
|
+
// would freeze the first round forever.
|
|
31
|
+
const text = dynamicText ? resolve : resolve();
|
|
24
32
|
c.systemPrompt.section({ name: SECTION_NAME, order: SECTION_ORDER, text });
|
|
25
33
|
if (diagnosticMarker) {
|
|
26
34
|
fs.writeFileSync(
|
|
@@ -29,7 +37,8 @@ export function registerSection(ctx, { getText, diagnosticMarker = null } = {})
|
|
|
29
37
|
{
|
|
30
38
|
name: SECTION_NAME,
|
|
31
39
|
order: SECTION_ORDER,
|
|
32
|
-
text_length: String(
|
|
40
|
+
text_length: String(resolve()).length,
|
|
41
|
+
dynamic: dynamicText === true,
|
|
33
42
|
registered_at: new Date().toISOString(),
|
|
34
43
|
},
|
|
35
44
|
null,
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Core gate facade. The single merge/persistence source is ui-config.mjs;
|
|
3
|
+
* this file must never re-implement it.
|
|
4
|
+
*/
|
|
5
|
+
export {
|
|
6
|
+
DEFAULT_MODULES,
|
|
7
|
+
MODULE_KEYS,
|
|
8
|
+
moduleEnabled,
|
|
9
|
+
readUiConfig,
|
|
10
|
+
resolveModules,
|
|
11
|
+
resolveModulesDetail,
|
|
12
|
+
writeUiConfig,
|
|
13
|
+
} from './ui-config.mjs';
|
|
14
|
+
|
|
15
|
+
import { resolveModulesDetail } from './ui-config.mjs';
|
|
16
|
+
|
|
17
|
+
/** Resolve the effective gate set for one plugin instance. */
|
|
18
|
+
export function modulesFor({ dataDir = null, config = null, logger = console } = {}) {
|
|
19
|
+
return resolveModulesDetail({ dataDir, profileConfig: config, logger }).modules;
|
|
20
|
+
}
|
package/src/runtime/summary.mjs
CHANGED
|
@@ -1,105 +1,48 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Host side of the optional Web UI (sidebar panel + settings section).
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
4
|
+
* Read-only over SQLite, plus the module switches read through `ui-config.mjs`
|
|
5
|
+
* (the same source the host gates use). Both routes enforce loopback +
|
|
6
|
+
* same-origin before touching data; nothing here is model-facing.
|
|
7
7
|
*/
|
|
8
|
-
import
|
|
9
|
-
|
|
8
|
+
import {
|
|
9
|
+
DEFAULT_MODULES,
|
|
10
|
+
MODULE_KEYS,
|
|
11
|
+
readUiConfig,
|
|
12
|
+
resolveModulesDetail,
|
|
13
|
+
writeUiConfig,
|
|
14
|
+
} from './ui-config.mjs';
|
|
10
15
|
|
|
11
|
-
const UI_CONFIG_FILE = 'ui-config.json';
|
|
12
|
-
const UI_CONFIG_VERSION = 1;
|
|
13
16
|
const RECENT_LIMIT = 5;
|
|
14
|
-
|
|
17
|
+
// 主人要求:卡片展示 120 字(按码点截断,预算保护仍在 host 侧)
|
|
18
|
+
const TEXT_LIMIT = 120;
|
|
15
19
|
const BODY_LIMIT = 4096;
|
|
16
20
|
|
|
17
|
-
const warn = (logger, message) => {
|
|
18
|
-
try {
|
|
19
|
-
logger?.warn?.(`[dsh-memsys] ${message}`);
|
|
20
|
-
} catch {
|
|
21
|
-
// a logger that throws must never break boot
|
|
22
|
-
}
|
|
23
|
-
};
|
|
24
|
-
|
|
25
|
-
/**
|
|
26
|
-
* Read the settings file written by the Web switch.
|
|
27
|
-
* Returns `{ auto_inject }` or `null` when absent. A corrupt or foreign-version
|
|
28
|
-
* file is ignored with one warning: a bad file must never stop the plugin.
|
|
29
|
-
*/
|
|
30
|
-
export function readUiConfig(dataDir, logger = console) {
|
|
31
|
-
if (!dataDir) return null;
|
|
32
|
-
const file = path.join(dataDir, UI_CONFIG_FILE);
|
|
33
|
-
let raw = null;
|
|
34
|
-
try {
|
|
35
|
-
if (!fs.existsSync(file)) return null;
|
|
36
|
-
raw = fs.readFileSync(file, 'utf8');
|
|
37
|
-
} catch (err) {
|
|
38
|
-
warn(logger, `ui-config 读取失败(${err?.message ?? err}),回落 profile 配置`);
|
|
39
|
-
return null;
|
|
40
|
-
}
|
|
41
|
-
let parsed = null;
|
|
42
|
-
try {
|
|
43
|
-
parsed = JSON.parse(raw);
|
|
44
|
-
} catch {
|
|
45
|
-
warn(logger, 'ui-config 不是合法 JSON,回落 profile 配置');
|
|
46
|
-
return null;
|
|
47
|
-
}
|
|
48
|
-
if (parsed?.version !== UI_CONFIG_VERSION) {
|
|
49
|
-
warn(logger, `ui-config 版本不符(${parsed?.version ?? 'none'},期望 ${UI_CONFIG_VERSION}),已忽略`);
|
|
50
|
-
return null;
|
|
51
|
-
}
|
|
52
|
-
if (typeof parsed?.auto_inject !== 'boolean') {
|
|
53
|
-
warn(logger, 'ui-config 缺少 auto_inject 布尔值,已忽略');
|
|
54
|
-
return null;
|
|
55
|
-
}
|
|
56
|
-
return { auto_inject: parsed.auto_inject };
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Priority: ui-config.json (when present and valid) > profile patch value > false.
|
|
61
|
-
* The reported `source` is what the Web page shows next to the switch.
|
|
62
|
-
*/
|
|
63
|
-
export function resolveAutoInject({ dataDir = null, profileValue = undefined, logger = console } = {}) {
|
|
64
|
-
const stored = readUiConfig(dataDir, logger);
|
|
65
|
-
if (stored !== null) return { value: stored.auto_inject, source: 'ui-config' };
|
|
66
|
-
if (typeof profileValue === 'boolean') return { value: profileValue, source: 'profile' };
|
|
67
|
-
return { value: false, source: 'default' };
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
/** Write-through with a temp file so a crash never leaves half a config. */
|
|
71
|
-
export function writeUiConfig(dataDir, autoInject) {
|
|
72
|
-
if (!dataDir) return false;
|
|
73
|
-
fs.mkdirSync(dataDir, { recursive: true });
|
|
74
|
-
const target = path.join(dataDir, UI_CONFIG_FILE);
|
|
75
|
-
const temp = `${target}.tmp`;
|
|
76
|
-
fs.writeFileSync(
|
|
77
|
-
temp,
|
|
78
|
-
JSON.stringify({ version: UI_CONFIG_VERSION, auto_inject: autoInject === true }, null, 2),
|
|
79
|
-
'utf8',
|
|
80
|
-
);
|
|
81
|
-
fs.renameSync(temp, target);
|
|
82
|
-
return true;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
21
|
const truncate = (text) => Array.from(String(text ?? '')).slice(0, TEXT_LIMIT).join('');
|
|
86
22
|
|
|
87
|
-
/** Three counts
|
|
88
|
-
export function buildSummary(
|
|
23
|
+
/** Three counts, the five latest memories, and the effective module map. */
|
|
24
|
+
export function buildSummary(
|
|
25
|
+
main,
|
|
26
|
+
{ dataDir = null, modules = DEFAULT_MODULES, modulesSource = 'default', autoInject = undefined } = {},
|
|
27
|
+
) {
|
|
89
28
|
const db = typeof main === 'function' ? main() : main;
|
|
90
29
|
const one = (sql, ...params) => Number(db.prepare(sql).get(...params)?.n ?? 0);
|
|
91
30
|
const recent = db
|
|
92
31
|
.prepare('SELECT id, text FROM memories ORDER BY recorded_at DESC, id DESC LIMIT ?')
|
|
93
32
|
.all(RECENT_LIMIT)
|
|
94
33
|
.map((row) => ({ id: row.id, text: truncate(row.text) }));
|
|
34
|
+
const effective = {};
|
|
35
|
+
for (const key of MODULE_KEYS) effective[key] = modules?.[key] !== false;
|
|
95
36
|
return {
|
|
96
37
|
memories: one('SELECT COUNT(*) AS n FROM memories'),
|
|
97
38
|
candidates: one("SELECT COUNT(*) AS n FROM candidates WHERE status IN ('pending', 'conflicted')"),
|
|
98
39
|
pending_due: one("SELECT COUNT(*) AS n FROM memories WHERE due_state = 'pending-due'"),
|
|
99
40
|
recent,
|
|
100
41
|
data_dir: dataDir,
|
|
101
|
-
auto_inject: autoInject === true,
|
|
102
|
-
auto_inject_source:
|
|
42
|
+
auto_inject: autoInject === undefined ? effective.context : autoInject === true,
|
|
43
|
+
auto_inject_source: modulesSource,
|
|
44
|
+
modules: effective,
|
|
45
|
+
modules_source: modulesSource,
|
|
103
46
|
};
|
|
104
47
|
}
|
|
105
48
|
|
|
@@ -128,8 +71,8 @@ export function sameOrigin(req) {
|
|
|
128
71
|
export function createSummaryHandler({
|
|
129
72
|
main,
|
|
130
73
|
dataDir = null,
|
|
131
|
-
|
|
132
|
-
|
|
74
|
+
getConfig = () => ({ modules: DEFAULT_MODULES, source: 'default' }),
|
|
75
|
+
onConfig = null,
|
|
133
76
|
} = {}) {
|
|
134
77
|
const send = (res, status, payload) => {
|
|
135
78
|
res.statusCode = status;
|
|
@@ -138,6 +81,16 @@ export function createSummaryHandler({
|
|
|
138
81
|
res.end(JSON.stringify(payload));
|
|
139
82
|
};
|
|
140
83
|
|
|
84
|
+
const snapshot = () => {
|
|
85
|
+
const current = getConfig() ?? {};
|
|
86
|
+
const modules = current.modules ?? DEFAULT_MODULES;
|
|
87
|
+
return {
|
|
88
|
+
modules,
|
|
89
|
+
source: current.source ?? 'default',
|
|
90
|
+
auto_inject: modules?.context !== false,
|
|
91
|
+
};
|
|
92
|
+
};
|
|
93
|
+
|
|
141
94
|
return (req, res) => {
|
|
142
95
|
if (!isLoopback(req) || !sameOrigin(req)) {
|
|
143
96
|
send(res, 403, { error: 'forbidden' });
|
|
@@ -168,13 +121,31 @@ export function createSummaryHandler({
|
|
|
168
121
|
send(res, 400, { error: 'invalid_json' });
|
|
169
122
|
return;
|
|
170
123
|
}
|
|
171
|
-
|
|
172
|
-
|
|
124
|
+
const wantsModules = parsed?.modules && typeof parsed.modules === 'object';
|
|
125
|
+
const wantsAutoInject = typeof parsed?.auto_inject === 'boolean';
|
|
126
|
+
if (!wantsModules && !wantsAutoInject) {
|
|
127
|
+
send(res, 400, { error: 'config_required' });
|
|
173
128
|
return;
|
|
174
129
|
}
|
|
130
|
+
if (wantsModules) {
|
|
131
|
+
const bad = Object.keys(parsed.modules).filter(
|
|
132
|
+
(key) => MODULE_KEYS.includes(key) && typeof parsed.modules[key] !== 'boolean',
|
|
133
|
+
);
|
|
134
|
+
if (bad.length > 0) {
|
|
135
|
+
send(res, 400, { error: 'module_value_not_boolean', keys: bad });
|
|
136
|
+
return;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
175
139
|
try {
|
|
176
|
-
|
|
177
|
-
|
|
140
|
+
const written = onConfig?.({ ...parsed }) ?? null;
|
|
141
|
+
const next = written ?? snapshot();
|
|
142
|
+
send(res, 200, {
|
|
143
|
+
ok: true,
|
|
144
|
+
auto_inject: next.auto_inject,
|
|
145
|
+
auto_inject_source: 'ui-config',
|
|
146
|
+
modules: next.modules,
|
|
147
|
+
modules_source: 'ui-config',
|
|
148
|
+
});
|
|
178
149
|
} catch (err) {
|
|
179
150
|
send(res, 500, { error: 'write_failed', message: String(err?.message ?? err) });
|
|
180
151
|
}
|
|
@@ -186,12 +157,21 @@ export function createSummaryHandler({
|
|
|
186
157
|
return;
|
|
187
158
|
}
|
|
188
159
|
try {
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
160
|
+
const state = snapshot();
|
|
161
|
+
send(
|
|
162
|
+
res,
|
|
163
|
+
200,
|
|
164
|
+
buildSummary(main, {
|
|
165
|
+
dataDir,
|
|
166
|
+
modules: state.modules,
|
|
167
|
+
modulesSource: state.source,
|
|
168
|
+
autoInject: state.auto_inject,
|
|
169
|
+
}),
|
|
170
|
+
);
|
|
193
171
|
} catch (err) {
|
|
194
172
|
send(res, 503, { error: 'summary_unavailable', message: String(err?.code ?? err?.message ?? err) });
|
|
195
173
|
}
|
|
196
174
|
};
|
|
197
175
|
}
|
|
176
|
+
|
|
177
|
+
export { readUiConfig, resolveModulesDetail, writeUiConfig };
|
package/src/runtime/tools.mjs
CHANGED
|
@@ -246,8 +246,22 @@ function textRender(value) {
|
|
|
246
246
|
}
|
|
247
247
|
|
|
248
248
|
/** Plain tool objects before the host wraps them with defineTool. */
|
|
249
|
-
export function
|
|
250
|
-
|
|
249
|
+
export function enabledToolNames(modules = null) {
|
|
250
|
+
const enabled = modules ?? { context: true, read: true, write: true, dream: true, projects: true, due: true, feed: true };
|
|
251
|
+
return MEMSYS_TOOLS.filter((name) => {
|
|
252
|
+
if (['memsys_get', 'memsys_search', 'memsys_review_get', 'memsys_context_get', 'memsys_self_get'].includes(name)) {
|
|
253
|
+
return enabled.read !== false;
|
|
254
|
+
}
|
|
255
|
+
if (name === 'memsys_project_get') return enabled.read !== false && enabled.projects !== false;
|
|
256
|
+
if (['memsys_dream_record', 'memsys_organize'].includes(name)) return enabled.dream !== false;
|
|
257
|
+
if (name === 'memsys_feed') return enabled.feed !== false;
|
|
258
|
+
if (name === 'memsys_record') return true; // registered but call-gated for an explicit module_disabled
|
|
259
|
+
return true;
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export function toolDefinitions(handlers = {}, modules = null) {
|
|
264
|
+
return enabledToolNames(modules).map((name) => {
|
|
251
265
|
const spec = TOOL_SPECS[name];
|
|
252
266
|
return {
|
|
253
267
|
name,
|
|
@@ -255,6 +269,9 @@ export function toolDefinitions(handlers = {}) {
|
|
|
255
269
|
parameters: spec.parameters,
|
|
256
270
|
outputSchema: TOOL_OUTPUT_SCHEMAS[name] ?? openObject(),
|
|
257
271
|
async execute(args, exec) {
|
|
272
|
+
if (name === 'memsys_record' && modules?.write === false) {
|
|
273
|
+
return { status: 'error', code: 'module_disabled', module: 'write' };
|
|
274
|
+
}
|
|
258
275
|
const handler = handlers[name];
|
|
259
276
|
if (typeof handler !== 'function') {
|
|
260
277
|
return { status: 'error', code: 'handler_unavailable', tool: name };
|
|
@@ -292,7 +309,7 @@ export function toolCapabilityStatus(liveReport = null) {
|
|
|
292
309
|
* Register against a host ctx. No ctx.tools -> tools-only, no throw.
|
|
293
310
|
* `defineTool` is resolved dynamically so offline tests never need the host package.
|
|
294
311
|
*/
|
|
295
|
-
export async function registerHostTools({ ctx = null, handlers = {}, defineTool: injectedDefineTool = null } = {}) {
|
|
312
|
+
export async function registerHostTools({ ctx = null, handlers = {}, modules = null, defineTool: injectedDefineTool = null } = {}) {
|
|
296
313
|
if (!ctx || !ctx.tools || typeof ctx.tools.register !== 'function') {
|
|
297
314
|
return { status: 'tools_only', registered: [], reason: 'no_tools_service', defineTool: null, tools: [...MEMSYS_TOOLS] };
|
|
298
315
|
}
|
|
@@ -313,7 +330,7 @@ export async function registerHostTools({ ctx = null, handlers = {}, defineTool:
|
|
|
313
330
|
}
|
|
314
331
|
const registered = [];
|
|
315
332
|
const errors = [];
|
|
316
|
-
for (const spec of toolDefinitions(handlers)) {
|
|
333
|
+
for (const spec of toolDefinitions(handlers, modules)) {
|
|
317
334
|
try {
|
|
318
335
|
const tool = defineTool({
|
|
319
336
|
name: spec.name,
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The single source of truth for module switches.
|
|
3
|
+
*
|
|
4
|
+
* Both halves read this file: the Web data route (`src/runtime/summary.mjs`) and
|
|
5
|
+
* the host-side gates (`src/runtime/modules.mjs` re-exports from here). Nothing
|
|
6
|
+
* else may re-implement the merge — a second copy is how the switch becomes a
|
|
7
|
+
* lie.
|
|
8
|
+
*
|
|
9
|
+
* Priority: `<data_dir>/ui-config.json` > profile patch config > default (true).
|
|
10
|
+
*/
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
|
|
14
|
+
export const UI_CONFIG_FILE = 'ui-config.json';
|
|
15
|
+
export const UI_CONFIG_VERSION = 2;
|
|
16
|
+
export const MODULE_KEYS = Object.freeze(['context', 'read', 'write', 'dream', 'projects', 'due', 'feed']);
|
|
17
|
+
export const DEFAULT_MODULES = Object.freeze({
|
|
18
|
+
context: true,
|
|
19
|
+
read: true,
|
|
20
|
+
write: true,
|
|
21
|
+
dream: true,
|
|
22
|
+
projects: true,
|
|
23
|
+
due: true,
|
|
24
|
+
feed: true,
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
const warn = (logger, message) => {
|
|
28
|
+
try {
|
|
29
|
+
logger?.warn?.(`[dsh-memsys] ${message}`);
|
|
30
|
+
} catch {
|
|
31
|
+
// a logger that throws must never break boot
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
|
|
35
|
+
/** Missing keys mean `true`; only an explicit `false` disables a module. */
|
|
36
|
+
export function normalizeModules(input = {}) {
|
|
37
|
+
const modules = { ...DEFAULT_MODULES };
|
|
38
|
+
if (input && typeof input === 'object') {
|
|
39
|
+
for (const key of MODULE_KEYS) {
|
|
40
|
+
if (typeof input[key] === 'boolean') modules[key] = input[key];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return modules;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* v2 is `{ version: 2, auto_inject, modules }`.
|
|
48
|
+
* v1 (or versionless) files only carry `auto_inject`; they migrate by mapping it
|
|
49
|
+
* onto `modules.context` while every other module stays on.
|
|
50
|
+
*/
|
|
51
|
+
export function normalizeUiConfig(parsed, logger = console) {
|
|
52
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;
|
|
53
|
+
const version = parsed.version;
|
|
54
|
+
const known = version === undefined || version === 1 || version === UI_CONFIG_VERSION;
|
|
55
|
+
if (!known) {
|
|
56
|
+
warn(logger, `ui-config 版本不认识(${version}),已忽略`);
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const hasModules = parsed.modules && typeof parsed.modules === 'object';
|
|
60
|
+
if (version === undefined && typeof parsed.auto_inject !== 'boolean' && !hasModules) {
|
|
61
|
+
warn(logger, 'ui-config 既无 auto_inject 也无 modules,已忽略');
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
const modules = normalizeModules(hasModules ? parsed.modules : {});
|
|
65
|
+
if (!hasModules && typeof parsed.auto_inject === 'boolean') modules.context = parsed.auto_inject;
|
|
66
|
+
return {
|
|
67
|
+
version: UI_CONFIG_VERSION,
|
|
68
|
+
auto_inject: modules.context,
|
|
69
|
+
modules,
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function readUiConfig(dataDir, logger = console) {
|
|
74
|
+
if (!dataDir) return null;
|
|
75
|
+
const file = path.join(dataDir, UI_CONFIG_FILE);
|
|
76
|
+
let raw = null;
|
|
77
|
+
try {
|
|
78
|
+
if (!fs.existsSync(file)) return null;
|
|
79
|
+
raw = fs.readFileSync(file, 'utf8');
|
|
80
|
+
} catch (err) {
|
|
81
|
+
warn(logger, `ui-config 读取失败(${err?.message ?? err}),回落 profile 配置`);
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
try {
|
|
85
|
+
return normalizeUiConfig(JSON.parse(raw), logger);
|
|
86
|
+
} catch {
|
|
87
|
+
warn(logger, 'ui-config 不是合法 JSON,回落 profile 配置');
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Pure merge used by every caller: defaults <- profile config <- ui-config.
|
|
94
|
+
* A legacy `auto_inject` fills `modules.context` only when that source says
|
|
95
|
+
* nothing about `modules` at all.
|
|
96
|
+
*/
|
|
97
|
+
export function mergeModules(profileConfig = null, uiConfig = null) {
|
|
98
|
+
const base = { ...DEFAULT_MODULES };
|
|
99
|
+
const apply = (source) => {
|
|
100
|
+
if (!source || typeof source !== 'object') return;
|
|
101
|
+
const modules = source.modules;
|
|
102
|
+
if (modules && typeof modules === 'object') {
|
|
103
|
+
for (const key of MODULE_KEYS) {
|
|
104
|
+
if (typeof modules[key] === 'boolean') base[key] = modules[key];
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (typeof source.auto_inject === 'boolean' && modules?.context === undefined) {
|
|
108
|
+
base.context = source.auto_inject;
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
apply(profileConfig);
|
|
112
|
+
apply(uiConfig);
|
|
113
|
+
return base;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Kept under the name the host gates already import. */
|
|
117
|
+
export function resolveModules(profileConfig = null, uiConfig = null) {
|
|
118
|
+
return Object.freeze(mergeModules(profileConfig, uiConfig));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
export function moduleEnabled(modules, key) {
|
|
122
|
+
return (modules ?? DEFAULT_MODULES)[key] !== false;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
const profileSaysSomething = (profileConfig) =>
|
|
126
|
+
Boolean(
|
|
127
|
+
profileConfig &&
|
|
128
|
+
(profileConfig.modules && typeof profileConfig.modules === 'object'
|
|
129
|
+
? MODULE_KEYS.some((key) => typeof profileConfig.modules[key] === 'boolean')
|
|
130
|
+
: typeof profileConfig.auto_inject === 'boolean'),
|
|
131
|
+
);
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* Resolve for the Web route: returns the effective map plus which rank won,
|
|
135
|
+
* so the settings page can show where the value came from.
|
|
136
|
+
*/
|
|
137
|
+
export function resolveModulesDetail({ dataDir = null, profileConfig = null, logger = console } = {}) {
|
|
138
|
+
const stored = readUiConfig(dataDir, logger);
|
|
139
|
+
const modules = mergeModules(profileConfig, stored);
|
|
140
|
+
const source = stored ? 'ui-config' : profileSaysSomething(profileConfig) ? 'profile' : 'default';
|
|
141
|
+
return { modules, source, auto_inject: modules.context };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Partial update: sends only the keys it owns. A legacy `auto_inject` maps onto
|
|
146
|
+
* `modules.context`; sending `modules.context` mirrors back into `auto_inject`
|
|
147
|
+
* so v1 readers keep working.
|
|
148
|
+
*/
|
|
149
|
+
export function writeUiConfig(dataDir, patch = {}, logger = console) {
|
|
150
|
+
if (!dataDir) return null;
|
|
151
|
+
const current = readUiConfig(dataDir, logger) ?? {
|
|
152
|
+
version: UI_CONFIG_VERSION,
|
|
153
|
+
auto_inject: DEFAULT_MODULES.context,
|
|
154
|
+
modules: { ...DEFAULT_MODULES },
|
|
155
|
+
};
|
|
156
|
+
const next = { ...current.modules };
|
|
157
|
+
if (patch.modules && typeof patch.modules === 'object') {
|
|
158
|
+
for (const key of MODULE_KEYS) {
|
|
159
|
+
if (typeof patch.modules[key] === 'boolean') next[key] = patch.modules[key];
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
if (typeof patch.auto_inject === 'boolean' && patch.modules?.context === undefined) {
|
|
163
|
+
next.context = patch.auto_inject;
|
|
164
|
+
}
|
|
165
|
+
const normalized = {
|
|
166
|
+
version: UI_CONFIG_VERSION,
|
|
167
|
+
auto_inject: next.context,
|
|
168
|
+
modules: next,
|
|
169
|
+
};
|
|
170
|
+
fs.mkdirSync(dataDir, { recursive: true });
|
|
171
|
+
const target = path.join(dataDir, UI_CONFIG_FILE);
|
|
172
|
+
const temp = `${target}.tmp`;
|
|
173
|
+
fs.writeFileSync(temp, JSON.stringify(normalized, null, 2), 'utf8');
|
|
174
|
+
fs.renameSync(temp, target);
|
|
175
|
+
return normalized;
|
|
176
|
+
}
|
|
@@ -76,7 +76,13 @@ test('P4/P4-B E10: receipts must match the persistent manifest and groups', (t)
|
|
|
76
76
|
receivedIds: expected,
|
|
77
77
|
payloadHash,
|
|
78
78
|
});
|
|
79
|
-
|
|
79
|
+
if (compiled.manifest.actual_ids.filter((id) => id.startsWith('mem_')).length === 0) {
|
|
80
|
+
// Design §6.2c: an empty actual set can never be confirmed, even if the receipt equals it.
|
|
81
|
+
assert.equal(full.delivery, 'incomplete', JSON.stringify(full));
|
|
82
|
+
assert.equal(full.code, 'receipt_incomplete');
|
|
83
|
+
} else {
|
|
84
|
+
assert.equal(full.delivery, 'confirmed', JSON.stringify(full));
|
|
85
|
+
}
|
|
80
86
|
const exposure = ctx.main.prepare('SELECT memory_id FROM injections').all().map((row) => row.memory_id);
|
|
81
87
|
assert.equal(exposure.length, 0, 'deferred members must not produce exposure');
|
|
82
88
|
});
|