@deepmaid/maid-state-server 0.0.0-stage → 0.1.0-alpha.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/LICENSE +21 -0
- package/lib/cli.d.ts +14 -0
- package/lib/cli.js +233 -0
- package/lib/config.d.ts +45 -0
- package/lib/config.js +117 -0
- package/lib/index.d.ts +5 -0
- package/lib/index.js +5 -0
- package/lib/migrate.d.ts +51 -0
- package/lib/migrate.js +85 -0
- package/lib/server.d.ts +19 -0
- package/lib/server.js +39 -0
- package/package.json +45 -3
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 kenyonxu
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/lib/cli.d.ts
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
//#region src/cli.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* maid-state CLI(maid-state 阶段规格 §12):serve/status/events/import/export/diff/compensate。
|
|
4
|
+
* 只读子命令以 readOnly 形态开库(不取排他锁,可与运行中 server 共存);
|
|
5
|
+
* import/export 建立在写库上(独占);compensate 走 client mTLS(缺 note / 非有限数 /
|
|
6
|
+
* maid 越权非零退出)。
|
|
7
|
+
*/
|
|
8
|
+
interface CliIo {
|
|
9
|
+
stdout(text: string): void;
|
|
10
|
+
stderr(text: string): void;
|
|
11
|
+
}
|
|
12
|
+
declare function runCli(argv: readonly string[], io: CliIo): Promise<number>;
|
|
13
|
+
//#endregion
|
|
14
|
+
export { CliIo, runCli };
|
package/lib/cli.js
ADDED
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { loadClientConfig, loadServerConfig } from "./config.js";
|
|
3
|
+
import { startMaidStateServer } from "./server.js";
|
|
4
|
+
import { diffEmotionJson, exportEmotionJson, importEmotionJson } from "./migrate.js";
|
|
5
|
+
import { readFileSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { loadRegistry } from "@deepmaid/maid-identity/registry";
|
|
7
|
+
import { PROTOCOL_VERSION, StateHttpClient, newEventId, openAuthorityStore } from "@deepmaid/maid-state";
|
|
8
|
+
import { createEmotionConfigAuthority } from "@deepmaid/maid-emotion/config-authority";
|
|
9
|
+
//#region src/cli.ts
|
|
10
|
+
const HELP = `maid-state — DeepMaid 跨宿主状态服务 CLI
|
|
11
|
+
|
|
12
|
+
用法:
|
|
13
|
+
maid-state serve --config <server.yml> 前台运行权威服务(mTLS)
|
|
14
|
+
maid-state status --config <server.yml> 各 maid revision/配置版本概览
|
|
15
|
+
maid-state events --config <server.yml> [--maid <id>] [--after <revision>] [--limit <n>]
|
|
16
|
+
事件回执清单(只读)
|
|
17
|
+
maid-state import --config <server.yml> --from <state.json> 空库整份导入本机基线
|
|
18
|
+
maid-state export --config <server.yml> --out <export.json> 导出当前权威状态
|
|
19
|
+
maid-state diff --config <server.yml> --from <other.json> --out <diff.json>
|
|
20
|
+
工作机旧状态 vs server 差异报告
|
|
21
|
+
maid-state compensate --config <client.yml> --maid <id> --delta <dim=value>... --note <text>
|
|
22
|
+
人工补偿(显式 manual_compensation)
|
|
23
|
+
`;
|
|
24
|
+
function readJson(file) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
27
|
+
} catch (error) {
|
|
28
|
+
throw new Error(`cannot read JSON ${file} (${error.message})`, { cause: error });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
async function runCli(argv, io) {
|
|
32
|
+
const [command, ...rest] = argv;
|
|
33
|
+
if (command === void 0 || command === "--help" || command === "help") {
|
|
34
|
+
io.stdout(HELP);
|
|
35
|
+
return command === void 0 ? 1 : 0;
|
|
36
|
+
}
|
|
37
|
+
const flag = (name) => {
|
|
38
|
+
const index = rest.indexOf(name);
|
|
39
|
+
return index >= 0 && index + 1 < rest.length ? rest[index + 1] : void 0;
|
|
40
|
+
};
|
|
41
|
+
try {
|
|
42
|
+
switch (command) {
|
|
43
|
+
case "serve": {
|
|
44
|
+
const configFile = flag("--config");
|
|
45
|
+
if (configFile === void 0) throw new Error("serve requires --config <server.yml>");
|
|
46
|
+
const config = loadServerConfig(configFile);
|
|
47
|
+
const server = await startMaidStateServer(config, { warn: (m) => io.stderr(m) });
|
|
48
|
+
io.stdout(`maid-state server listening at ${server.url} (authority ${server.authorityId})\n`);
|
|
49
|
+
const shutdown = async () => {
|
|
50
|
+
io.stderr("maid-state: shutting down\n");
|
|
51
|
+
await server.close();
|
|
52
|
+
process.exit(0);
|
|
53
|
+
};
|
|
54
|
+
process.once("SIGINT", () => {
|
|
55
|
+
shutdown();
|
|
56
|
+
});
|
|
57
|
+
process.once("SIGTERM", () => {
|
|
58
|
+
shutdown();
|
|
59
|
+
});
|
|
60
|
+
return new Promise(() => {});
|
|
61
|
+
}
|
|
62
|
+
case "status": {
|
|
63
|
+
const config = loadServerConfig(required(flag("--config"), "--config"));
|
|
64
|
+
const store = openAuthorityStore({
|
|
65
|
+
dataDir: config.dataDir,
|
|
66
|
+
readOnly: true
|
|
67
|
+
});
|
|
68
|
+
try {
|
|
69
|
+
const registry = loadRegistry(config.presetRoots, {
|
|
70
|
+
packRoots: config.packRoots,
|
|
71
|
+
warn: () => {}
|
|
72
|
+
});
|
|
73
|
+
const authority = createEmotionConfigAuthority({
|
|
74
|
+
presetRoots: config.presetRoots,
|
|
75
|
+
identity: registry,
|
|
76
|
+
globals: config.emotion,
|
|
77
|
+
warn: () => {}
|
|
78
|
+
});
|
|
79
|
+
io.stdout(JSON.stringify({
|
|
80
|
+
authorityId: store.authorityId,
|
|
81
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
82
|
+
maids: Object.entries(store.exportStates()).map(([maidId, s]) => ({
|
|
83
|
+
maidId,
|
|
84
|
+
stateRevision: s.revision,
|
|
85
|
+
lastEffectiveAt: s.state.lastEffectiveAt,
|
|
86
|
+
configRevision: authority.get(maidId)?.configRevision ?? null
|
|
87
|
+
}))
|
|
88
|
+
}, null, 2) + "\n");
|
|
89
|
+
registry.dispose();
|
|
90
|
+
} finally {
|
|
91
|
+
store.close();
|
|
92
|
+
}
|
|
93
|
+
return 0;
|
|
94
|
+
}
|
|
95
|
+
case "events": {
|
|
96
|
+
const config = loadServerConfig(required(flag("--config"), "--config"));
|
|
97
|
+
const store = openAuthorityStore({
|
|
98
|
+
dataDir: config.dataDir,
|
|
99
|
+
readOnly: true
|
|
100
|
+
});
|
|
101
|
+
try {
|
|
102
|
+
const after = flag("--after");
|
|
103
|
+
const limit = flag("--limit");
|
|
104
|
+
const events = store.listEvents({
|
|
105
|
+
...flag("--maid") !== void 0 ? { maidId: flag("--maid") } : {},
|
|
106
|
+
...after !== void 0 ? { afterRevision: Number(after) } : {},
|
|
107
|
+
limit: limit !== void 0 ? Number(limit) : 100
|
|
108
|
+
});
|
|
109
|
+
io.stdout(JSON.stringify({ events }, null, 2) + "\n");
|
|
110
|
+
} finally {
|
|
111
|
+
store.close();
|
|
112
|
+
}
|
|
113
|
+
return 0;
|
|
114
|
+
}
|
|
115
|
+
case "import": {
|
|
116
|
+
const config = loadServerConfig(required(flag("--config"), "--config"));
|
|
117
|
+
const from = required(flag("--from"), "--from");
|
|
118
|
+
const registry = loadRegistry(config.presetRoots, {
|
|
119
|
+
packRoots: config.packRoots,
|
|
120
|
+
warn: () => {}
|
|
121
|
+
});
|
|
122
|
+
const authority = createEmotionConfigAuthority({
|
|
123
|
+
presetRoots: config.presetRoots,
|
|
124
|
+
identity: registry,
|
|
125
|
+
globals: config.emotion,
|
|
126
|
+
warn: () => {}
|
|
127
|
+
});
|
|
128
|
+
const store = openAuthorityStore({ dataDir: config.dataDir });
|
|
129
|
+
try {
|
|
130
|
+
const count = importEmotionJson(store, authority, readJson(from));
|
|
131
|
+
io.stdout(`imported ${count} maid(s) at revision 0\n`);
|
|
132
|
+
} finally {
|
|
133
|
+
store.close();
|
|
134
|
+
registry.dispose();
|
|
135
|
+
}
|
|
136
|
+
return 0;
|
|
137
|
+
}
|
|
138
|
+
case "export": {
|
|
139
|
+
const config = loadServerConfig(required(flag("--config"), "--config"));
|
|
140
|
+
const out = required(flag("--out"), "--out");
|
|
141
|
+
const store = openAuthorityStore({ dataDir: config.dataDir });
|
|
142
|
+
try {
|
|
143
|
+
writeFileSync(out, JSON.stringify(exportEmotionJson(store), null, 2) + "\n", "utf8");
|
|
144
|
+
io.stdout(`exported to ${out}\n`);
|
|
145
|
+
} finally {
|
|
146
|
+
store.close();
|
|
147
|
+
}
|
|
148
|
+
return 0;
|
|
149
|
+
}
|
|
150
|
+
case "diff": {
|
|
151
|
+
const config = loadServerConfig(required(flag("--config"), "--config"));
|
|
152
|
+
const from = required(flag("--from"), "--from");
|
|
153
|
+
const out = required(flag("--out"), "--out");
|
|
154
|
+
const store = openAuthorityStore({
|
|
155
|
+
dataDir: config.dataDir,
|
|
156
|
+
readOnly: true
|
|
157
|
+
});
|
|
158
|
+
try {
|
|
159
|
+
writeFileSync(out, JSON.stringify(diffEmotionJson(store, readJson(from)), null, 2) + "\n", "utf8");
|
|
160
|
+
io.stdout(`diff written to ${out}\n`);
|
|
161
|
+
} finally {
|
|
162
|
+
store.close();
|
|
163
|
+
}
|
|
164
|
+
return 0;
|
|
165
|
+
}
|
|
166
|
+
case "compensate": {
|
|
167
|
+
const config = loadClientConfig(required(flag("--config"), "--config"));
|
|
168
|
+
const maidId = required(flag("--maid"), "--maid");
|
|
169
|
+
const note = required(flag("--note"), "--note");
|
|
170
|
+
const deltas = {};
|
|
171
|
+
for (let i = 0; i < rest.length - 1; i++) if (rest[i] === "--delta") {
|
|
172
|
+
const token = rest[i + 1];
|
|
173
|
+
const eq = token.indexOf("=");
|
|
174
|
+
if (eq <= 0) throw new Error(`--delta expects <dim=value> (got '${token}')`);
|
|
175
|
+
const value = Number(token.slice(eq + 1));
|
|
176
|
+
if (!Number.isFinite(value)) throw new Error(`--delta value must be a finite number (got '${token.slice(eq + 1)}')`);
|
|
177
|
+
deltas[token.slice(0, eq)] = value;
|
|
178
|
+
}
|
|
179
|
+
if (Object.keys(deltas).length === 0) throw new Error("compensate requires at least one --delta <dim=value>");
|
|
180
|
+
const client = new StateHttpClient({
|
|
181
|
+
url: config.url,
|
|
182
|
+
hostId: config.hostId,
|
|
183
|
+
keyFile: config.keyFile,
|
|
184
|
+
certFile: config.certFile,
|
|
185
|
+
caFile: config.caFile,
|
|
186
|
+
serverFingerprint256: config.serverFingerprint256,
|
|
187
|
+
authorityId: config.authorityId
|
|
188
|
+
});
|
|
189
|
+
try {
|
|
190
|
+
const snapshot = await client.getSnapshot(maidId);
|
|
191
|
+
const receipt = await client.submit({
|
|
192
|
+
protocolVersion: PROTOCOL_VERSION,
|
|
193
|
+
eventId: newEventId(),
|
|
194
|
+
hostId: config.hostId,
|
|
195
|
+
maidId,
|
|
196
|
+
kind: "emotion.apply_deltas",
|
|
197
|
+
occurredAt: Date.now(),
|
|
198
|
+
sourceConfigRevision: snapshot.configRevision,
|
|
199
|
+
payload: {
|
|
200
|
+
deltas,
|
|
201
|
+
source: "manual_compensation",
|
|
202
|
+
note
|
|
203
|
+
}
|
|
204
|
+
});
|
|
205
|
+
if (receipt.status === "rejected") {
|
|
206
|
+
io.stderr(`compensate rejected: ${receipt.errorCode ?? "unknown"}\n`);
|
|
207
|
+
return 1;
|
|
208
|
+
}
|
|
209
|
+
io.stdout(`compensated ${maidId} (revision ${receipt.snapshot?.stateRevision ?? receipt.appliedRevision})\n`);
|
|
210
|
+
return 0;
|
|
211
|
+
} finally {
|
|
212
|
+
client.close();
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
default:
|
|
216
|
+
io.stderr(`unknown command '${command}'\n\n${HELP}`);
|
|
217
|
+
return 1;
|
|
218
|
+
}
|
|
219
|
+
} catch (error) {
|
|
220
|
+
io.stderr(`maid-state: ${error.message}\n`);
|
|
221
|
+
return 1;
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
function required(value, name) {
|
|
225
|
+
if (value === void 0) throw new Error(`${name} is required`);
|
|
226
|
+
return value;
|
|
227
|
+
}
|
|
228
|
+
if (process.argv[1] !== void 0 && process.argv[1].endsWith("cli.js")) runCli(process.argv.slice(2), {
|
|
229
|
+
stdout: (t) => process.stdout.write(t),
|
|
230
|
+
stderr: (t) => process.stderr.write(t)
|
|
231
|
+
}).then((code) => process.exit(code)).catch(() => process.exit(1));
|
|
232
|
+
//#endregion
|
|
233
|
+
export { runCli };
|
package/lib/config.d.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
//#region src/config.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* 独立进程配置(maid-state 阶段规格 §10.3/§12):server.yml / client.yml(compensate 用)。
|
|
4
|
+
* fail-loud 纪律:缺 TLS、重复 hostId、空 allowMaids、相对 dataDir、未知顶层键全部拒绝;
|
|
5
|
+
* emotion 四数值是权威结算参数,**必填显式声明**(权威不携带隐式缺省)。
|
|
6
|
+
*/
|
|
7
|
+
interface EmotionGlobalsConfig {
|
|
8
|
+
vectorHalfLifeMs: number;
|
|
9
|
+
moodHalfLifeMs: number;
|
|
10
|
+
trendBand: number;
|
|
11
|
+
timezone: string;
|
|
12
|
+
}
|
|
13
|
+
interface MaidStateServerConfig {
|
|
14
|
+
dataDir: string;
|
|
15
|
+
presetRoots: string[];
|
|
16
|
+
packRoots: string[];
|
|
17
|
+
emotion: EmotionGlobalsConfig;
|
|
18
|
+
listen: {
|
|
19
|
+
host: string;
|
|
20
|
+
port: number;
|
|
21
|
+
};
|
|
22
|
+
tls: {
|
|
23
|
+
keyFile: string;
|
|
24
|
+
certFile: string;
|
|
25
|
+
caFile: string;
|
|
26
|
+
};
|
|
27
|
+
clients: Array<{
|
|
28
|
+
hostId: string;
|
|
29
|
+
fingerprint256: string;
|
|
30
|
+
allowMaids?: string[];
|
|
31
|
+
}>;
|
|
32
|
+
}
|
|
33
|
+
interface MaidStateClientConfig {
|
|
34
|
+
url: string;
|
|
35
|
+
hostId: string;
|
|
36
|
+
keyFile: string;
|
|
37
|
+
certFile: string;
|
|
38
|
+
caFile: string;
|
|
39
|
+
serverFingerprint256: string;
|
|
40
|
+
authorityId: string;
|
|
41
|
+
}
|
|
42
|
+
declare function loadServerConfig(file: string): MaidStateServerConfig;
|
|
43
|
+
declare function loadClientConfig(file: string): MaidStateClientConfig;
|
|
44
|
+
//#endregion
|
|
45
|
+
export { EmotionGlobalsConfig, MaidStateClientConfig, MaidStateServerConfig, loadClientConfig, loadServerConfig };
|
package/lib/config.js
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { isAbsolute, resolve } from "node:path";
|
|
3
|
+
import { parse } from "yaml";
|
|
4
|
+
//#region src/config.ts
|
|
5
|
+
const SERVER_KEYS = /* @__PURE__ */ new Set([
|
|
6
|
+
"dataDir",
|
|
7
|
+
"presetRoots",
|
|
8
|
+
"packRoots",
|
|
9
|
+
"emotion",
|
|
10
|
+
"listen",
|
|
11
|
+
"tls",
|
|
12
|
+
"clients"
|
|
13
|
+
]);
|
|
14
|
+
const CLIENT_KEYS = /* @__PURE__ */ new Set([
|
|
15
|
+
"url",
|
|
16
|
+
"hostId",
|
|
17
|
+
"keyFile",
|
|
18
|
+
"certFile",
|
|
19
|
+
"caFile",
|
|
20
|
+
"serverFingerprint256",
|
|
21
|
+
"authorityId"
|
|
22
|
+
]);
|
|
23
|
+
function fail(where, message) {
|
|
24
|
+
throw new Error(`maid-state-server: ${where}: ${message}`);
|
|
25
|
+
}
|
|
26
|
+
function readYaml(file) {
|
|
27
|
+
let raw;
|
|
28
|
+
try {
|
|
29
|
+
raw = readFileSync(file, "utf8");
|
|
30
|
+
} catch (error) {
|
|
31
|
+
throw new Error(`maid-state-server: cannot read config ${file} (${error.message})`, { cause: error });
|
|
32
|
+
}
|
|
33
|
+
const parsed = parse(raw);
|
|
34
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) fail(file, "config must be a mapping");
|
|
35
|
+
return parsed;
|
|
36
|
+
}
|
|
37
|
+
function requireStrings(where, node, keys) {
|
|
38
|
+
for (const key of keys) if (typeof node[key] !== "string" || node[key].length === 0) fail(where, `${key} must be a non-empty string`);
|
|
39
|
+
}
|
|
40
|
+
function loadServerConfig(file) {
|
|
41
|
+
const raw = readYaml(file);
|
|
42
|
+
for (const key of Object.keys(raw)) if (!SERVER_KEYS.has(key)) fail(file, `unknown top-level key '${key}'`);
|
|
43
|
+
if (typeof raw.dataDir !== "string" || raw.dataDir.length === 0 || !isAbsolute(raw.dataDir)) fail(file, "dataDir must be an absolute path");
|
|
44
|
+
const dataDir = raw.dataDir;
|
|
45
|
+
const presetRoots = Array.isArray(raw.presetRoots) && raw.presetRoots.every((p) => typeof p === "string") ? raw.presetRoots.map((p) => resolve(p)) : [];
|
|
46
|
+
if (presetRoots.length === 0) fail(file, "presetRoots must be a non-empty string array");
|
|
47
|
+
const packRoots = Array.isArray(raw.packRoots) && raw.packRoots.every((p) => typeof p === "string") ? raw.packRoots.map((p) => resolve(p)) : [];
|
|
48
|
+
const emotionNode = raw.emotion;
|
|
49
|
+
if (typeof emotionNode !== "object" || emotionNode === null) fail(file, "emotion globals required (vectorHalfLifeMs/moodHalfLifeMs/trendBand/timezone)");
|
|
50
|
+
const e = emotionNode;
|
|
51
|
+
const emotion = {
|
|
52
|
+
vectorHalfLifeMs: e.vectorHalfLifeMs,
|
|
53
|
+
moodHalfLifeMs: e.moodHalfLifeMs,
|
|
54
|
+
trendBand: e.trendBand,
|
|
55
|
+
timezone: e.timezone
|
|
56
|
+
};
|
|
57
|
+
for (const [key, value] of Object.entries(emotion)) if (key === "timezone") {
|
|
58
|
+
if (typeof value !== "string" || value.length === 0) fail(file, "emotion.timezone must be a non-empty string");
|
|
59
|
+
} else if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) fail(file, `emotion.${key} must be a positive finite number`);
|
|
60
|
+
const listenNode = raw.listen;
|
|
61
|
+
if (typeof listenNode !== "object" || listenNode === null) fail(file, "listen required ({host, port})");
|
|
62
|
+
const l = listenNode;
|
|
63
|
+
if (typeof l.host !== "string" || l.host.length === 0) fail(file, "listen.host must be a non-empty string");
|
|
64
|
+
if (typeof l.port !== "number" || !Number.isInteger(l.port) || l.port < 0 || l.port > 65535) fail(file, "listen.port must be 0-65535");
|
|
65
|
+
const tlsNode = raw.tls;
|
|
66
|
+
if (typeof tlsNode !== "object" || tlsNode === null) fail(file, "tls required (keyFile/certFile/caFile)");
|
|
67
|
+
const t = tlsNode;
|
|
68
|
+
requireStrings(`${file} [tls]`, t, [
|
|
69
|
+
"keyFile",
|
|
70
|
+
"certFile",
|
|
71
|
+
"caFile"
|
|
72
|
+
]);
|
|
73
|
+
const clientsNode = raw.clients;
|
|
74
|
+
if (!Array.isArray(clientsNode) || clientsNode.length === 0) fail(file, "clients must be a non-empty list");
|
|
75
|
+
const seen = /* @__PURE__ */ new Set();
|
|
76
|
+
const clients = clientsNode.map((entry, index) => {
|
|
77
|
+
if (typeof entry !== "object" || entry === null) fail(`${file} [clients.${index}]`, "must be a mapping");
|
|
78
|
+
const c = entry;
|
|
79
|
+
requireStrings(`${file} [clients.${index}]`, c, ["hostId", "fingerprint256"]);
|
|
80
|
+
if (seen.has(c.hostId)) fail(file, `duplicate client hostId '${String(c.hostId)}'`);
|
|
81
|
+
seen.add(c.hostId);
|
|
82
|
+
if (c.allowMaids === void 0) return {
|
|
83
|
+
hostId: c.hostId,
|
|
84
|
+
fingerprint256: c.fingerprint256
|
|
85
|
+
};
|
|
86
|
+
if (!Array.isArray(c.allowMaids) || c.allowMaids.length === 0 || !c.allowMaids.every((m) => typeof m === "string")) fail(`${file} [clients.${index}]`, "allowMaids must be a non-empty string array (omit to allow all registered maids)");
|
|
87
|
+
return {
|
|
88
|
+
hostId: c.hostId,
|
|
89
|
+
fingerprint256: c.fingerprint256,
|
|
90
|
+
allowMaids: c.allowMaids
|
|
91
|
+
};
|
|
92
|
+
});
|
|
93
|
+
return {
|
|
94
|
+
dataDir,
|
|
95
|
+
presetRoots,
|
|
96
|
+
packRoots,
|
|
97
|
+
emotion,
|
|
98
|
+
listen: {
|
|
99
|
+
host: l.host,
|
|
100
|
+
port: l.port
|
|
101
|
+
},
|
|
102
|
+
tls: {
|
|
103
|
+
keyFile: t.keyFile,
|
|
104
|
+
certFile: t.certFile,
|
|
105
|
+
caFile: t.caFile
|
|
106
|
+
},
|
|
107
|
+
clients
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
function loadClientConfig(file) {
|
|
111
|
+
const raw = readYaml(file);
|
|
112
|
+
for (const key of Object.keys(raw)) if (!CLIENT_KEYS.has(key)) fail(file, `unknown top-level key '${key}'`);
|
|
113
|
+
requireStrings(file, raw, [...CLIENT_KEYS]);
|
|
114
|
+
return raw;
|
|
115
|
+
}
|
|
116
|
+
//#endregion
|
|
117
|
+
export { loadClientConfig, loadServerConfig };
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { CliIo, runCli } from "./cli.js";
|
|
2
|
+
import { EmotionGlobalsConfig, MaidStateClientConfig, MaidStateServerConfig, loadClientConfig, loadServerConfig } from "./config.js";
|
|
3
|
+
import { RunningMaidStateServer, startMaidStateServer } from "./server.js";
|
|
4
|
+
import { EmotionDiffEntry, EmotionDiffReport, EmotionStateExport, LegacyEmotionStates, diffEmotionJson, exportEmotionJson, importEmotionJson } from "./migrate.js";
|
|
5
|
+
export { type CliIo, type EmotionDiffEntry, type EmotionDiffReport, type EmotionGlobalsConfig, type EmotionStateExport, type LegacyEmotionStates, type MaidStateClientConfig, type MaidStateServerConfig, type RunningMaidStateServer, diffEmotionJson, exportEmotionJson, importEmotionJson, loadClientConfig, loadServerConfig, runCli, startMaidStateServer };
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { loadClientConfig, loadServerConfig } from "./config.js";
|
|
2
|
+
import { startMaidStateServer } from "./server.js";
|
|
3
|
+
import { diffEmotionJson, exportEmotionJson, importEmotionJson } from "./migrate.js";
|
|
4
|
+
import { runCli } from "./cli.js";
|
|
5
|
+
export { diffEmotionJson, exportEmotionJson, importEmotionJson, loadClientConfig, loadServerConfig, runCli, startMaidStateServer };
|
package/lib/migrate.d.ts
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { AuthorityStore } from "@deepmaid/maid-state";
|
|
2
|
+
import { EmotionAuthorityState, MaidEmotionState } from "@deepmaid/maid-emotion/domain";
|
|
3
|
+
import { EmotionConfigAuthority } from "@deepmaid/maid-emotion/config-authority";
|
|
4
|
+
//#region src/migrate.d.ts
|
|
5
|
+
/**
|
|
6
|
+
* 迁移工具(maid-state 阶段规格 §13):空库整份导入本机基线、当前权威导出、
|
|
7
|
+
* 分叉差异报告。纪律:仅空库可导入(任一 maid 有状态或有事件回执即拒绝);一次导入
|
|
8
|
+
* 覆盖全部已配置 maid,任一缺失/未注册即整批回滚;**绝不自动合并**分叉(差异只报告)。
|
|
9
|
+
*/
|
|
10
|
+
interface EmotionStateExport {
|
|
11
|
+
formatVersion: 1;
|
|
12
|
+
authorityId: string;
|
|
13
|
+
exportedAt: number;
|
|
14
|
+
maids: Record<string, {
|
|
15
|
+
state: EmotionAuthorityState;
|
|
16
|
+
revision: number;
|
|
17
|
+
}>;
|
|
18
|
+
}
|
|
19
|
+
interface EmotionDiffEntry {
|
|
20
|
+
vectors?: {
|
|
21
|
+
server: Record<string, number>;
|
|
22
|
+
other: Record<string, number>;
|
|
23
|
+
};
|
|
24
|
+
emotion?: {
|
|
25
|
+
server: Record<string, number>;
|
|
26
|
+
other: Record<string, number>;
|
|
27
|
+
};
|
|
28
|
+
signals?: {
|
|
29
|
+
server: Record<string, unknown>;
|
|
30
|
+
other: Record<string, unknown>;
|
|
31
|
+
};
|
|
32
|
+
updatedAt?: {
|
|
33
|
+
server: number;
|
|
34
|
+
other: number;
|
|
35
|
+
};
|
|
36
|
+
historyLength?: {
|
|
37
|
+
server: number;
|
|
38
|
+
other: number;
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
interface EmotionDiffReport {
|
|
42
|
+
maids: Record<string, EmotionDiffEntry>;
|
|
43
|
+
}
|
|
44
|
+
/** 旧宿主状态文件形态:单文件多 maidId → Record<maidId, MaidEmotionState> */
|
|
45
|
+
type LegacyEmotionStates = Record<string, MaidEmotionState>;
|
|
46
|
+
declare function importEmotionJson(store: AuthorityStore<EmotionAuthorityState>, configAuthority: EmotionConfigAuthority, legacy: LegacyEmotionStates): number;
|
|
47
|
+
declare function exportEmotionJson(store: AuthorityStore<EmotionAuthorityState>): EmotionStateExport;
|
|
48
|
+
/** 差异报告:vectors/emotion 数值、signals、updatedAt、history 长度的双值对照;只读不写库 */
|
|
49
|
+
declare function diffEmotionJson(store: AuthorityStore<EmotionAuthorityState>, other: LegacyEmotionStates): EmotionDiffReport;
|
|
50
|
+
//#endregion
|
|
51
|
+
export { EmotionDiffEntry, EmotionDiffReport, EmotionStateExport, LegacyEmotionStates, diffEmotionJson, exportEmotionJson, importEmotionJson };
|
package/lib/migrate.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { alignStateToConfig, emotionTiersOf } from "@deepmaid/maid-emotion/domain";
|
|
2
|
+
//#region src/migrate.ts
|
|
3
|
+
function importEmotionJson(store, configAuthority, legacy) {
|
|
4
|
+
const existing = store.exportStates();
|
|
5
|
+
const hasEvents = store.listEvents({ limit: 1 }).length > 0;
|
|
6
|
+
if (Object.keys(existing).length > 0 || hasEvents) throw new Error(`maid-state-server: import requires an empty authority store (data dir not empty): refusing to overwrite history`);
|
|
7
|
+
const configured = /* @__PURE__ */ new Set();
|
|
8
|
+
for (const maidId of configAuthority.list()) if (configAuthority.get(maidId) !== void 0) configured.add(maidId);
|
|
9
|
+
for (const maidId of Object.keys(legacy)) if (!configured.has(maidId)) throw new Error(`maid-state-server: legacy state carries unregistered/unconfigured maid '${maidId}'`);
|
|
10
|
+
for (const maidId of configured) if (legacy[maidId] === void 0) throw new Error(`maid-state-server: configured maid '${maidId}' missing from legacy state (refusing partial import)`);
|
|
11
|
+
let count = 0;
|
|
12
|
+
store.transaction((tx) => {
|
|
13
|
+
for (const maidId of configured) {
|
|
14
|
+
const entry = configAuthority.get(maidId);
|
|
15
|
+
const legacyState = legacy[maidId];
|
|
16
|
+
const current = alignStateToConfig(legacyState, Object.keys(entry.config.emotion.dimensions), emotionTiersOf(entry.config.emotion));
|
|
17
|
+
const lastEffectiveAt = Math.max(legacyState.updatedAt, legacyState.emotion?.updatedAt ?? 0, legacyState.signals.lastMessageAt);
|
|
18
|
+
tx.writeState(maidId, {
|
|
19
|
+
state: {
|
|
20
|
+
current,
|
|
21
|
+
lastEffectiveAt
|
|
22
|
+
},
|
|
23
|
+
revision: 0
|
|
24
|
+
});
|
|
25
|
+
count++;
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
return count;
|
|
29
|
+
}
|
|
30
|
+
function exportEmotionJson(store) {
|
|
31
|
+
return {
|
|
32
|
+
formatVersion: 1,
|
|
33
|
+
authorityId: store.authorityId,
|
|
34
|
+
exportedAt: Date.now(),
|
|
35
|
+
maids: store.exportStates()
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
/** 差异报告:vectors/emotion 数值、signals、updatedAt、history 长度的双值对照;只读不写库 */
|
|
39
|
+
function diffEmotionJson(store, other) {
|
|
40
|
+
const serverStates = store.exportStates();
|
|
41
|
+
const maids = {};
|
|
42
|
+
const emotionValues = (state) => {
|
|
43
|
+
const dims = state.emotion?.dimensions;
|
|
44
|
+
return dims === void 0 ? {} : Object.fromEntries(Object.entries(dims).map(([id, d]) => [id, d.value]));
|
|
45
|
+
};
|
|
46
|
+
const asMaid = (s) => s;
|
|
47
|
+
for (const maidId of /* @__PURE__ */ new Set([...Object.keys(serverStates), ...Object.keys(other)])) {
|
|
48
|
+
const server = serverStates[maidId]?.state.current;
|
|
49
|
+
const otherState = other[maidId];
|
|
50
|
+
if (server === void 0 || otherState === void 0) {
|
|
51
|
+
maids[maidId] = { historyLength: {
|
|
52
|
+
server: server !== void 0 ? asMaid(server).history.length : -1,
|
|
53
|
+
other: otherState !== void 0 ? otherState.history.length : -1
|
|
54
|
+
} };
|
|
55
|
+
continue;
|
|
56
|
+
}
|
|
57
|
+
const entry = {};
|
|
58
|
+
if (JSON.stringify(server.vectors) !== JSON.stringify(otherState.vectors)) entry.vectors = {
|
|
59
|
+
server: { ...server.vectors },
|
|
60
|
+
other: { ...otherState.vectors }
|
|
61
|
+
};
|
|
62
|
+
const serverEmotion = emotionValues(asMaid(server));
|
|
63
|
+
const otherEmotion = emotionValues(otherState);
|
|
64
|
+
if (JSON.stringify(serverEmotion) !== JSON.stringify(otherEmotion)) entry.emotion = {
|
|
65
|
+
server: serverEmotion,
|
|
66
|
+
other: otherEmotion
|
|
67
|
+
};
|
|
68
|
+
if (JSON.stringify(server.signals) !== JSON.stringify(otherState.signals)) entry.signals = {
|
|
69
|
+
server: { ...server.signals },
|
|
70
|
+
other: { ...otherState.signals }
|
|
71
|
+
};
|
|
72
|
+
if (server.updatedAt !== otherState.updatedAt) entry.updatedAt = {
|
|
73
|
+
server: server.updatedAt,
|
|
74
|
+
other: otherState.updatedAt
|
|
75
|
+
};
|
|
76
|
+
if (asMaid(server).history.length !== otherState.history.length) entry.historyLength = {
|
|
77
|
+
server: asMaid(server).history.length,
|
|
78
|
+
other: otherState.history.length
|
|
79
|
+
};
|
|
80
|
+
if (Object.keys(entry).length > 0) maids[maidId] = entry;
|
|
81
|
+
}
|
|
82
|
+
return { maids };
|
|
83
|
+
}
|
|
84
|
+
//#endregion
|
|
85
|
+
export { diffEmotionJson, exportEmotionJson, importEmotionJson };
|
package/lib/server.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { MaidStateServerConfig } from "./config.js";
|
|
2
|
+
//#region src/server.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* 权威服务组合入口(maid-state 阶段规格 §4.2;M3j 起委托 maid-emotion 的共享
|
|
5
|
+
* createEmotionAuthority 组合面):纯 registry + 共享 authority(config 权威 +
|
|
6
|
+
* domain reducer + 事务存储)+ mTLS 面。embedded 后端与 server 消费同一组合,
|
|
7
|
+
* 「同一输入同一结果」由结构保证。
|
|
8
|
+
*/
|
|
9
|
+
interface RunningMaidStateServer {
|
|
10
|
+
authorityId: string;
|
|
11
|
+
url: string;
|
|
12
|
+
close(): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
declare function startMaidStateServer(config: MaidStateServerConfig, deps?: {
|
|
15
|
+
warn?: (m: string) => void;
|
|
16
|
+
now?: () => number;
|
|
17
|
+
}): Promise<RunningMaidStateServer>;
|
|
18
|
+
//#endregion
|
|
19
|
+
export { RunningMaidStateServer, startMaidStateServer };
|
package/lib/server.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { loadRegistry } from "@deepmaid/maid-identity/registry";
|
|
2
|
+
import { createEmotionAuthority } from "@deepmaid/maid-emotion/authority";
|
|
3
|
+
import { startStateHttpServer } from "@deepmaid/maid-state";
|
|
4
|
+
//#region src/server.ts
|
|
5
|
+
async function startMaidStateServer(config, deps = {}) {
|
|
6
|
+
const warn = deps.warn ?? (() => {});
|
|
7
|
+
const registry = loadRegistry(config.presetRoots, {
|
|
8
|
+
packRoots: config.packRoots,
|
|
9
|
+
warn
|
|
10
|
+
});
|
|
11
|
+
const runtime = createEmotionAuthority({
|
|
12
|
+
dataDir: config.dataDir,
|
|
13
|
+
presetRoots: config.presetRoots,
|
|
14
|
+
identity: registry,
|
|
15
|
+
globals: config.emotion,
|
|
16
|
+
warn,
|
|
17
|
+
...deps.now !== void 0 ? { now: deps.now } : {}
|
|
18
|
+
});
|
|
19
|
+
const http = await startStateHttpServer({
|
|
20
|
+
authority: runtime.authority,
|
|
21
|
+
store: runtime.store,
|
|
22
|
+
listen: config.listen,
|
|
23
|
+
tls: {
|
|
24
|
+
...config.tls,
|
|
25
|
+
clients: config.clients
|
|
26
|
+
}
|
|
27
|
+
});
|
|
28
|
+
return {
|
|
29
|
+
authorityId: runtime.authority.authorityId,
|
|
30
|
+
url: http.url,
|
|
31
|
+
close: async () => {
|
|
32
|
+
await http.close();
|
|
33
|
+
registry.dispose();
|
|
34
|
+
runtime.close();
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
//#endregion
|
|
39
|
+
export { startMaidStateServer };
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deepmaid/maid-state-server",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0-alpha.3",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"maid-state": "./lib/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"main": "lib/index.js",
|
|
10
|
+
"types": "lib/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./lib/index.d.ts",
|
|
14
|
+
"default": "./lib/index.js"
|
|
15
|
+
},
|
|
16
|
+
"./server": {
|
|
17
|
+
"types": "./lib/server.d.ts",
|
|
18
|
+
"default": "./lib/server.js"
|
|
19
|
+
},
|
|
20
|
+
"./config": {
|
|
21
|
+
"types": "./lib/config.d.ts",
|
|
22
|
+
"default": "./lib/config.js"
|
|
23
|
+
},
|
|
24
|
+
"./migrate": {
|
|
25
|
+
"types": "./lib/migrate.d.ts",
|
|
26
|
+
"default": "./lib/migrate.js"
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"lib"
|
|
31
|
+
],
|
|
32
|
+
"dependencies": {
|
|
33
|
+
"yaml": "2.9.0",
|
|
34
|
+
"@deepmaid/maid-emotion": "0.1.0-alpha.3",
|
|
35
|
+
"@deepmaid/maid-identity": "0.1.0-alpha.3",
|
|
36
|
+
"@deepmaid/maid-state": "0.1.0-alpha.3"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"tsdown": "0.22.14",
|
|
40
|
+
"typescript": "6.0.3"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsdown"
|
|
47
|
+
}
|
|
6
48
|
}
|
package/README.md
DELETED