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,483 @@
1
+ import { createHash } from "node:crypto";
2
+ import { realpath, stat } from "node:fs/promises";
3
+ import { basename, isAbsolute, relative, resolve, sep } from "node:path";
4
+ import { ConfigurationStore } from "../config/store.ts";
5
+ import { assertProjectAlias } from "../config/validation.ts";
6
+ import type { ManagerConfiguration, ProjectDefinition } from "../config/types.ts";
7
+
8
+ export type ProjectServiceErrorCode =
9
+ | "invalid_alias"
10
+ | "duplicate_alias"
11
+ | "project_alias_not_found"
12
+ | "invalid_display_name"
13
+ | "project_path_denied"
14
+ | "project_directory_not_found"
15
+ | "allowed_root_not_found";
16
+
17
+ /**
18
+ * 表示项目 alias 或目录校验失败。
19
+ */
20
+ export class ProjectServiceError extends Error {
21
+ /**
22
+ * 创建项目服务错误。
23
+ *
24
+ * @param code 稳定错误代码。
25
+ * @param message 面向用户的中文错误信息。
26
+ */
27
+ constructor(
28
+ readonly code: ProjectServiceErrorCode,
29
+ message: string,
30
+ ) {
31
+ super(message);
32
+ this.name = "ProjectServiceError";
33
+ }
34
+ }
35
+
36
+ /**
37
+ * 管理已登记项目及默认项目, 不执行 shell 命令或删除项目目录。
38
+ */
39
+ export class ProjectService {
40
+ /**
41
+ * 创建项目服务。
42
+ *
43
+ * @param store 项目配置存储。
44
+ */
45
+ constructor(private readonly store: ConfigurationStore) {}
46
+
47
+ /**
48
+ * 列出已登记项目并按 alias 排序。
49
+ *
50
+ * @returns 当前配置和项目列表。
51
+ */
52
+ async list(): Promise<{
53
+ config: ManagerConfiguration;
54
+ projects: Array<[string, ProjectDefinition]>;
55
+ }> {
56
+ const { config } = await this.store.load();
57
+ const projects = Object.entries(config.projects).sort(([left], [right]) =>
58
+ left.localeCompare(right),
59
+ );
60
+ return { config, projects };
61
+ }
62
+
63
+ /**
64
+ * 添加一个授权根目录, 后续该目录及其子目录可自动接入 Hub.
65
+ *
66
+ * @param rootPath 用户明确授权的目录.
67
+ * @returns 已规范化的根目录.
68
+ * @throws {ProjectServiceError} 目录不存在或不是绝对路径时抛出.
69
+ */
70
+ async addAllowedRoot(rootPath: string): Promise<string> {
71
+ if (!isAbsolute(rootPath)) {
72
+ throw new ProjectServiceError("project_path_denied", "授权根目录必须是绝对路径.");
73
+ }
74
+ const canonicalRoot = await getCanonicalDirectory(rootPath, "allowed_root_not_found");
75
+ await this.store.update(async (config) => {
76
+ const canonicalRoots = await Promise.all(config.allowedProjectRoots.map((root) =>
77
+ getCanonicalDirectory(root, "allowed_root_not_found"),
78
+ ));
79
+ if (canonicalRoots.some((root) => isWithinDirectory(root, canonicalRoot))) {
80
+ return config;
81
+ }
82
+ return {
83
+ ...config,
84
+ allowedProjectRoots: [...config.allowedProjectRoots, canonicalRoot],
85
+ };
86
+ });
87
+ return canonicalRoot;
88
+ }
89
+
90
+ /**
91
+ * 首次从当前 Pi cwd 建立授权根和默认项目.
92
+ *
93
+ * @param cwd 当前 Pi session 工作目录.
94
+ * @returns 根目录是否由本次初始化添加, 以及当前项目记录.
95
+ * @throws {ProjectServiceError} 当前目录已不在已有授权根内时抛出.
96
+ */
97
+ async initializeFromCurrentCwd(cwd: string): Promise<{
98
+ rootAdded: boolean;
99
+ alias: string;
100
+ project: ProjectDefinition;
101
+ }> {
102
+ const { config } = await this.store.load();
103
+ const rootAdded = config.allowedProjectRoots.length === 0;
104
+ if (rootAdded) {
105
+ await this.addAllowedRoot(cwd);
106
+ }
107
+ const project = await this.ensureProjectForCwd(cwd);
108
+ return { rootAdded, ...project };
109
+ }
110
+
111
+ /**
112
+ * 在授权根内自动创建或复用当前 cwd 对应的项目记录.
113
+ *
114
+ * @param cwd 当前 Pi session 工作目录.
115
+ * @returns 稳定 alias 和以 cwd 文件夹名作为展示名的项目记录.
116
+ * @throws {ProjectServiceError} cwd 不在已授权根目录内时抛出.
117
+ */
118
+ async ensureProjectForCwd(cwd: string): Promise<{
119
+ alias: string;
120
+ project: ProjectDefinition;
121
+ }> {
122
+ let resolved: { alias: string; project: ProjectDefinition } | undefined;
123
+ await this.store.update(async (config) => {
124
+ const canonicalPath = await validateProjectDirectory(cwd, config.allowedProjectRoots);
125
+ for (const [alias, project] of Object.entries(config.projects)) {
126
+ try {
127
+ const projectPath = await getCanonicalDirectory(project.path, "project_directory_not_found");
128
+ if (samePath(projectPath, canonicalPath)) {
129
+ resolved = { alias, project: { ...project, path: projectPath } };
130
+ return config.defaultProject ? config : { ...config, defaultProject: alias };
131
+ }
132
+ } catch (error) {
133
+ if (!(error instanceof ProjectServiceError)) {
134
+ throw error;
135
+ }
136
+ }
137
+ }
138
+
139
+ const displayName = basename(canonicalPath) || canonicalPath;
140
+ const alias = createProjectAlias(config.projects, displayName, canonicalPath);
141
+ const project = { displayName, path: canonicalPath };
142
+ resolved = { alias, project };
143
+ return {
144
+ ...config,
145
+ defaultProject: config.defaultProject ?? alias,
146
+ projects: {
147
+ ...config.projects,
148
+ [alias]: project,
149
+ },
150
+ };
151
+ });
152
+ if (!resolved) {
153
+ throw new ProjectServiceError("project_alias_not_found", "无法为当前目录建立项目记录.");
154
+ }
155
+ return resolved;
156
+ }
157
+
158
+ /**
159
+ * 添加一个通过允许根目录检查的项目 alias。
160
+ *
161
+ * @param alias 项目稳定 ID。
162
+ * @param displayName 面向用户显示的名称。
163
+ * @param projectPath 项目目录绝对路径。
164
+ * @returns 新登记的项目定义。
165
+ * @throws {ProjectServiceError} alias、路径或允许根目录非法时抛出。
166
+ */
167
+ async add(
168
+ alias: string,
169
+ displayName: string,
170
+ projectPath: string,
171
+ ): Promise<ProjectDefinition> {
172
+ assertAlias(alias);
173
+ const normalizedName = displayName.trim();
174
+ if (!normalizedName || normalizedName.length > 100) {
175
+ throw new ProjectServiceError(
176
+ "invalid_display_name",
177
+ "项目显示名称需为 1-100 个字符。",
178
+ );
179
+ }
180
+
181
+ let addedProject: ProjectDefinition | undefined;
182
+ await this.store.update(async (config) => {
183
+ if (Object.hasOwn(config.projects, alias)) {
184
+ throw new ProjectServiceError(
185
+ "duplicate_alias",
186
+ `项目 alias 已存在: ${alias}。如需替换, 请先移除旧 alias。`,
187
+ );
188
+ }
189
+ const canonicalPath = await validateProjectDirectory(
190
+ projectPath,
191
+ config.allowedProjectRoots,
192
+ );
193
+ const project: ProjectDefinition = {
194
+ displayName: normalizedName,
195
+ path: canonicalPath,
196
+ };
197
+ addedProject = project;
198
+ return {
199
+ ...config,
200
+ projects: {
201
+ ...config.projects,
202
+ [alias]: project,
203
+ },
204
+ };
205
+ });
206
+
207
+ if (!addedProject) {
208
+ throw new Error("项目登记未产生结果。");
209
+ }
210
+ return addedProject;
211
+ }
212
+
213
+ /**
214
+ * 解析已登记 alias 并在启动前重新验证真实路径和授权根目录。
215
+ *
216
+ * @param alias 项目稳定 ID。
217
+ * @returns 可安全用于 worker cwd 的项目定义。
218
+ * @throws {ProjectServiceError} alias 不存在或路径已越界时抛出。
219
+ */
220
+ async resolve(alias: string): Promise<ProjectDefinition> {
221
+ assertAlias(alias);
222
+ const { config } = await this.store.load();
223
+ if (!Object.hasOwn(config.projects, alias)) {
224
+ throw new ProjectServiceError(
225
+ "project_alias_not_found",
226
+ `未找到项目 alias: ${alias}。`,
227
+ );
228
+ }
229
+ const project = config.projects[alias];
230
+ const canonicalPath = await validateProjectDirectory(
231
+ project.path,
232
+ config.allowedProjectRoots,
233
+ );
234
+ return {
235
+ ...project,
236
+ path: canonicalPath,
237
+ };
238
+ }
239
+
240
+ /**
241
+ * 按 session 创建时记录的 cwd 恢复项目上下文, 即使 alias 已移除或改指向其他路径。
242
+ *
243
+ * @param alias session 索引中的项目 alias。
244
+ * @param sessionCwd session 创建时的工作目录。
245
+ * @returns 仍在授权根目录内的原项目路径及显示名称。
246
+ * @throws {ProjectServiceError} 原路径不存在或已越过授权根目录时抛出。
247
+ */
248
+ async resolveSession(alias: string, sessionCwd: string): Promise<ProjectDefinition> {
249
+ assertAlias(alias);
250
+ const { config } = await this.store.load();
251
+ const canonicalPath = await validateProjectDirectory(
252
+ sessionCwd,
253
+ config.allowedProjectRoots,
254
+ );
255
+ const displayName = Object.hasOwn(config.projects, alias)
256
+ ? config.projects[alias].displayName
257
+ : alias;
258
+ return {
259
+ displayName,
260
+ path: canonicalPath,
261
+ };
262
+ }
263
+
264
+ /**
265
+ * 移除项目登记, 不删除实际目录, 并清除对应的默认项目设置。
266
+ *
267
+ * @param alias 要移除的项目 alias。
268
+ * @returns 更新后的配置。
269
+ * @throws {ProjectServiceError} alias 未登记时抛出。
270
+ */
271
+ async remove(alias: string): Promise<ManagerConfiguration> {
272
+ assertAlias(alias);
273
+ return this.store.update((config) => {
274
+ if (!Object.hasOwn(config.projects, alias)) {
275
+ throw new ProjectServiceError(
276
+ "project_alias_not_found",
277
+ `未找到项目 alias: ${alias}。`,
278
+ );
279
+ }
280
+ const projects = { ...config.projects };
281
+ delete projects[alias];
282
+ const next: ManagerConfiguration = {
283
+ ...config,
284
+ projects,
285
+ };
286
+ if (config.defaultProject === alias) {
287
+ delete next.defaultProject;
288
+ }
289
+ return next;
290
+ });
291
+ }
292
+
293
+ /**
294
+ * 设置默认项目 alias。
295
+ *
296
+ * @param alias 要设为默认的项目 alias。
297
+ * @returns 更新后的配置。
298
+ * @throws {ProjectServiceError} alias 未登记时抛出。
299
+ */
300
+ async setDefault(alias: string): Promise<ManagerConfiguration> {
301
+ assertAlias(alias);
302
+ return this.store.update((config) => {
303
+ if (!Object.hasOwn(config.projects, alias)) {
304
+ throw new ProjectServiceError(
305
+ "project_alias_not_found",
306
+ `未找到项目 alias: ${alias}。`,
307
+ );
308
+ }
309
+ return {
310
+ ...config,
311
+ defaultProject: alias,
312
+ };
313
+ });
314
+ }
315
+ }
316
+
317
+ /**
318
+ * 校验项目目录存在且位于某个已授权根目录中。
319
+ *
320
+ * @param projectPath 用户提交的项目目录。
321
+ * @param allowedRoots 已授权目录根列表。
322
+ * @returns 真实路径, 用于持久化和后续启动。
323
+ * @throws {ProjectServiceError} 路径不存在或越界时抛出。
324
+ */
325
+ export async function validateProjectDirectory(
326
+ projectPath: string,
327
+ allowedRoots: string[],
328
+ ): Promise<string> {
329
+ if (!isAbsolute(projectPath)) {
330
+ throw new ProjectServiceError(
331
+ "project_path_denied",
332
+ "项目路径必须是绝对路径。",
333
+ );
334
+ }
335
+
336
+ const canonicalProjectPath = await getCanonicalDirectory(projectPath, "project_directory_not_found");
337
+ if (allowedRoots.length === 0) {
338
+ throw new ProjectServiceError(
339
+ "project_path_denied",
340
+ "尚未配置 allowedProjectRoots, 请先在配置文件中登记授权根目录。",
341
+ );
342
+ }
343
+
344
+ const canonicalRoots = await Promise.all(
345
+ allowedRoots.map(async (root) => {
346
+ if (!isAbsolute(root)) {
347
+ throw new ProjectServiceError(
348
+ "project_path_denied",
349
+ "allowedProjectRoots 中存在非绝对路径。",
350
+ );
351
+ }
352
+ return getCanonicalDirectory(root, "allowed_root_not_found");
353
+ }),
354
+ );
355
+
356
+ const isAllowed = canonicalRoots.some((root) => isWithinDirectory(root, canonicalProjectPath));
357
+ if (!isAllowed) {
358
+ throw new ProjectServiceError(
359
+ "project_path_denied",
360
+ "项目路径不在任何 allowedProjectRoots 目录内。",
361
+ );
362
+ }
363
+ return canonicalProjectPath;
364
+ }
365
+
366
+ /**
367
+ * 解析并确认路径指向现存目录。
368
+ *
369
+ * @param directoryPath 待检查目录。
370
+ * @param errorCode 路径不存在时返回的错误代码。
371
+ * @returns 目录真实路径。
372
+ */
373
+ async function getCanonicalDirectory(
374
+ directoryPath: string,
375
+ errorCode: "project_directory_not_found" | "allowed_root_not_found",
376
+ ): Promise<string> {
377
+ try {
378
+ const canonicalPath = await realpath(resolve(directoryPath));
379
+ const directoryStat = await stat(canonicalPath);
380
+ if (!directoryStat.isDirectory()) {
381
+ throw new Error("not_directory");
382
+ }
383
+ return canonicalPath;
384
+ } catch {
385
+ const message = errorCode === "allowed_root_not_found"
386
+ ? "allowedProjectRoots 中的目录不存在或不是目录。"
387
+ : "项目目录不存在或不是目录。";
388
+ throw new ProjectServiceError(errorCode, message);
389
+ }
390
+ }
391
+
392
+ /**
393
+ * 判断目标路径是否等于根目录或位于其子目录。
394
+ *
395
+ * @param root 规范化的授权根目录。
396
+ * @param target 规范化的目标目录。
397
+ * @returns 目标位于根目录范围内时返回 true。
398
+ */
399
+ function isWithinDirectory(root: string, target: string): boolean {
400
+ const normalizedRoot = process.platform === "win32" ? root.toLowerCase() : root;
401
+ const normalizedTarget = process.platform === "win32" ? target.toLowerCase() : target;
402
+ const relativePath = relative(normalizedRoot, normalizedTarget);
403
+ return relativePath === "" || (
404
+ relativePath !== ".." &&
405
+ !relativePath.startsWith(`..${sep}`) &&
406
+ !isAbsolute(relativePath)
407
+ );
408
+ }
409
+
410
+ /**
411
+ * 比较两个规范化目录路径, 在 Windows 上忽略大小写.
412
+ *
413
+ * @param left 左侧路径.
414
+ * @param right 右侧路径.
415
+ * @returns 两条路径指向同一规范化位置时返回 true.
416
+ */
417
+ function samePath(left: string, right: string): boolean {
418
+ const normalizedLeft = resolve(left);
419
+ const normalizedRight = resolve(right);
420
+ return process.platform === "win32"
421
+ ? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
422
+ : normalizedLeft === normalizedRight;
423
+ }
424
+
425
+ /**
426
+ * 根据文件夹名生成稳定且无冲突的项目 alias.
427
+ *
428
+ * @param projects 当前项目记录.
429
+ * @param displayName 当前文件夹名称.
430
+ * @param projectPath 已规范化的项目路径.
431
+ * @returns 满足配置 schema 的唯一 alias.
432
+ */
433
+ function createProjectAlias(
434
+ projects: Record<string, ProjectDefinition>,
435
+ displayName: string,
436
+ projectPath: string,
437
+ ): string {
438
+ const base = displayName
439
+ .normalize("NFKD")
440
+ .toLowerCase()
441
+ .replace(/[^a-z0-9_-]+/g, "-")
442
+ .replace(/^-+|-+$/g, "")
443
+ .slice(0, 32)
444
+ .replace(/-+$/g, "") || "project";
445
+ if (!Object.hasOwn(projects, base)) {
446
+ return base;
447
+ }
448
+
449
+ const pathHash = createHash("sha256")
450
+ .update(process.platform === "win32" ? projectPath.toLowerCase() : projectPath)
451
+ .digest("hex")
452
+ .slice(0, 8);
453
+ const prefix = base.slice(0, 19).replace(/-+$/g, "") || "project";
454
+ const withHash = `${prefix}-${pathHash}`;
455
+ if (!Object.hasOwn(projects, withHash)) {
456
+ return withHash;
457
+ }
458
+ let index = 2;
459
+ let candidate = `${prefix}-${pathHash}-${index}`;
460
+ while (Object.hasOwn(projects, candidate)) {
461
+ index += 1;
462
+ candidate = `${prefix}-${pathHash}-${index}`;
463
+ }
464
+ return candidate;
465
+ }
466
+
467
+ /**
468
+ * 将配置校验错误转换为项目服务稳定错误代码.
469
+ *
470
+ * @param alias 待校验 alias。
471
+ * @returns 无返回值。
472
+ * @throws {ProjectServiceError} alias 非法时抛出。
473
+ */
474
+ function assertAlias(alias: string): void {
475
+ try {
476
+ assertProjectAlias(alias);
477
+ } catch {
478
+ throw new ProjectServiceError(
479
+ "invalid_alias",
480
+ "alias 需为 1-32 位小写字母、数字、下划线或连字符, 且以字母或数字开头。",
481
+ );
482
+ }
483
+ }