pi-wechat-session-hub 0.1.0

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.
Files changed (51) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +365 -0
  3. package/docs/decisions/0001-ilink-context-token-queue.md +41 -0
  4. package/docs/handoff-next-session.md +134 -0
  5. package/docs/implementation-spec.md +147 -0
  6. package/extensions/wechat-session-hub.ts +589 -0
  7. package/package.json +67 -0
  8. package/scripts/pi-rpc-smoke.mjs +150 -0
  9. package/scripts/probe-wt-capability.mjs +27 -0
  10. package/scripts/start-ui-worker.ps1 +37 -0
  11. package/src/commands/ilink-qr-login-component.ts +148 -0
  12. package/src/commands/project-command-parser.ts +108 -0
  13. package/src/commands/tokenizer.ts +71 -0
  14. package/src/commands/wechat-manager-command-parser.ts +143 -0
  15. package/src/config/defaults.ts +30 -0
  16. package/src/config/paths.ts +56 -0
  17. package/src/config/store.ts +311 -0
  18. package/src/config/types.ts +33 -0
  19. package/src/config/validation.ts +221 -0
  20. package/src/gateway/channel-types.ts +47 -0
  21. package/src/gateway/command-parser.ts +291 -0
  22. package/src/gateway/command-router.ts +1449 -0
  23. package/src/gateway/credential-store.ts +611 -0
  24. package/src/gateway/durable-message-queue.ts +1043 -0
  25. package/src/gateway/gateway-control-ipc.ts +687 -0
  26. package/src/gateway/gateway-runtime.ts +726 -0
  27. package/src/gateway/ui-worker-extension-bridge.ts +1070 -0
  28. package/src/gateway/ui-worker-ipc.ts +1483 -0
  29. package/src/gateway/ui-worker-types.ts +50 -0
  30. package/src/gateway/wechat-ilink/api-client.ts +390 -0
  31. package/src/gateway/wechat-ilink/channel-adapter.ts +320 -0
  32. package/src/gateway/wechat-ilink/cursor-store.ts +134 -0
  33. package/src/gateway/wechat-ilink/qr-login.ts +612 -0
  34. package/src/gateway/wechat-ilink/typing-indicator.ts +133 -0
  35. package/src/gateway/windows-terminal-launcher.ts +247 -0
  36. package/src/projects/project-service.ts +483 -0
  37. package/src/registry/gateway-lease.ts +348 -0
  38. package/src/registry/manager-registry.ts +466 -0
  39. package/src/registry/types.ts +61 -0
  40. package/src/runtime/background-pi-worker.ts +309 -0
  41. package/src/runtime/background-worker-manager.ts +594 -0
  42. package/src/runtime/gateway-daemon.ts +281 -0
  43. package/src/runtime/gateway-lifecycle-operation.ts +308 -0
  44. package/src/runtime/gateway-service-controller.ts +339 -0
  45. package/src/runtime/gateway-worker-manager.ts +181 -0
  46. package/src/runtime/pi-cli.ts +56 -0
  47. package/src/runtime/pi-rpc-client.ts +427 -0
  48. package/src/runtime/ui-worker-manager.ts +1186 -0
  49. package/src/runtime/windows-logon-task-manager.ts +212 -0
  50. package/src/system/process-liveness.ts +88 -0
  51. package/tsconfig.json +19 -0
@@ -0,0 +1,30 @@
1
+ import type { ManagerConfiguration } from "./types.ts";
2
+ import { getCredentialFilePath } from "./paths.ts";
3
+
4
+ /**
5
+ * 创建默认运行时配置。
6
+ *
7
+ * @param credentialFile 凭证应单独保存的文件路径。
8
+ * @returns 不会写入磁盘的默认配置对象。
9
+ */
10
+ export function createDefaultConfiguration(
11
+ credentialFile = getCredentialFilePath(),
12
+ ): ManagerConfiguration {
13
+ return {
14
+ schemaVersion: 1,
15
+ autoStartOnWindowsLogon: false,
16
+ defaultMode: "background",
17
+ allowedProjectRoots: [],
18
+ projects: {},
19
+ wechat: {
20
+ authorizedUserId: "",
21
+ credentialFile,
22
+ },
23
+ runtime: {
24
+ heartbeatIntervalMs: 5000,
25
+ staleAfterMs: 20000,
26
+ maxBackgroundWorkers: 4,
27
+ maxQueuePerSession: 20,
28
+ },
29
+ };
30
+ }
@@ -0,0 +1,56 @@
1
+ import { homedir } from "node:os";
2
+ import { isAbsolute, join, resolve } from "node:path";
3
+
4
+ /**
5
+ * 获取 Pi 微信会话枢纽的数据目录。
6
+ *
7
+ * @param agentDirectory Pi agent 目录, 可为空以使用默认目录。
8
+ * @param homeDirectory 用户主目录, 用于测试时注入。
9
+ * @returns 规范化后的数据目录绝对路径。
10
+ */
11
+ export function getManagerDataDirectory(
12
+ agentDirectory = process.env.PI_CODING_AGENT_DIR,
13
+ homeDirectory = homedir(),
14
+ ): string {
15
+ const baseDirectory = agentDirectory?.trim()
16
+ ? isAbsolute(agentDirectory)
17
+ ? agentDirectory
18
+ : resolve(homeDirectory, agentDirectory)
19
+ : join(homeDirectory, ".pi", "agent");
20
+
21
+ return join(baseDirectory, "wechat-session-manager");
22
+ }
23
+
24
+ /**
25
+ * 获取 Pi 微信会话枢纽配置文件的绝对路径。
26
+ *
27
+ * @param agentDirectory Pi agent 目录, 可为空以使用默认目录。
28
+ * @param homeDirectory 用户主目录, 用于测试时注入。
29
+ * @returns 配置文件绝对路径。
30
+ */
31
+ export function getManagerConfigurationPath(
32
+ agentDirectory = process.env.PI_CODING_AGENT_DIR,
33
+ homeDirectory = homedir(),
34
+ ): string {
35
+ const baseDirectory = agentDirectory?.trim()
36
+ ? isAbsolute(agentDirectory)
37
+ ? agentDirectory
38
+ : resolve(homeDirectory, agentDirectory)
39
+ : join(homeDirectory, ".pi", "agent");
40
+
41
+ return join(baseDirectory, "wechat-session-manager.json");
42
+ }
43
+
44
+ /**
45
+ * 获取凭证文件路径。此函数只计算路径, 不读取或写入凭证。
46
+ *
47
+ * @param agentDirectory Pi agent 目录, 可为空以使用默认目录。
48
+ * @param homeDirectory 用户主目录, 用于测试时注入。
49
+ * @returns 独立凭证文件绝对路径。
50
+ */
51
+ export function getCredentialFilePath(
52
+ agentDirectory = process.env.PI_CODING_AGENT_DIR,
53
+ homeDirectory = homedir(),
54
+ ): string {
55
+ return join(getManagerDataDirectory(agentDirectory, homeDirectory), "credentials.json");
56
+ }
@@ -0,0 +1,311 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { mkdir, open, readFile, rename, unlink } from "node:fs/promises";
3
+ import { dirname, isAbsolute, join, resolve } from "node:path";
4
+ import { isProcessAlive } from "../system/process-liveness.ts";
5
+ import { getCredentialFilePath, getManagerConfigurationPath } from "./paths.ts";
6
+ import { createDefaultConfiguration } from "./defaults.ts";
7
+ import { ConfigurationValidationError, validateConfiguration } from "./validation.ts";
8
+ import type { ManagerConfiguration } from "./types.ts";
9
+
10
+ interface LockMetadata {
11
+ pid: number;
12
+ token: string;
13
+ }
14
+
15
+ /**
16
+ * 表示配置文件当前被另一个进程占用, 或锁状态无法安全判定。
17
+ */
18
+ export class ConfigurationBusyError extends Error {
19
+ /**
20
+ * 创建配置占用错误。
21
+ *
22
+ * @param message 面向用户的中文错误信息。
23
+ */
24
+ constructor(message: string) {
25
+ super(message);
26
+ this.name = "ConfigurationBusyError";
27
+ }
28
+ }
29
+
30
+ /**
31
+ * 配置文件加载结果。
32
+ */
33
+ export interface ConfigurationSnapshot {
34
+ config: ManagerConfiguration;
35
+ exists: boolean;
36
+ }
37
+
38
+ /**
39
+ * 读写 Pi 微信会话枢纽 JSON 配置, 并以临时文件原子替换。
40
+ */
41
+ export class ConfigurationStore {
42
+ private writeQueue: Promise<void> = Promise.resolve();
43
+ private readonly credentialFile: string;
44
+
45
+ /**
46
+ * 创建配置存储。
47
+ *
48
+ * @param filePath 配置 JSON 文件路径。
49
+ * @param credentialFile 独立凭证文件路径, 缺省为 manager 数据目录中的文件。
50
+ */
51
+ constructor(
52
+ readonly filePath: string,
53
+ credentialFile = join(dirname(filePath), "wechat-session-manager", "credentials.json"),
54
+ ) {
55
+ this.filePath = resolve(filePath);
56
+ this.credentialFile = isAbsolute(credentialFile)
57
+ ? credentialFile
58
+ : resolve(dirname(this.filePath), credentialFile);
59
+ }
60
+
61
+ /**
62
+ * 读取并校验配置; 文件不存在时返回默认配置但不创建文件。
63
+ *
64
+ * @returns 配置内容及文件是否已存在。
65
+ * @throws {ConfigurationValidationError} 文件 JSON 或 schema 非法时抛出。
66
+ */
67
+ async load(): Promise<ConfigurationSnapshot> {
68
+ try {
69
+ const contents = await readFile(this.filePath, "utf8");
70
+ let parsed: unknown;
71
+ try {
72
+ parsed = JSON.parse(contents) as unknown;
73
+ } catch {
74
+ throw new ConfigurationValidationError("配置文件不是有效 JSON, 请检查文件格式。");
75
+ }
76
+ return {
77
+ config: validateConfiguration(parsed, this.credentialFile),
78
+ exists: true,
79
+ };
80
+ } catch (error) {
81
+ if (isNodeError(error) && error.code === "ENOENT") {
82
+ return {
83
+ config: createDefaultConfiguration(this.credentialFile),
84
+ exists: false,
85
+ };
86
+ }
87
+ throw error;
88
+ }
89
+ }
90
+
91
+ /**
92
+ * 校验并原子保存完整配置。
93
+ *
94
+ * @param value 待保存配置。
95
+ * @returns 实际保存的规范化配置。
96
+ */
97
+ async save(value: ManagerConfiguration): Promise<ManagerConfiguration> {
98
+ return this.withWriteQueue(async () => this.withFileLock(async () => {
99
+ const config = validateConfiguration(value, this.credentialFile);
100
+ await this.writeUnlocked(config);
101
+ return config;
102
+ }));
103
+ }
104
+
105
+ /**
106
+ * 在互斥区内读取、修改并保存配置, 防止多个 manager 丢失彼此更新。
107
+ *
108
+ * @param updater 根据当前配置生成新配置的函数。
109
+ * @returns 更新并保存后的配置。
110
+ */
111
+ async update(
112
+ updater: (current: ManagerConfiguration) => ManagerConfiguration | Promise<ManagerConfiguration>,
113
+ ): Promise<ManagerConfiguration> {
114
+ return this.withWriteQueue(async () => this.withFileLock(async () => {
115
+ const snapshot = await this.load();
116
+ const updated = validateConfiguration(
117
+ await updater(snapshot.config),
118
+ this.credentialFile,
119
+ );
120
+ await this.writeUnlocked(updated);
121
+ return updated;
122
+ }));
123
+ }
124
+
125
+ /**
126
+ * 串行执行当前进程内对此 store 的写操作。
127
+ *
128
+ * @param operation 要执行的异步写操作。
129
+ * @returns 写操作结果。
130
+ */
131
+ private async withWriteQueue<T>(operation: () => Promise<T>): Promise<T> {
132
+ const previous = this.writeQueue;
133
+ let release = (): void => undefined;
134
+ this.writeQueue = new Promise<void>((resolveQueue) => {
135
+ release = resolveQueue;
136
+ });
137
+ await previous;
138
+ try {
139
+ return await operation();
140
+ } finally {
141
+ release();
142
+ }
143
+ }
144
+
145
+ /**
146
+ * 使用独占锁执行写操作; 遇到不确定的锁状态时 fail-closed。
147
+ *
148
+ * @param operation 获得锁后执行的异步操作。
149
+ * @returns 写操作结果。
150
+ */
151
+ private async withFileLock<T>(operation: () => Promise<T>): Promise<T> {
152
+ await mkdir(dirname(this.filePath), { recursive: true });
153
+ const lockPath = `${this.filePath}.lock`;
154
+ const token = randomUUID();
155
+ const lockHandle = await this.acquireFileLock(lockPath, token);
156
+ try {
157
+ return await operation();
158
+ } finally {
159
+ await lockHandle.close();
160
+ await this.releaseFileLock(lockPath, token);
161
+ }
162
+ }
163
+
164
+ /**
165
+ * 创建或安全回收配置锁。
166
+ *
167
+ * @param lockPath 锁文件路径。
168
+ * @param token 当前写入者随机令牌。
169
+ * @returns 已持有锁文件的句柄。
170
+ * @throws {ConfigurationBusyError} 锁由活动进程持有或锁数据损坏时抛出。
171
+ */
172
+ private async acquireFileLock(lockPath: string, token: string) {
173
+ for (let attempt = 0; attempt < 2; attempt += 1) {
174
+ let handle;
175
+ try {
176
+ handle = await open(lockPath, "wx", 0o600);
177
+ } catch (error) {
178
+ if (!isNodeError(error) || error.code !== "EEXIST") {
179
+ throw error;
180
+ }
181
+ if (attempt > 0 || await this.lockOwnerIsAlive(lockPath)) {
182
+ throw new ConfigurationBusyError(
183
+ "配置正在被另一个 Pi 进程修改, 请稍后重试; 锁状态不明确时不会强行覆盖。",
184
+ );
185
+ }
186
+ await unlink(lockPath);
187
+ continue;
188
+ }
189
+
190
+ try {
191
+ await handle.writeFile(
192
+ JSON.stringify({ pid: process.pid, token } satisfies LockMetadata),
193
+ "utf8",
194
+ );
195
+ await handle.sync();
196
+ return handle;
197
+ } catch (error) {
198
+ await handle.close();
199
+ try {
200
+ await this.releaseFileLock(lockPath, token);
201
+ } catch {
202
+ throw new ConfigurationBusyError(
203
+ "配置锁写入失败且无法安全清理, 请检查配置目录后重试。",
204
+ );
205
+ }
206
+ throw error;
207
+ }
208
+ }
209
+ throw new ConfigurationBusyError("无法取得配置写入锁, 请稍后重试。");
210
+ }
211
+
212
+ /**
213
+ * 检查锁记录中的进程是否仍可能存活。
214
+ *
215
+ * @param lockPath 锁文件路径。
216
+ * @returns 进程存活或锁数据不完整时返回 true。
217
+ */
218
+ private async lockOwnerIsAlive(lockPath: string): Promise<boolean> {
219
+ try {
220
+ const lockContents = await readFile(lockPath, "utf8");
221
+ const metadata = JSON.parse(lockContents) as Partial<LockMetadata>;
222
+ const pid = metadata.pid;
223
+ if (typeof pid !== "number" || !Number.isInteger(pid) || pid <= 0 || !metadata.token) {
224
+ return true;
225
+ }
226
+ return isProcessAlive(pid);
227
+ } catch {
228
+ return true;
229
+ }
230
+ }
231
+
232
+ /**
233
+ * 仅在锁令牌仍匹配时移除锁文件。
234
+ *
235
+ * @param lockPath 锁文件路径。
236
+ * @param token 当前写入者随机令牌。
237
+ * @returns 无返回值。
238
+ */
239
+ private async releaseFileLock(lockPath: string, token: string): Promise<void> {
240
+ try {
241
+ const lockContents = await readFile(lockPath, "utf8");
242
+ const metadata = JSON.parse(lockContents) as Partial<LockMetadata>;
243
+ if (metadata.token === token && metadata.pid === process.pid) {
244
+ await unlink(lockPath);
245
+ }
246
+ } catch (error) {
247
+ if (!isNodeError(error) || error.code !== "ENOENT") {
248
+ throw error;
249
+ }
250
+ }
251
+ }
252
+
253
+ /**
254
+ * 将配置写入同目录临时文件并原子替换目标文件。
255
+ *
256
+ * @param config 已校验配置。
257
+ * @returns 无返回值。
258
+ */
259
+ private async writeUnlocked(config: ManagerConfiguration): Promise<void> {
260
+ await mkdir(dirname(this.filePath), { recursive: true });
261
+ const temporaryPath = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
262
+ const handle = await open(temporaryPath, "wx", 0o600);
263
+ try {
264
+ await handle.writeFile(`${JSON.stringify(config, null, 2)}\n`, "utf8");
265
+ await handle.sync();
266
+ } catch (error) {
267
+ await handle.close();
268
+ try {
269
+ await unlink(temporaryPath);
270
+ } catch {
271
+ throw new Error("配置写入失败, 且无法清理临时文件。");
272
+ }
273
+ throw error;
274
+ }
275
+ await handle.close();
276
+ try {
277
+ await rename(temporaryPath, this.filePath);
278
+ } catch (error) {
279
+ try {
280
+ await unlink(temporaryPath);
281
+ } catch (cleanupError) {
282
+ if (!isNodeError(cleanupError) || cleanupError.code !== "ENOENT") {
283
+ throw cleanupError;
284
+ }
285
+ }
286
+ throw error;
287
+ }
288
+ }
289
+ }
290
+
291
+ /**
292
+ * 判断值是否为 Node.js 文件系统错误。
293
+ *
294
+ * @param error 待检查值。
295
+ * @returns 值包含 Node.js 错误代码时返回 true。
296
+ */
297
+ function isNodeError(error: unknown): error is NodeJS.ErrnoException {
298
+ return error instanceof Error && "code" in error;
299
+ }
300
+
301
+ /**
302
+ * 获取使用 Pi 配置目录约定的默认配置存储。
303
+ *
304
+ * @returns 配置存储实例。
305
+ */
306
+ export function createDefaultConfigurationStore(): ConfigurationStore {
307
+ return new ConfigurationStore(
308
+ getManagerConfigurationPath(),
309
+ getCredentialFilePath(),
310
+ );
311
+ }
@@ -0,0 +1,33 @@
1
+ export type RuntimeMode = "background" | "ui";
2
+
3
+ export interface ProjectDefinition {
4
+ displayName: string;
5
+ path: string;
6
+ [key: string]: unknown;
7
+ }
8
+
9
+ export interface WechatConfiguration {
10
+ authorizedUserId: string;
11
+ credentialFile: string;
12
+ [key: string]: unknown;
13
+ }
14
+
15
+ export interface RuntimeConfiguration {
16
+ heartbeatIntervalMs: number;
17
+ staleAfterMs: number;
18
+ maxBackgroundWorkers: number;
19
+ maxQueuePerSession: number;
20
+ [key: string]: unknown;
21
+ }
22
+
23
+ export interface ManagerConfiguration {
24
+ schemaVersion: 1;
25
+ autoStartOnWindowsLogon: boolean;
26
+ defaultMode: RuntimeMode;
27
+ defaultProject?: string;
28
+ allowedProjectRoots: string[];
29
+ projects: Record<string, ProjectDefinition>;
30
+ wechat: WechatConfiguration;
31
+ runtime: RuntimeConfiguration;
32
+ [key: string]: unknown;
33
+ }
@@ -0,0 +1,221 @@
1
+ import { isAbsolute } from "node:path";
2
+ import { createDefaultConfiguration } from "./defaults.ts";
3
+ import { getCredentialFilePath } from "./paths.ts";
4
+ import type {
5
+ ManagerConfiguration,
6
+ ProjectDefinition,
7
+ RuntimeConfiguration,
8
+ RuntimeMode,
9
+ WechatConfiguration,
10
+ } from "./types.ts";
11
+
12
+ const PROJECT_ALIAS_PATTERN = /^[a-z0-9][a-z0-9_-]{0,31}$/;
13
+
14
+ /**
15
+ * 表示配置文件结构或字段不符合当前 schema。
16
+ */
17
+ export class ConfigurationValidationError extends Error {
18
+ /**
19
+ * 创建配置校验错误。
20
+ *
21
+ * @param message 面向用户的中文错误信息。
22
+ */
23
+ constructor(message: string) {
24
+ super(message);
25
+ this.name = "ConfigurationValidationError";
26
+ }
27
+ }
28
+
29
+ /**
30
+ * 校验并规范化 Pi 微信会话枢纽配置, 同时保留未知字段。
31
+ *
32
+ * @param value 从 JSON 解码得到的任意值。
33
+ * @param credentialFile 默认独立凭证文件路径。
34
+ * @returns 符合 schemaVersion 1 的配置对象。
35
+ * @throws {ConfigurationValidationError} 配置字段非法时抛出。
36
+ */
37
+ export function validateConfiguration(
38
+ value: unknown,
39
+ credentialFile = getCredentialFilePath(),
40
+ ): ManagerConfiguration {
41
+ const input = asRecord(value, "配置根节点");
42
+ const defaults = createDefaultConfiguration(credentialFile);
43
+ const inputWechat = input.wechat === undefined
44
+ ? {}
45
+ : asRecord(input.wechat, "wechat");
46
+ const inputRuntime = input.runtime === undefined
47
+ ? {}
48
+ : asRecord(input.runtime, "runtime");
49
+
50
+ const candidate: Record<string, unknown> = {
51
+ ...defaults,
52
+ ...input,
53
+ wechat: {
54
+ ...defaults.wechat,
55
+ ...inputWechat,
56
+ },
57
+ runtime: {
58
+ ...defaults.runtime,
59
+ ...inputRuntime,
60
+ },
61
+ allowedProjectRoots: input.allowedProjectRoots ?? defaults.allowedProjectRoots,
62
+ projects: input.projects ?? defaults.projects,
63
+ };
64
+
65
+ if (candidate.schemaVersion !== 1) {
66
+ throw new ConfigurationValidationError("配置 schemaVersion 必须为 1。");
67
+ }
68
+ if (typeof candidate.autoStartOnWindowsLogon !== "boolean") {
69
+ throw new ConfigurationValidationError("autoStartOnWindowsLogon 必须是布尔值。");
70
+ }
71
+
72
+ if (candidate.defaultMode !== "background" && candidate.defaultMode !== "ui") {
73
+ throw new ConfigurationValidationError("defaultMode 只能是 background 或 ui。");
74
+ }
75
+
76
+ if (!Array.isArray(candidate.allowedProjectRoots)) {
77
+ throw new ConfigurationValidationError("allowedProjectRoots 必须是路径数组。");
78
+ }
79
+
80
+ const allowedProjectRoots = candidate.allowedProjectRoots.map((root, index) => {
81
+ if (typeof root !== "string" || !root.trim() || !isAbsolute(root)) {
82
+ throw new ConfigurationValidationError(
83
+ `allowedProjectRoots[${index}] 必须是非空绝对路径。`,
84
+ );
85
+ }
86
+ return root;
87
+ });
88
+
89
+ const rawProjects = asRecord(candidate.projects, "projects");
90
+ const projectEntries: Array<[string, ProjectDefinition]> = [];
91
+ for (const [alias, rawProject] of Object.entries(rawProjects)) {
92
+ assertProjectAlias(alias);
93
+ const project = asRecord(rawProject, `projects.${alias}`);
94
+ if (typeof project.displayName !== "string" || !project.displayName.trim()) {
95
+ throw new ConfigurationValidationError(
96
+ `projects.${alias}.displayName 必须是非空字符串。`,
97
+ );
98
+ }
99
+ if (typeof project.path !== "string" || !project.path.trim() || !isAbsolute(project.path)) {
100
+ throw new ConfigurationValidationError(
101
+ `projects.${alias}.path 必须是非空绝对路径。`,
102
+ );
103
+ }
104
+ projectEntries.push([
105
+ alias,
106
+ {
107
+ ...project,
108
+ displayName: project.displayName.trim(),
109
+ path: project.path,
110
+ },
111
+ ]);
112
+ }
113
+ const projects = Object.fromEntries(projectEntries) as Record<string, ProjectDefinition>;
114
+
115
+ const inputDefaultProject = candidate.defaultProject;
116
+ if (inputDefaultProject !== undefined) {
117
+ if (typeof inputDefaultProject !== "string") {
118
+ throw new ConfigurationValidationError("defaultProject 必须是项目 alias 字符串。");
119
+ }
120
+ assertProjectAlias(inputDefaultProject);
121
+ if (!Object.hasOwn(projects, inputDefaultProject)) {
122
+ throw new ConfigurationValidationError(
123
+ `defaultProject 引用了未登记的项目 alias: ${inputDefaultProject}。`,
124
+ );
125
+ }
126
+ }
127
+
128
+ const wechat = validateWechat(candidate.wechat);
129
+ const runtime = validateRuntime(candidate.runtime);
130
+
131
+ return {
132
+ ...candidate,
133
+ schemaVersion: 1,
134
+ defaultMode: candidate.defaultMode as RuntimeMode,
135
+ ...(inputDefaultProject === undefined ? {} : { defaultProject: inputDefaultProject }),
136
+ allowedProjectRoots,
137
+ projects,
138
+ wechat,
139
+ runtime,
140
+ } as ManagerConfiguration;
141
+ }
142
+
143
+ /**
144
+ * 校验稳定项目 alias 的格式。
145
+ *
146
+ * @param alias 待校验的项目 alias。
147
+ * @throws {ConfigurationValidationError} alias 不符合格式时抛出。
148
+ */
149
+ export function assertProjectAlias(alias: string): void {
150
+ if (!PROJECT_ALIAS_PATTERN.test(alias)) {
151
+ throw new ConfigurationValidationError(
152
+ "项目 alias 需为 1-32 位小写字母、数字、下划线或连字符, 且以字母或数字开头。",
153
+ );
154
+ }
155
+ }
156
+
157
+ /**
158
+ * 将未知值校验为普通对象。
159
+ *
160
+ * @param value 待校验值。
161
+ * @param label 错误信息中使用的字段名。
162
+ * @returns 普通键值对象。
163
+ * @throws {ConfigurationValidationError} 值不是普通对象时抛出。
164
+ */
165
+ function asRecord(value: unknown, label: string): Record<string, unknown> {
166
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
167
+ throw new ConfigurationValidationError(`${label} 必须是 JSON 对象。`);
168
+ }
169
+ return value as Record<string, unknown>;
170
+ }
171
+
172
+ /**
173
+ * 校验微信配置并保留扩展字段。
174
+ *
175
+ * @param value 待校验值。
176
+ * @returns 微信配置对象。
177
+ */
178
+ function validateWechat(value: unknown): WechatConfiguration {
179
+ const wechat = asRecord(value, "wechat");
180
+ if (typeof wechat.authorizedUserId !== "string") {
181
+ throw new ConfigurationValidationError("wechat.authorizedUserId 必须是字符串。");
182
+ }
183
+ if (
184
+ typeof wechat.credentialFile !== "string" ||
185
+ !wechat.credentialFile.trim() ||
186
+ !isAbsolute(wechat.credentialFile)
187
+ ) {
188
+ throw new ConfigurationValidationError("wechat.credentialFile 必须是非空绝对路径。");
189
+ }
190
+ return wechat as WechatConfiguration;
191
+ }
192
+
193
+ /**
194
+ * 校验运行时参数并保留扩展字段。
195
+ *
196
+ * @param value 待校验值。
197
+ * @returns 运行时配置对象。
198
+ */
199
+ function validateRuntime(value: unknown): RuntimeConfiguration {
200
+ const runtime = asRecord(value, "runtime");
201
+ const fields: Array<keyof RuntimeConfiguration> = [
202
+ "heartbeatIntervalMs",
203
+ "staleAfterMs",
204
+ "maxBackgroundWorkers",
205
+ "maxQueuePerSession",
206
+ ];
207
+ for (const field of fields) {
208
+ const fieldValue = runtime[field];
209
+ if (typeof fieldValue !== "number" || !Number.isInteger(fieldValue) || fieldValue <= 0) {
210
+ throw new ConfigurationValidationError(`runtime.${field} 必须是正整数。`);
211
+ }
212
+ }
213
+ const staleAfterMs = runtime.staleAfterMs as number;
214
+ const heartbeatIntervalMs = runtime.heartbeatIntervalMs as number;
215
+ if (staleAfterMs <= heartbeatIntervalMs) {
216
+ throw new ConfigurationValidationError(
217
+ "runtime.staleAfterMs 必须大于 runtime.heartbeatIntervalMs。",
218
+ );
219
+ }
220
+ return runtime as RuntimeConfiguration;
221
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * iLink 回复所需的临时上下文, 仅随待处理消息持久化。
3
+ */
4
+ export interface IlinkReplyContext {
5
+ recipientId: string;
6
+ contextToken: string;
7
+ }
8
+
9
+ /**
10
+ * 由 channel adapter 统一后的 Gateway 入站消息。
11
+ */
12
+ export interface GatewayInboundMessage {
13
+ messageId: string;
14
+ senderId: string;
15
+ text: string;
16
+ replyContext?: IlinkReplyContext;
17
+ }
18
+
19
+ /**
20
+ * iLink getupdates 返回的单条消息及 text item 数据结构。
21
+ */
22
+ export interface IlinkTextMessage {
23
+ message_id?: number | string;
24
+ client_id?: string;
25
+ from_user_id?: string;
26
+ to_user_id?: string;
27
+ message_type?: number;
28
+ context_token?: string;
29
+ item_list?: Array<{
30
+ type?: number;
31
+ text_item?: {
32
+ text?: string;
33
+ };
34
+ }>;
35
+ }
36
+
37
+ /**
38
+ * iLink getupdates 的批次响应。
39
+ */
40
+ export interface IlinkGetUpdatesResponse {
41
+ ret?: number;
42
+ errcode?: number;
43
+ errmsg?: string;
44
+ msgs?: IlinkTextMessage[];
45
+ get_updates_buf?: string;
46
+ longpolling_timeout_ms?: number;
47
+ }