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,150 @@
1
+ import assert from "node:assert/strict";
2
+ import { spawn } from "node:child_process";
3
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ const projectDirectory = resolve(dirname(fileURLToPath(import.meta.url)), "..");
9
+ const packageDirectory = join(
10
+ projectDirectory,
11
+ "node_modules",
12
+ "@earendil-works",
13
+ "pi-coding-agent",
14
+ );
15
+ const packageManifest = JSON.parse(
16
+ await readFile(join(packageDirectory, "package.json"), "utf8"),
17
+ );
18
+ const cliRelativePath = packageManifest.bin?.pi;
19
+ assert.equal(typeof cliRelativePath, "string", "Pi package 未声明 pi CLI 入口。");
20
+
21
+ const temporaryDirectory = await mkdtemp(join(tmpdir(), "pi-wechat-runtime-smoke-"));
22
+ const extensionPath = join(projectDirectory, "extensions", "wechat-session-hub.ts");
23
+ const cliPath = join(packageDirectory, cliRelativePath);
24
+
25
+ try {
26
+ const output = await runRpcSmoke(cliPath, extensionPath, temporaryDirectory);
27
+ const records = output.stdout
28
+ .split(/\r?\n/)
29
+ .filter(Boolean)
30
+ .map((line) => JSON.parse(line));
31
+ const statusNotices = records.filter((record) =>
32
+ record.type === "extension_ui_request" &&
33
+ record.method === "notify" &&
34
+ record.message?.includes("微信连接: 已停止"),
35
+ );
36
+ const helpNotices = records.filter((record) =>
37
+ record.type === "extension_ui_request" &&
38
+ record.method === "notify" &&
39
+ record.message?.includes("Pi 微信会话枢纽命令:") &&
40
+ record.message?.includes("/wx roots"),
41
+ );
42
+ const promptResponses = records.filter((record) =>
43
+ record.type === "response" &&
44
+ record.command === "prompt" &&
45
+ record.success === true &&
46
+ ["wx-status-smoke", "wx-help-smoke", "compat-manager-smoke"].includes(record.id),
47
+ );
48
+
49
+ assert.equal(statusNotices.length, 2, `Pi RPC 未收到两个 /wx status 通知: ${JSON.stringify(records)}\n${output.stderr}`);
50
+ assert.equal(helpNotices.length, 1, `Pi RPC 未收到 /wx help 通知: ${JSON.stringify(records)}\n${output.stderr}`);
51
+ assert.equal(promptResponses.length, 3, `Pi RPC 未接受 /wx status、/wx help 和兼容别名命令: ${JSON.stringify(records)}\n${output.stderr}`);
52
+ process.stdout.write(`Pi ${packageManifest.version} 扩展 RPC smoke test 通过。\n`);
53
+ } finally {
54
+ await rm(temporaryDirectory, { recursive: true, force: true });
55
+ }
56
+
57
+ /**
58
+ * 启动隔离的 Pi RPC 进程并发送不触发模型调用的扩展状态命令。
59
+ *
60
+ * @param cliPath Pi CLI JavaScript 入口路径。
61
+ * @param extensionPath 本项目扩展入口路径。
62
+ * @param temporaryDirectory 隔离配置目录。
63
+ * @returns Pi stdout 与 stderr。
64
+ */
65
+ function runRpcSmoke(cliPath, extensionPath, temporaryDirectory) {
66
+ return new Promise((resolveOutput, rejectOutput) => {
67
+ const child = spawn(
68
+ process.execPath,
69
+ [
70
+ cliPath,
71
+ "--mode",
72
+ "rpc",
73
+ "--no-session",
74
+ "--no-extensions",
75
+ "--no-skills",
76
+ "--no-prompt-templates",
77
+ "--extension",
78
+ extensionPath,
79
+ "--no-context-files",
80
+ ],
81
+ {
82
+ cwd: projectDirectory,
83
+ env: {
84
+ ...process.env,
85
+ PI_CODING_AGENT_DIR: temporaryDirectory,
86
+ PI_CODING_AGENT_SESSION_DIR: join(temporaryDirectory, "sessions"),
87
+ PI_OFFLINE: "1",
88
+ PI_SKIP_VERSION_CHECK: "1",
89
+ },
90
+ stdio: ["pipe", "pipe", "pipe"],
91
+ },
92
+ );
93
+ let stdout = "";
94
+ let stderr = "";
95
+ let pendingOutputLine = "";
96
+ const expectedResponseIds = new Set(["wx-status-smoke", "wx-help-smoke", "compat-manager-smoke"]);
97
+ const completedResponseIds = new Set();
98
+ const timeout = setTimeout(() => {
99
+ child.kill();
100
+ rejectOutput(new Error("Pi RPC smoke test 超时。"));
101
+ }, 15000);
102
+
103
+ child.stdout.setEncoding("utf8");
104
+ child.stderr.setEncoding("utf8");
105
+ child.stdout.on("data", (chunk) => {
106
+ stdout += chunk;
107
+ pendingOutputLine += chunk;
108
+ const lines = pendingOutputLine.split(/\r?\n/);
109
+ pendingOutputLine = lines.pop() ?? "";
110
+ for (const line of lines) {
111
+ if (!line) continue;
112
+ try {
113
+ const record = JSON.parse(line);
114
+ if (
115
+ record.type === "response" &&
116
+ record.command === "prompt" &&
117
+ expectedResponseIds.has(record.id)
118
+ ) {
119
+ completedResponseIds.add(record.id);
120
+ }
121
+ } catch {
122
+ continue;
123
+ }
124
+ }
125
+ if (completedResponseIds.size === expectedResponseIds.size && !child.stdin.destroyed) {
126
+ child.stdin.end();
127
+ }
128
+ });
129
+ child.stderr.on("data", (chunk) => {
130
+ stderr += chunk;
131
+ });
132
+ child.on("error", (error) => {
133
+ clearTimeout(timeout);
134
+ rejectOutput(error);
135
+ });
136
+ child.on("close", (code) => {
137
+ clearTimeout(timeout);
138
+ if (code !== 0) {
139
+ rejectOutput(new Error(`Pi RPC 退出码为 ${code}: ${stderr}`));
140
+ return;
141
+ }
142
+ resolveOutput({ stdout, stderr });
143
+ });
144
+ child.stdin.write([
145
+ { id: "wx-status-smoke", type: "prompt", message: "/wx status" },
146
+ { id: "wx-help-smoke", type: "prompt", message: "/wx help" },
147
+ { id: "compat-manager-smoke", type: "prompt", message: "/wechat-manager status" },
148
+ ].map((request) => JSON.stringify(request)).join("\n") + "\n");
149
+ });
150
+ }
@@ -0,0 +1,27 @@
1
+ import { isAbsolute, basename } from "node:path";
2
+ import { resolveWindowsTerminalExecutable } from "../src/gateway/windows-terminal-launcher.ts";
3
+
4
+ /**
5
+ * 校验可见 UI 模式的真实平台探测自洽。
6
+ *
7
+ * 注意 Windows Terminal 常以 App Execution Alias 形式存在(位于
8
+ * `%LOCALAPPDATA%\Microsoft\WindowsApps`)。该目录权限受限, 对别名执行
9
+ * `existsSync` / `Test-Path` 会返回 false, 因此这里不复检文件存在性,
10
+ * 而是断言解析结果自洽: 绝对路径且文件名为 `wt.exe`。
11
+ *
12
+ * @returns 探测结果自洽时正常结束。
13
+ * @throws {Error} 解析结果不是绝对 wt.exe 路径时抛出。
14
+ */
15
+ async function main() {
16
+ const executable = await resolveWindowsTerminalExecutable();
17
+ console.log(`已解析 wt.exe: ${executable}`);
18
+ if (!isAbsolute(executable) || basename(executable).toLowerCase() !== "wt.exe") {
19
+ throw new Error(`解析结果不是绝对 wt.exe 路径: ${executable}`);
20
+ }
21
+ if (/[\\/]Microsoft[\\/]WindowsApps[\\/]wt\.exe$/i.test(executable)) {
22
+ console.log("该路径为 App Execution Alias, 按设计跳过存在性复检。");
23
+ }
24
+ console.log("可见 UI 模式前置探测通过。");
25
+ }
26
+
27
+ await main();
@@ -0,0 +1,37 @@
1
+ $ErrorActionPreference = 'Stop'
2
+ if ($args.Count -ne 2) {
3
+ exit 31
4
+ }
5
+ $managerDirectory = [System.IO.Path]::GetFullPath($args[0])
6
+ $launchId = $args[1]
7
+ if ($launchId -notmatch '^[a-fA-F0-9-]{36}$') {
8
+ exit 32
9
+ }
10
+ $launchDirectory = Join-Path $managerDirectory 'launches'
11
+ $launchFile = Join-Path $launchDirectory ($launchId + '.json')
12
+ $record = Get-Content -LiteralPath $launchFile -Raw -Encoding UTF8 | ConvertFrom-Json
13
+ if ($record.schemaVersion -ne 1 -or $record.launchId -ne $launchId -or $record.managerDirectory -ne $managerDirectory) {
14
+ exit 33
15
+ }
16
+ $env:PI_CODING_AGENT_DIR = $record.agentDirectory
17
+ $env:PI_WECHAT_MANAGER_DIR = $managerDirectory
18
+ $env:PI_WECHAT_MANAGER_LAUNCH_ID = $launchId
19
+ $env:PI_WECHAT_MANAGER_PIPE = $record.pipeEndpoint
20
+ $startInfo = [System.Diagnostics.ProcessStartInfo]::new()
21
+ $startInfo.FileName = $record.nodeExecutable
22
+ $startInfo.WorkingDirectory = $record.projectPath
23
+ $startInfo.UseShellExecute = $false
24
+ $startInfo.ArgumentList.Add($record.piCliEntry)
25
+ $startInfo.ArgumentList.Add('--extension')
26
+ $startInfo.ArgumentList.Add($record.extensionPath)
27
+ if ($record.sessionName) {
28
+ $startInfo.ArgumentList.Add('--name')
29
+ $startInfo.ArgumentList.Add($record.sessionName)
30
+ }
31
+ if ($record.mode -eq 'resume') {
32
+ $startInfo.ArgumentList.Add('--session')
33
+ $startInfo.ArgumentList.Add($record.sessionFile)
34
+ }
35
+ $process = [System.Diagnostics.Process]::Start($startInfo)
36
+ $process.WaitForExit()
37
+ exit $process.ExitCode
@@ -0,0 +1,148 @@
1
+ const ANSI_SEQUENCE = /\u001B\[[0-?]*[ -/]*[@-~]/g;
2
+
3
+ /**
4
+ * 在 Pi TUI 中显示临时 iLink QR 和扫码状态。
5
+ */
6
+ export class IlinkQrLoginComponent {
7
+ private status: string;
8
+ private qrLines: string[] = [];
9
+
10
+ /**
11
+ * 创建二维码登录界面。
12
+ *
13
+ * @param onCancel Escape / Ctrl+C 回调。
14
+ * @param initialStatus 初始化状态。
15
+ */
16
+ constructor(
17
+ private readonly onCancel: () => void,
18
+ initialStatus = "正在连接 iLink 授权服务...",
19
+ ) {
20
+ this.status = initialStatus;
21
+ }
22
+
23
+ /**
24
+ * 更新待扫描的终端二维码内容。
25
+ *
26
+ * @param terminalQr ANSI 终端二维码文本。
27
+ * @returns 无返回值。
28
+ */
29
+ setQr(terminalQr: string): void {
30
+ this.qrLines = terminalQr.replace(/\r/g, "").split("\n").filter((line) => line.length > 0);
31
+ }
32
+
33
+ /**
34
+ * 更新授权状态提示。
35
+ *
36
+ * @param status 新状态。
37
+ * @returns 无返回值。
38
+ */
39
+ setStatus(status: string): void {
40
+ this.status = status;
41
+ }
42
+
43
+ /**
44
+ * 渲染二维码和授权安全提示。
45
+ *
46
+ * @param width 当前 TUI 可用列数。
47
+ * @returns 每行宽度不超过 width 的文本。
48
+ */
49
+ render(width: number): string[] {
50
+ const lines = [
51
+ "Pi Hub 微信授权",
52
+ "请确认该微信/iLink 账号没有被其他客户端同时轮询。",
53
+ "本流程只写入 Pi Hub 自己的 credentials.json, 不读取或修改其他客户端数据。",
54
+ `状态: ${this.status}`,
55
+ "",
56
+ ].map((line) => truncateDisplayWidth(line, width));
57
+
58
+ if (this.qrLines.some((line) => displayWidth(line) > width)) {
59
+ lines.push(truncateDisplayWidth("终端宽度不足以完整显示二维码, 请扩大终端后重试.", width));
60
+ } else {
61
+ lines.push(...this.qrLines);
62
+ }
63
+ lines.push("");
64
+ lines.push(truncateDisplayWidth("使用手机微信扫描二维码并确认授权. 按 Esc 取消.", width));
65
+ return lines;
66
+ }
67
+
68
+ /**
69
+ * 处理用户取消按键。
70
+ *
71
+ * @param data TUI 输入序列。
72
+ * @returns Escape 或 Ctrl+C 时调用 onCancel。
73
+ */
74
+ handleInput(data: string): void {
75
+ if (data === "\u001b" || data === "\u0003") {
76
+ this.onCancel();
77
+ }
78
+ }
79
+
80
+ /**
81
+ * 当前组件不缓存渲染内容, 无需额外处理 theme invalidate。
82
+ *
83
+ * @returns 无返回值。
84
+ */
85
+ invalidate(): void {}
86
+ }
87
+
88
+ /**
89
+ * 计算去除 ANSI 控制码后的终端显示宽度。
90
+ *
91
+ * @param value 待测文本。
92
+ * @returns 估算的终端列宽。
93
+ */
94
+ function displayWidth(value: string): number {
95
+ return Array.from(value.replace(ANSI_SEQUENCE, "")).reduce((width, character) => {
96
+ const codePoint = character.codePointAt(0) ?? 0;
97
+ return width + (isWideCharacter(codePoint) ? 2 : codePoint < 0x20 ? 0 : 1);
98
+ }, 0);
99
+ }
100
+
101
+ /**
102
+ * 将文本按终端列宽截断, 保证渲染行不越界。
103
+ *
104
+ * @param value 待截断文本。
105
+ * @param maxWidth 最大终端列宽。
106
+ * @returns 宽度不超过 maxWidth 的文本。
107
+ */
108
+ function truncateDisplayWidth(value: string, maxWidth: number): string {
109
+ if (maxWidth <= 0) {
110
+ return "";
111
+ }
112
+ let output = "";
113
+ let width = 0;
114
+ for (const character of value) {
115
+ const codePoint = character.codePointAt(0) ?? 0;
116
+ const characterWidth = isWideCharacter(codePoint) ? 2 : 1;
117
+ if (width + characterWidth > maxWidth) {
118
+ break;
119
+ }
120
+ output += character;
121
+ width += characterWidth;
122
+ }
123
+ return output;
124
+ }
125
+
126
+ /**
127
+ * 识别常见的 CJK 和 emoji wide code points。
128
+ *
129
+ * @param codePoint Unicode code point。
130
+ * @returns 字符通常占用两列时返回 true。
131
+ */
132
+ function isWideCharacter(codePoint: number): boolean {
133
+ return (
134
+ codePoint >= 0x1100 && (
135
+ codePoint <= 0x115f ||
136
+ codePoint === 0x2329 || codePoint === 0x232a ||
137
+ (codePoint >= 0x2e80 && codePoint <= 0xa4cf) ||
138
+ (codePoint >= 0xac00 && codePoint <= 0xd7a3) ||
139
+ (codePoint >= 0xf900 && codePoint <= 0xfaff) ||
140
+ (codePoint >= 0xfe10 && codePoint <= 0xfe19) ||
141
+ (codePoint >= 0xfe30 && codePoint <= 0xfe6f) ||
142
+ (codePoint >= 0xff00 && codePoint <= 0xff60) ||
143
+ (codePoint >= 0xffe0 && codePoint <= 0xffe6) ||
144
+ (codePoint >= 0x1f300 && codePoint <= 0x1faff) ||
145
+ (codePoint >= 0x20000 && codePoint <= 0x3fffd)
146
+ )
147
+ );
148
+ }
@@ -0,0 +1,108 @@
1
+ import { CommandTokenizeError, tokenizeCommandArguments } from "./tokenizer.ts";
2
+
3
+ export type ProjectCommand =
4
+ | { action: "list" }
5
+ | { action: "add"; alias: string; displayName: string; path: string }
6
+ | { action: "remove"; alias: string }
7
+ | { action: "default"; alias: string };
8
+
9
+ /**
10
+ * 表示 /projects 命令参数格式错误。
11
+ */
12
+ export class ProjectCommandParseError extends Error {
13
+ /**
14
+ * 创建命令参数错误。
15
+ *
16
+ * @param message 面向用户的中文错误信息。
17
+ */
18
+ constructor(message: string) {
19
+ super(message);
20
+ this.name = "ProjectCommandParseError";
21
+ }
22
+ }
23
+
24
+ /**
25
+ * 解析 /projects 子命令, 并支持带空格的单引号或双引号参数。
26
+ *
27
+ * @param input Pi command handler 收到的原始参数。
28
+ * @returns 规范化后的项目命令。
29
+ * @throws {ProjectCommandParseError} 参数格式不合法时抛出。
30
+ */
31
+ export function parseProjectCommand(input: string): ProjectCommand {
32
+ let tokens: string[];
33
+ try {
34
+ tokens = tokenizeCommandArguments(input);
35
+ } catch (error) {
36
+ if (error instanceof CommandTokenizeError) {
37
+ throw new ProjectCommandParseError(`${error.message}\n${PROJECT_COMMAND_USAGE}`);
38
+ }
39
+ throw error;
40
+ }
41
+ if (tokens.length === 0 || tokens[0] === "list") {
42
+ if (tokens.length > 1) {
43
+ throw usageError();
44
+ }
45
+ return { action: "list" };
46
+ }
47
+
48
+ const [action, alias, ...arguments_] = tokens;
49
+ if (action === "remove" || action === "default") {
50
+ if (!alias || arguments_.length > 0) {
51
+ throw usageError();
52
+ }
53
+ return { action, alias };
54
+ }
55
+
56
+ if (action !== "add" || !alias) {
57
+ throw usageError();
58
+ }
59
+
60
+ const options = new Map<string, string>();
61
+ for (let index = 0; index < arguments_.length; index += 1) {
62
+ const argument = arguments_[index];
63
+ if (!argument.startsWith("--")) {
64
+ throw usageError();
65
+ }
66
+ const equalsIndex = argument.indexOf("=");
67
+ const optionName = equalsIndex >= 0 ? argument.slice(2, equalsIndex) : argument.slice(2);
68
+ const inlineValue = equalsIndex >= 0 ? argument.slice(equalsIndex + 1) : undefined;
69
+ if (optionName !== "name" && optionName !== "path") {
70
+ throw new ProjectCommandParseError(`未知参数: --${optionName}。\n${PROJECT_COMMAND_USAGE}`);
71
+ }
72
+ if (options.has(optionName)) {
73
+ throw new ProjectCommandParseError(`参数 --${optionName} 不能重复。\n${PROJECT_COMMAND_USAGE}`);
74
+ }
75
+ const value = inlineValue ?? arguments_[index + 1];
76
+ if (value === undefined || (inlineValue === undefined && value.startsWith("--"))) {
77
+ throw usageError();
78
+ }
79
+ options.set(optionName, value);
80
+ if (inlineValue === undefined) {
81
+ index += 1;
82
+ }
83
+ }
84
+
85
+ const displayName = options.get("name");
86
+ const path = options.get("path");
87
+ if (!displayName || !path) {
88
+ throw usageError();
89
+ }
90
+ return {
91
+ action: "add",
92
+ alias,
93
+ displayName,
94
+ path,
95
+ };
96
+ }
97
+
98
+ const PROJECT_COMMAND_USAGE =
99
+ "用法: /projects | /projects add <alias> --name <名称> --path <绝对路径> | /projects remove <alias> | /projects default <alias>";
100
+
101
+ /**
102
+ * 创建统一格式的命令用法错误。
103
+ *
104
+ * @returns 命令参数错误。
105
+ */
106
+ function usageError(): ProjectCommandParseError {
107
+ return new ProjectCommandParseError(PROJECT_COMMAND_USAGE);
108
+ }
@@ -0,0 +1,71 @@
1
+ export class CommandTokenizeError extends Error {
2
+ /**
3
+ * 创建命令分词错误。
4
+ *
5
+ * @param message 面向用户的中文错误信息。
6
+ */
7
+ constructor(message: string) {
8
+ super(message);
9
+ this.name = "CommandTokenizeError";
10
+ }
11
+ }
12
+
13
+ /**
14
+ * 按单引号和双引号分词, 不执行 shell expansion。
15
+ *
16
+ * @param input 原始命令行参数。
17
+ * @returns 分词结果。
18
+ * @throws {CommandTokenizeError} 引号未闭合时抛出。
19
+ */
20
+ export function tokenizeCommandArguments(input: string): string[] {
21
+ const tokens: string[] = [];
22
+ let current = "";
23
+ let quote: "'" | '"' | undefined;
24
+ let tokenStarted = false;
25
+
26
+ for (let index = 0; index < input.length; index += 1) {
27
+ const character = input[index];
28
+ if (quote) {
29
+ if (character === quote) {
30
+ quote = undefined;
31
+ tokenStarted = true;
32
+ } else if (
33
+ quote === '"' &&
34
+ character === "\\" &&
35
+ (input[index + 1] === '"' || input[index + 1] === "\\")
36
+ ) {
37
+ current += input[index + 1];
38
+ index += 1;
39
+ tokenStarted = true;
40
+ } else {
41
+ current += character;
42
+ tokenStarted = true;
43
+ }
44
+ continue;
45
+ }
46
+
47
+ if (character === '"' || character === "'") {
48
+ quote = character;
49
+ tokenStarted = true;
50
+ continue;
51
+ }
52
+ if (/\s/.test(character)) {
53
+ if (tokenStarted) {
54
+ tokens.push(current);
55
+ current = "";
56
+ tokenStarted = false;
57
+ }
58
+ continue;
59
+ }
60
+ current += character;
61
+ tokenStarted = true;
62
+ }
63
+
64
+ if (quote) {
65
+ throw new CommandTokenizeError("命令参数中的引号未闭合。");
66
+ }
67
+ if (tokenStarted) {
68
+ tokens.push(current);
69
+ }
70
+ return tokens;
71
+ }
@@ -0,0 +1,143 @@
1
+ import { CommandTokenizeError, tokenizeCommandArguments } from "./tokenizer.ts";
2
+ import { parseProjectCommand, type ProjectCommand, ProjectCommandParseError } from "./project-command-parser.ts";
3
+
4
+ export type WechatManagerCommand =
5
+ | { action: "help" }
6
+ | { action: "login" }
7
+ | { action: "start" }
8
+ | { action: "stop" }
9
+ | { action: "restart" }
10
+ | { action: "status" }
11
+ | { action: "autostart"; enabled: boolean }
12
+ | { action: "projects"; command: ProjectCommand }
13
+ | { action: "roots"; operation: "list" | "add-current" | "add"; path?: string };
14
+
15
+ export interface WechatManagerCommandCompletion {
16
+ value: string;
17
+ label: string;
18
+ description: string;
19
+ }
20
+
21
+ const COMMAND_COMPLETIONS: WechatManagerCommandCompletion[] = [
22
+ { value: "login", label: "login", description: "使用微信扫码授权" },
23
+ { value: "start", label: "start", description: "启动后台微信连接" },
24
+ { value: "status", label: "status", description: "查看连接和会话状态" },
25
+ { value: "stop", label: "stop", description: "确认后停止后台连接" },
26
+ { value: "restart", label: "restart", description: "重启后台连接" },
27
+ { value: "autostart on", label: "autostart on", description: "登录 Windows 后自动连接" },
28
+ { value: "autostart off", label: "autostart off", description: "关闭登录后自动连接" },
29
+ { value: "projects", label: "projects", description: "查看和管理项目" },
30
+ { value: "projects add", label: "projects add", description: "手动登记项目" },
31
+ { value: "projects default", label: "projects default", description: "设置默认项目" },
32
+ { value: "roots", label: "roots", description: "查看授权根目录" },
33
+ { value: "roots add-current", label: "roots add-current", description: "授权当前目录及其子目录" },
34
+ { value: "roots add", label: "roots add", description: "添加一个授权根目录" },
35
+ { value: "help", label: "help", description: "查看命令说明" },
36
+ ];
37
+
38
+ /**
39
+ * 表示 /wx 参数不符合受支持的控制命令.
40
+ */
41
+ export class WechatManagerCommandParseError extends Error {
42
+ /**
43
+ * 创建命令参数错误.
44
+ *
45
+ * @param message 可安全显示的中文用法说明.
46
+ */
47
+ constructor(message: string) {
48
+ super(message);
49
+ this.name = "WechatManagerCommandParseError";
50
+ }
51
+ }
52
+
53
+ /**
54
+ * 解析 Hub 本机命令, 不接受 shell 命令或未声明的参数.
55
+ *
56
+ * @param args /wx 命令前缀后的原始字符串.
57
+ * @returns 已验证的本机控制动作.
58
+ * @throws {WechatManagerCommandParseError} 出现未知动作或额外参数时抛出.
59
+ */
60
+ export function parseWechatManagerCommand(args: string): WechatManagerCommand {
61
+ const trimmed = args.trim();
62
+ if (!trimmed) {
63
+ return { action: "help" };
64
+ }
65
+ const projectsMatch = trimmed.match(/^projects(?:\s+([\s\S]*))?$/i);
66
+ if (projectsMatch) {
67
+ try {
68
+ return {
69
+ action: "projects",
70
+ command: parseProjectCommand(projectsMatch[1] ?? ""),
71
+ };
72
+ } catch (error) {
73
+ if (error instanceof ProjectCommandParseError) {
74
+ throw new WechatManagerCommandParseError(error.message);
75
+ }
76
+ throw error;
77
+ }
78
+ }
79
+
80
+ let tokens: string[];
81
+ try {
82
+ tokens = tokenizeCommandArguments(trimmed);
83
+ } catch (error) {
84
+ if (error instanceof CommandTokenizeError) {
85
+ throw new WechatManagerCommandParseError(`${error.message}\n${COMMAND_USAGE}`);
86
+ }
87
+ throw error;
88
+ }
89
+ if (tokens.length === 1) {
90
+ switch (tokens[0]) {
91
+ case "login":
92
+ case "start":
93
+ case "stop":
94
+ case "restart":
95
+ case "status":
96
+ case "help":
97
+ return { action: tokens[0] };
98
+ case "roots":
99
+ return { action: "roots", operation: "list" };
100
+ default:
101
+ break;
102
+ }
103
+ }
104
+ if (tokens[0] === "roots") {
105
+ if (tokens.length === 2 && tokens[1] === "list") {
106
+ return { action: "roots", operation: "list" };
107
+ }
108
+ if (tokens.length === 2 && tokens[1] === "add-current") {
109
+ return { action: "roots", operation: "add-current" };
110
+ }
111
+ if (tokens.length === 3 && tokens[1] === "add" && tokens[2].trim()) {
112
+ return { action: "roots", operation: "add", path: tokens[2] };
113
+ }
114
+ }
115
+ if (tokens.length === 2 && tokens[0] === "autostart") {
116
+ if (tokens[1] === "on") {
117
+ return { action: "autostart", enabled: true };
118
+ }
119
+ if (tokens[1] === "off") {
120
+ return { action: "autostart", enabled: false };
121
+ }
122
+ }
123
+ throw new WechatManagerCommandParseError(COMMAND_USAGE);
124
+ }
125
+
126
+ /**
127
+ * 提供 /wx 命令参数补全项.
128
+ *
129
+ * @param prefix 当前光标前的命令参数前缀.
130
+ * @returns 匹配项, 无匹配时返回 null.
131
+ */
132
+ export function getWechatManagerCommandCompletions(
133
+ prefix: string,
134
+ ): WechatManagerCommandCompletion[] | null {
135
+ const normalizedPrefix = prefix.trimStart().toLowerCase();
136
+ const matches = COMMAND_COMPLETIONS.filter((completion) =>
137
+ completion.value.toLowerCase().startsWith(normalizedPrefix),
138
+ );
139
+ return matches.length > 0 ? matches.map((completion) => ({ ...completion })) : null;
140
+ }
141
+
142
+ const COMMAND_USAGE =
143
+ "用法: /wx [login|start|stop|restart|status|projects|roots|autostart on|autostart off|help]";