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.
- package/LICENSE +661 -0
- package/README.md +365 -0
- package/docs/decisions/0001-ilink-context-token-queue.md +41 -0
- package/docs/handoff-next-session.md +134 -0
- package/docs/implementation-spec.md +147 -0
- package/extensions/wechat-session-hub.ts +589 -0
- package/package.json +67 -0
- package/scripts/pi-rpc-smoke.mjs +150 -0
- package/scripts/probe-wt-capability.mjs +27 -0
- package/scripts/start-ui-worker.ps1 +37 -0
- package/src/commands/ilink-qr-login-component.ts +148 -0
- package/src/commands/project-command-parser.ts +108 -0
- package/src/commands/tokenizer.ts +71 -0
- package/src/commands/wechat-manager-command-parser.ts +143 -0
- package/src/config/defaults.ts +30 -0
- package/src/config/paths.ts +56 -0
- package/src/config/store.ts +311 -0
- package/src/config/types.ts +33 -0
- package/src/config/validation.ts +221 -0
- package/src/gateway/channel-types.ts +47 -0
- package/src/gateway/command-parser.ts +291 -0
- package/src/gateway/command-router.ts +1449 -0
- package/src/gateway/credential-store.ts +611 -0
- package/src/gateway/durable-message-queue.ts +1043 -0
- package/src/gateway/gateway-control-ipc.ts +687 -0
- package/src/gateway/gateway-runtime.ts +726 -0
- package/src/gateway/ui-worker-extension-bridge.ts +1070 -0
- package/src/gateway/ui-worker-ipc.ts +1483 -0
- package/src/gateway/ui-worker-types.ts +50 -0
- package/src/gateway/wechat-ilink/api-client.ts +390 -0
- package/src/gateway/wechat-ilink/channel-adapter.ts +320 -0
- package/src/gateway/wechat-ilink/cursor-store.ts +134 -0
- package/src/gateway/wechat-ilink/qr-login.ts +612 -0
- package/src/gateway/wechat-ilink/typing-indicator.ts +133 -0
- package/src/gateway/windows-terminal-launcher.ts +247 -0
- package/src/projects/project-service.ts +483 -0
- package/src/registry/gateway-lease.ts +348 -0
- package/src/registry/manager-registry.ts +466 -0
- package/src/registry/types.ts +61 -0
- package/src/runtime/background-pi-worker.ts +309 -0
- package/src/runtime/background-worker-manager.ts +594 -0
- package/src/runtime/gateway-daemon.ts +281 -0
- package/src/runtime/gateway-lifecycle-operation.ts +308 -0
- package/src/runtime/gateway-service-controller.ts +339 -0
- package/src/runtime/gateway-worker-manager.ts +181 -0
- package/src/runtime/pi-cli.ts +56 -0
- package/src/runtime/pi-rpc-client.ts +427 -0
- package/src/runtime/ui-worker-manager.ts +1186 -0
- package/src/runtime/windows-logon-task-manager.ts +212 -0
- package/src/system/process-liveness.ts +88 -0
- package/tsconfig.json +19 -0
|
@@ -0,0 +1,589 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { parse as parsePath, resolve } from "node:path";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import {
|
|
6
|
+
ConfigurationBusyError,
|
|
7
|
+
createDefaultConfigurationStore,
|
|
8
|
+
type ConfigurationStore,
|
|
9
|
+
} from "../src/config/store.ts";
|
|
10
|
+
import { ConfigurationValidationError } from "../src/config/validation.ts";
|
|
11
|
+
import { IlinkQrLoginComponent } from "../src/commands/ilink-qr-login-component.ts";
|
|
12
|
+
import {
|
|
13
|
+
getWechatManagerCommandCompletions,
|
|
14
|
+
parseWechatManagerCommand,
|
|
15
|
+
WechatManagerCommandParseError,
|
|
16
|
+
} from "../src/commands/wechat-manager-command-parser.ts";
|
|
17
|
+
import { getManagerDataDirectory } from "../src/config/paths.ts";
|
|
18
|
+
import { GatewayControlError } from "../src/gateway/gateway-control-ipc.ts";
|
|
19
|
+
import { probeWindowsTerminalCapability } from "../src/gateway/windows-terminal-launcher.ts";
|
|
20
|
+
import { GatewayServiceController, type GatewayDaemonLaunchSpec, type GatewayServiceStatus } from "../src/runtime/gateway-service-controller.ts";
|
|
21
|
+
import { WindowsLogonTaskManager, WindowsLogonTaskManagerError } from "../src/runtime/windows-logon-task-manager.ts";
|
|
22
|
+
import { registerUiWorkerBridgeHooks, attachCurrentUiWorkerSession, getCurrentUiWorkerBridgeDiagnostics } from "../src/gateway/ui-worker-extension-bridge.ts";
|
|
23
|
+
import { UiWorkerIpcError } from "../src/gateway/ui-worker-ipc.ts";
|
|
24
|
+
import { IlinkApiError } from "../src/gateway/wechat-ilink/api-client.ts";
|
|
25
|
+
import { IlinkCredentialStoreError } from "../src/gateway/credential-store.ts";
|
|
26
|
+
import { IlinkQrLoginError, IlinkQrLoginService } from "../src/gateway/wechat-ilink/qr-login.ts";
|
|
27
|
+
import { BackgroundWorkerManagerError } from "../src/runtime/background-worker-manager.ts";
|
|
28
|
+
import { UiWorkerManagerError } from "../src/runtime/ui-worker-manager.ts";
|
|
29
|
+
import { PiCliUnavailableError, resolveCurrentPiCli } from "../src/runtime/pi-cli.ts";
|
|
30
|
+
import { ProjectService, ProjectServiceError } from "../src/projects/project-service.ts";
|
|
31
|
+
|
|
32
|
+
const HELP_TEXT = [
|
|
33
|
+
"Pi 微信会话枢纽命令:",
|
|
34
|
+
"/wx [login|start|stop|restart|status|projects|roots|autostart on|autostart off|help] - 管理 Hub",
|
|
35
|
+
"/wx projects [add <alias> --name <名称> --path <绝对路径>|remove <alias>|default <alias>] - 管理项目",
|
|
36
|
+
"/wx roots [list|add-current|add <绝对路径>] - 管理本机授权根目录",
|
|
37
|
+
" login - 使用独立二维码授权 Pi Hub",
|
|
38
|
+
" start - 启动后台连接; 首次启动时授权当前 session 目录",
|
|
39
|
+
" status - 查看连接、项目和授权根目录状态",
|
|
40
|
+
" roots add-current - 授权当前目录及其子目录并接入当前会话",
|
|
41
|
+
" help - 查看命令说明",
|
|
42
|
+
" 可见 UI 模式需要 Windows Terminal; 当前系统不支持或找不到 wt.exe 时会阻塞并在提示中说明原因.",
|
|
43
|
+
"/wechat-manager - /wx 的兼容别名",
|
|
44
|
+
].join("\n");
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 创建本机后台 Gateway 控制器及其固定 launch 参数。
|
|
48
|
+
*
|
|
49
|
+
* @returns 可启动、查询和控制 Hub daemon 的实例。
|
|
50
|
+
*/
|
|
51
|
+
function createGatewayServiceController(): GatewayServiceController {
|
|
52
|
+
const launchSpec = createGatewayServiceControllerSpec();
|
|
53
|
+
return new GatewayServiceController(launchSpec.managerDirectory, launchSpec);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* 创建当前用户的 daemon launch spec。
|
|
58
|
+
*
|
|
59
|
+
* @returns 通过 Pi 当前 Node 与当前安装扩展启动的固定参数。
|
|
60
|
+
*/
|
|
61
|
+
function createGatewayServiceControllerSpec(): GatewayDaemonLaunchSpec {
|
|
62
|
+
const managerDirectory = getManagerDataDirectory();
|
|
63
|
+
return {
|
|
64
|
+
managerDirectory,
|
|
65
|
+
extensionPath: fileURLToPath(import.meta.url),
|
|
66
|
+
daemonEntry: fileURLToPath(new URL("../src/runtime/gateway-daemon.ts", import.meta.url)),
|
|
67
|
+
piInvocation: resolveCurrentPiCli(),
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* 更新 Windows 登录自动启动任务与用户配置, 失败时尽量回滚外部任务。
|
|
73
|
+
*
|
|
74
|
+
* @param store Hub 全局配置存储。
|
|
75
|
+
* @param launchSpec 独立 daemon 启动参数。
|
|
76
|
+
* @param enabled 是否在当前 Windows 用户登录后自动连接。
|
|
77
|
+
* @returns 配置和 Task Scheduler 状态一致时正常结束。
|
|
78
|
+
*/
|
|
79
|
+
async function updateWindowsLogonAutoStart(
|
|
80
|
+
store: ConfigurationStore,
|
|
81
|
+
launchSpec: GatewayDaemonLaunchSpec,
|
|
82
|
+
enabled: boolean,
|
|
83
|
+
): Promise<void> {
|
|
84
|
+
const current = (await store.load()).config.autoStartOnWindowsLogon;
|
|
85
|
+
const taskManager = new WindowsLogonTaskManager(launchSpec);
|
|
86
|
+
try {
|
|
87
|
+
if (enabled) {
|
|
88
|
+
await taskManager.enable();
|
|
89
|
+
} else {
|
|
90
|
+
await taskManager.disable();
|
|
91
|
+
}
|
|
92
|
+
await store.update((config) => ({ ...config, autoStartOnWindowsLogon: enabled }));
|
|
93
|
+
} catch (error) {
|
|
94
|
+
try {
|
|
95
|
+
if (current) {
|
|
96
|
+
await taskManager.enable();
|
|
97
|
+
} else {
|
|
98
|
+
await taskManager.disable();
|
|
99
|
+
}
|
|
100
|
+
} catch {
|
|
101
|
+
throw new WindowsLogonTaskManagerError(
|
|
102
|
+
"自动启动配置更新失败, 且无法恢复之前的 Windows 登录任务状态。",
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* 格式化可在任何 Pi 会话查看的共享 Gateway 状态。
|
|
111
|
+
*
|
|
112
|
+
* @param status 后台 Hub 返回的状态快照。
|
|
113
|
+
* @param autoStart Windows 登录自动启动配置。
|
|
114
|
+
* @returns 面向用户的状态文本。
|
|
115
|
+
*/
|
|
116
|
+
function formatGatewayServiceStatus(
|
|
117
|
+
status: GatewayServiceStatus,
|
|
118
|
+
autoStart: boolean,
|
|
119
|
+
uiModeText: string,
|
|
120
|
+
): string {
|
|
121
|
+
const stateText: Record<GatewayServiceStatus["state"], string> = {
|
|
122
|
+
offline: "已停止",
|
|
123
|
+
starting: "启动中",
|
|
124
|
+
online: "已连接",
|
|
125
|
+
auth_required: "需要重新授权",
|
|
126
|
+
stopping: "停止中",
|
|
127
|
+
};
|
|
128
|
+
return [
|
|
129
|
+
`微信连接: ${stateText[status.state]}`,
|
|
130
|
+
`后台进程 PID: ${status.pid ?? "无"}`,
|
|
131
|
+
`前台会话: ${status.foregroundSessionCount ?? 0}`,
|
|
132
|
+
`后台会话: ${status.backgroundSessionCount ?? 0}`,
|
|
133
|
+
`微信 route: ${status.routeCount ?? 0}`,
|
|
134
|
+
`Windows 登录自动启动: ${autoStart ? "开启" : "关闭"}`,
|
|
135
|
+
`可见 UI 模式: ${uiModeText}`,
|
|
136
|
+
...(status.error ? [`状态说明: ${status.error}`] : []),
|
|
137
|
+
].join("\n");
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* 描述当前环境能否创建或恢复可见 UI 会话.
|
|
142
|
+
*
|
|
143
|
+
* @returns 面向用户的中文能力说明.
|
|
144
|
+
*/
|
|
145
|
+
async function describeUiModeCapability(): Promise<string> {
|
|
146
|
+
const capability = await probeWindowsTerminalCapability();
|
|
147
|
+
return capability.supported ? "可用" : `不可用 (${capability.reason})`;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 格式化当前 Pi TUI 自身的 Hub bridge 连接状态.
|
|
152
|
+
*
|
|
153
|
+
* Gateway 进程在线不代表当前 TUI 已接入; 该行用于区分全局服务状态与本终端连接状态.
|
|
154
|
+
*
|
|
155
|
+
* @returns 面向用户的中文状态说明.
|
|
156
|
+
*/
|
|
157
|
+
function formatCurrentTuiBridgeStatus(): string {
|
|
158
|
+
const diagnostics = getCurrentUiWorkerBridgeDiagnostics();
|
|
159
|
+
if (!diagnostics) {
|
|
160
|
+
return "当前终端接入: 未建立 (本会话未接入 Hub)";
|
|
161
|
+
}
|
|
162
|
+
const stateText: Record<typeof diagnostics.state, string> = {
|
|
163
|
+
connected: "🟢 已接入",
|
|
164
|
+
connecting: "🟡 连接中",
|
|
165
|
+
disconnected: "⚪ 未接入",
|
|
166
|
+
};
|
|
167
|
+
const lines = [
|
|
168
|
+
`当前终端接入: ${stateText[diagnostics.state]}`,
|
|
169
|
+
`终端实例: ${diagnostics.instanceId.slice(0, 8)}`,
|
|
170
|
+
];
|
|
171
|
+
if (diagnostics.lastConnectedAt) {
|
|
172
|
+
lines.push(`上次接入: ${formatLocalMinute(diagnostics.lastConnectedAt)}`);
|
|
173
|
+
}
|
|
174
|
+
if (diagnostics.reconnectAttempts > 0) {
|
|
175
|
+
lines.push(`重连失败次数: ${diagnostics.reconnectAttempts}`);
|
|
176
|
+
}
|
|
177
|
+
if (diagnostics.state !== "connected" && diagnostics.lastDisconnectReason) {
|
|
178
|
+
lines.push(`断开原因: ${diagnostics.lastDisconnectReason}`);
|
|
179
|
+
}
|
|
180
|
+
return lines.join("\n");
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 将 ISO 时间转换为本地时区的分钟精度文本.
|
|
185
|
+
*
|
|
186
|
+
* @param isoTimestamp ISO 时间字符串.
|
|
187
|
+
* @returns 本地时间文本, 无法解析时返回原始文本.
|
|
188
|
+
*/
|
|
189
|
+
function formatLocalMinute(isoTimestamp: string): string {
|
|
190
|
+
const parsed = new Date(isoTimestamp);
|
|
191
|
+
if (Number.isNaN(parsed.getTime())) {
|
|
192
|
+
return isoTimestamp;
|
|
193
|
+
}
|
|
194
|
+
const pad = (value: number): string => String(value).padStart(2, "0");
|
|
195
|
+
return `${pad(parsed.getMonth() + 1)}-${pad(parsed.getDate())} ${pad(parsed.getHours())}:${pad(parsed.getMinutes())}`;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* 格式化 start、stop、restart 完成后的最终提示.
|
|
200
|
+
*
|
|
201
|
+
* @param action 当前 Gateway 生命周期操作.
|
|
202
|
+
* @param status 后台 Gateway 返回的最终状态.
|
|
203
|
+
* @returns 用户可直接理解的提示文字和通知级别.
|
|
204
|
+
*/
|
|
205
|
+
function formatGatewayLifecycleResult(
|
|
206
|
+
action: "start" | "stop" | "restart",
|
|
207
|
+
status: GatewayServiceStatus,
|
|
208
|
+
): { message: string; level: "info" | "warning" | "error" } {
|
|
209
|
+
if (status.state === "online") {
|
|
210
|
+
if (action === "stop") {
|
|
211
|
+
return { message: "后台微信连接仍在线, 未确认停止。", level: "warning" };
|
|
212
|
+
}
|
|
213
|
+
const message = action === "restart"
|
|
214
|
+
? "后台微信连接已恢复并就绪。"
|
|
215
|
+
: "后台微信连接已启动并就绪。";
|
|
216
|
+
return { message, level: "info" };
|
|
217
|
+
}
|
|
218
|
+
if (status.state === "auth_required") {
|
|
219
|
+
return {
|
|
220
|
+
message: "后台服务已启动, 但微信授权需要重新登录; 请执行 /wx login。",
|
|
221
|
+
level: "warning",
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
if (status.state === "offline") {
|
|
225
|
+
return action === "stop"
|
|
226
|
+
? { message: "后台微信连接已停止。", level: "info" }
|
|
227
|
+
: { message: "后台微信连接未启动; 请执行 /wx status 检查状态。", level: "error" };
|
|
228
|
+
}
|
|
229
|
+
const stateText = status.state === "starting" ? "仍在启动" : "仍在停止";
|
|
230
|
+
return {
|
|
231
|
+
message: `后台微信连接${stateText}; 请执行 /wx status 查看当前状态。`,
|
|
232
|
+
level: "warning",
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* 比较路径, 在 Windows 上忽略大小写.
|
|
238
|
+
*
|
|
239
|
+
* @param left 左侧路径.
|
|
240
|
+
* @param right 右侧路径.
|
|
241
|
+
* @returns 两条路径相同时返回 true.
|
|
242
|
+
*/
|
|
243
|
+
function samePath(left: string, right: string): boolean {
|
|
244
|
+
const normalizedLeft = resolve(left);
|
|
245
|
+
const normalizedRight = resolve(right);
|
|
246
|
+
return process.platform === "win32"
|
|
247
|
+
? normalizedLeft.toLowerCase() === normalizedRight.toLowerCase()
|
|
248
|
+
: normalizedLeft === normalizedRight;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* 判断授权目录是否为盘符根目录或当前用户主目录.
|
|
253
|
+
*
|
|
254
|
+
* @param directory 待授权目录.
|
|
255
|
+
* @returns 目录范围过宽时返回 true.
|
|
256
|
+
*/
|
|
257
|
+
function isBroadAuthorizationRoot(directory: string): boolean {
|
|
258
|
+
const normalized = resolve(directory);
|
|
259
|
+
return samePath(normalized, parsePath(normalized).root) || samePath(normalized, homedir());
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/**
|
|
263
|
+
* 注册 Pi 微信会话枢纽的本地管理命令。
|
|
264
|
+
*
|
|
265
|
+
* @param pi Pi 扩展 API。
|
|
266
|
+
* @returns 无返回值。
|
|
267
|
+
*/
|
|
268
|
+
export default function registerWechatSessionHub(pi: ExtensionAPI): void {
|
|
269
|
+
const store = createDefaultConfigurationStore();
|
|
270
|
+
const projectService = new ProjectService(store);
|
|
271
|
+
registerUiWorkerBridgeHooks(pi, projectService, getManagerDataDirectory());
|
|
272
|
+
const handleWechatManagerCommand = async (
|
|
273
|
+
args: string,
|
|
274
|
+
ctx: ExtensionCommandContext,
|
|
275
|
+
): Promise<void> => {
|
|
276
|
+
try {
|
|
277
|
+
let commandArguments = args;
|
|
278
|
+
if (!commandArguments.trim()) {
|
|
279
|
+
if (!ctx.hasUI) {
|
|
280
|
+
ctx.ui.notify(HELP_TEXT, "info");
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
const selected = await ctx.ui.select("Pi 微信会话枢纽", [
|
|
284
|
+
"login | 微信扫码授权",
|
|
285
|
+
"start | 启动后台连接",
|
|
286
|
+
"status | 查看连接状态",
|
|
287
|
+
"projects | 查看已识别项目",
|
|
288
|
+
"roots | 查看授权根目录",
|
|
289
|
+
"stop | 确认后停止连接",
|
|
290
|
+
"restart | 重启后台连接",
|
|
291
|
+
"autostart on | 登录 Windows 后自动连接",
|
|
292
|
+
"autostart off | 关闭登录后自动连接",
|
|
293
|
+
"help | 查看命令说明",
|
|
294
|
+
]);
|
|
295
|
+
if (!selected) {
|
|
296
|
+
return;
|
|
297
|
+
}
|
|
298
|
+
commandArguments = selected.split(" | ", 1)[0];
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const command = parseWechatManagerCommand(commandArguments);
|
|
302
|
+
if (command.action === "help") {
|
|
303
|
+
ctx.ui.notify(HELP_TEXT, "info");
|
|
304
|
+
return;
|
|
305
|
+
}
|
|
306
|
+
if (command.action === "projects") {
|
|
307
|
+
const projectCommand = command.command;
|
|
308
|
+
if (projectCommand.action === "list") {
|
|
309
|
+
const { config, projects } = await projectService.list();
|
|
310
|
+
const lines = projects.length === 0
|
|
311
|
+
? ["当前暂无项目记录. 在授权目录中打开 Pi session 后会自动识别项目."]
|
|
312
|
+
: [
|
|
313
|
+
"已识别项目:",
|
|
314
|
+
...projects.map(([alias, project]) => {
|
|
315
|
+
const defaultMark = config.defaultProject === alias ? " (默认)" : "";
|
|
316
|
+
return `${alias}${defaultMark}: ${project.displayName} - ${project.path}`;
|
|
317
|
+
}),
|
|
318
|
+
];
|
|
319
|
+
ctx.ui.notify(lines.join("\n"), "info");
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
if (projectCommand.action === "add") {
|
|
323
|
+
const project = await projectService.add(
|
|
324
|
+
projectCommand.alias,
|
|
325
|
+
projectCommand.displayName,
|
|
326
|
+
projectCommand.path,
|
|
327
|
+
);
|
|
328
|
+
ctx.ui.notify(`项目已登记: ${projectCommand.alias} - ${project.displayName}`, "info");
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (projectCommand.action === "remove") {
|
|
332
|
+
await projectService.remove(projectCommand.alias);
|
|
333
|
+
ctx.ui.notify(`已移除项目登记: ${projectCommand.alias}; 项目目录未删除.`, "info");
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
await projectService.setDefault(projectCommand.alias);
|
|
337
|
+
ctx.ui.notify(`默认项目已设置为: ${projectCommand.alias}`, "info");
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
if (command.action === "roots") {
|
|
341
|
+
if (ctx.mode !== "tui") {
|
|
342
|
+
ctx.ui.notify("授权根目录只能在本机 Pi TUI 中管理.", "error");
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
if (command.operation === "list") {
|
|
346
|
+
const { config } = await projectService.list();
|
|
347
|
+
ctx.ui.notify(
|
|
348
|
+
config.allowedProjectRoots.length === 0
|
|
349
|
+
? "尚未设置授权根目录. 首次执行 /wx start 会授权当前目录."
|
|
350
|
+
: ["Hub 授权根目录:", ...config.allowedProjectRoots].join("\n"),
|
|
351
|
+
"info",
|
|
352
|
+
);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
const currentCwd = ctx.sessionManager.getCwd();
|
|
356
|
+
const requestedRoot = command.operation === "add-current" ? currentCwd : command.path!;
|
|
357
|
+
if (isBroadAuthorizationRoot(requestedRoot)) {
|
|
358
|
+
const confirmed = await ctx.ui.confirm(
|
|
359
|
+
"确认较宽的 Hub 授权范围",
|
|
360
|
+
`授权根目录 ${requestedRoot} 会允许其下所有 Pi session 接入 Hub. 是否继续?`,
|
|
361
|
+
);
|
|
362
|
+
if (!confirmed) {
|
|
363
|
+
ctx.ui.notify("已取消授权根目录添加.", "info");
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const canonicalRoot = await projectService.addAllowedRoot(requestedRoot);
|
|
368
|
+
let currentSessionAttached = false;
|
|
369
|
+
try {
|
|
370
|
+
await projectService.ensureProjectForCwd(currentCwd);
|
|
371
|
+
await attachCurrentUiWorkerSession(pi, ctx);
|
|
372
|
+
currentSessionAttached = true;
|
|
373
|
+
} catch (error) {
|
|
374
|
+
if (!(error instanceof ProjectServiceError && error.code === "project_path_denied")) {
|
|
375
|
+
throw error;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
ctx.ui.notify(
|
|
379
|
+
currentSessionAttached
|
|
380
|
+
? `授权根已添加: ${canonicalRoot}\n当前 Pi session 已接入 Hub.`
|
|
381
|
+
: `授权根已添加: ${canonicalRoot}\n当前 session 不在该授权范围内; 它会在授权范围内启动后自动接入.`,
|
|
382
|
+
"info",
|
|
383
|
+
);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
if (command.action === "login") {
|
|
387
|
+
if (ctx.mode !== "tui") {
|
|
388
|
+
ctx.ui.notify("iLink QR 登录需要可见 Pi TUI; 请在本地交互终端执行 /wx login。", "error");
|
|
389
|
+
return;
|
|
390
|
+
}
|
|
391
|
+
const proceed = await ctx.ui.confirm(
|
|
392
|
+
"授权 Pi Hub 使用微信",
|
|
393
|
+
"请确认该微信/iLink 账号没有被其他客户端同时轮询. 继续后 Pi Hub 会申请独立授权, 只写入自己的 credentials.json, 不读取或修改其他客户端数据.",
|
|
394
|
+
);
|
|
395
|
+
if (!proceed) {
|
|
396
|
+
ctx.ui.notify("未发起微信授权。", "info");
|
|
397
|
+
return;
|
|
398
|
+
}
|
|
399
|
+
const abortController = new AbortController();
|
|
400
|
+
const loginService = new IlinkQrLoginService({
|
|
401
|
+
managerDirectory: getManagerDataDirectory(),
|
|
402
|
+
configStore: store,
|
|
403
|
+
});
|
|
404
|
+
const result = await ctx.ui.custom<
|
|
405
|
+
{ type: "success"; authorizedUserId: string } | { type: "error"; message: string }
|
|
406
|
+
>((tui, _theme, _keybindings, done) => {
|
|
407
|
+
const component = new IlinkQrLoginComponent(() => abortController.abort());
|
|
408
|
+
void loginService.login({
|
|
409
|
+
signal: abortController.signal,
|
|
410
|
+
onQrCode: (_content, terminalQr) => {
|
|
411
|
+
component.setQr(terminalQr);
|
|
412
|
+
tui.requestRender();
|
|
413
|
+
},
|
|
414
|
+
onStatus: (status) => {
|
|
415
|
+
component.setStatus(status);
|
|
416
|
+
tui.requestRender();
|
|
417
|
+
},
|
|
418
|
+
requestVerificationCode: async () =>
|
|
419
|
+
ctx.ui.input("微信配对码", "输入微信页面显示的数字"),
|
|
420
|
+
}).then((login) => {
|
|
421
|
+
done({ type: "success", authorizedUserId: login.authorizedUserId });
|
|
422
|
+
}).catch((error: unknown) => {
|
|
423
|
+
done({ type: "error", message: toUserMessage(error) });
|
|
424
|
+
});
|
|
425
|
+
return {
|
|
426
|
+
render: (width) => component.render(width),
|
|
427
|
+
handleInput: (data) => component.handleInput(data),
|
|
428
|
+
invalidate: () => component.invalidate(),
|
|
429
|
+
};
|
|
430
|
+
});
|
|
431
|
+
if (result?.type === "success") {
|
|
432
|
+
ctx.ui.notify(
|
|
433
|
+
"微信授权已写入 Pi Hub 专属凭证. 请执行 /wx start 启动后台连接。",
|
|
434
|
+
"info",
|
|
435
|
+
);
|
|
436
|
+
} else {
|
|
437
|
+
ctx.ui.notify(result?.message ?? "扫码授权已取消, 未启动微信轮询。", "warning");
|
|
438
|
+
}
|
|
439
|
+
return;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const serviceController = createGatewayServiceController();
|
|
443
|
+
if (command.action === "status") {
|
|
444
|
+
const snapshot = await store.load();
|
|
445
|
+
const status = await serviceController.status();
|
|
446
|
+
const uiModeText = await describeUiModeCapability();
|
|
447
|
+
ctx.ui.notify(
|
|
448
|
+
[
|
|
449
|
+
formatGatewayServiceStatus(status, snapshot.config.autoStartOnWindowsLogon, uiModeText),
|
|
450
|
+
formatCurrentTuiBridgeStatus(),
|
|
451
|
+
`配置: ${snapshot.exists ? "已加载" : "尚未创建"}`,
|
|
452
|
+
`授权根目录: ${snapshot.config.allowedProjectRoots.length}`,
|
|
453
|
+
`项目: ${Object.keys(snapshot.config.projects).length}`,
|
|
454
|
+
`默认项目: ${snapshot.config.defaultProject ?? "未设置"}`,
|
|
455
|
+
].join("\n"),
|
|
456
|
+
"info",
|
|
457
|
+
);
|
|
458
|
+
return;
|
|
459
|
+
}
|
|
460
|
+
if (command.action === "start") {
|
|
461
|
+
let initializedProject: { rootAdded: boolean; alias: string; project: { displayName: string; path: string } } | undefined;
|
|
462
|
+
let initializationNotice: string | undefined;
|
|
463
|
+
if (ctx.mode === "tui") {
|
|
464
|
+
const currentCwd = ctx.sessionManager.getCwd();
|
|
465
|
+
const { config } = await store.load();
|
|
466
|
+
if (config.allowedProjectRoots.length === 0 && isBroadAuthorizationRoot(currentCwd)) {
|
|
467
|
+
const confirmed = await ctx.ui.confirm(
|
|
468
|
+
"确认 Hub 首次授权范围",
|
|
469
|
+
`首次启动将授权当前目录 ${currentCwd} 及其所有子目录. 是否继续?`,
|
|
470
|
+
);
|
|
471
|
+
if (!confirmed) {
|
|
472
|
+
initializationNotice = "未授权当前目录; 后台连接仍可启动, 但当前 session 不会接入 Hub.";
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
if (!initializationNotice) {
|
|
476
|
+
if (config.allowedProjectRoots.length === 0) {
|
|
477
|
+
initializedProject = await projectService.initializeFromCurrentCwd(currentCwd);
|
|
478
|
+
} else {
|
|
479
|
+
try {
|
|
480
|
+
initializedProject = {
|
|
481
|
+
rootAdded: false,
|
|
482
|
+
...await projectService.ensureProjectForCwd(currentCwd),
|
|
483
|
+
};
|
|
484
|
+
} catch (error) {
|
|
485
|
+
if (!(error instanceof ProjectServiceError && error.code === "project_path_denied")) {
|
|
486
|
+
throw error;
|
|
487
|
+
}
|
|
488
|
+
initializationNotice = "当前目录不在 Hub 授权根内; 后台连接仍可启动, 可执行 /wx roots add-current 授权当前目录.";
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
ctx.ui.notify("正在启动后台微信连接, 请稍候...", "info");
|
|
494
|
+
const status = await serviceController.start();
|
|
495
|
+
if (initializedProject && ctx.mode === "tui") {
|
|
496
|
+
try {
|
|
497
|
+
await attachCurrentUiWorkerSession(pi, ctx);
|
|
498
|
+
} catch (error) {
|
|
499
|
+
initializationNotice = `后台连接已启动, 但当前 session 尚未接入 Hub: ${toUserMessage(error)}`;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
const lifecycleNotice = formatGatewayLifecycleResult("start", status);
|
|
503
|
+
const notices = [
|
|
504
|
+
lifecycleNotice.message,
|
|
505
|
+
...(initializedProject?.rootAdded
|
|
506
|
+
? [`首次启动已授权当前目录及其子目录: ${initializedProject.project.path}`]
|
|
507
|
+
: initializedProject
|
|
508
|
+
? [`当前项目已接入 Hub: ${initializedProject.project.displayName}`]
|
|
509
|
+
: []),
|
|
510
|
+
...(initializationNotice ? [initializationNotice] : []),
|
|
511
|
+
];
|
|
512
|
+
ctx.ui.notify(notices.join("\n"), lifecycleNotice.level);
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
if (command.action === "stop") {
|
|
516
|
+
const current = await serviceController.status();
|
|
517
|
+
if (current.state === "offline") {
|
|
518
|
+
ctx.ui.notify("后台微信连接当前已停止。", "info");
|
|
519
|
+
return;
|
|
520
|
+
}
|
|
521
|
+
if (ctx.mode !== "tui") {
|
|
522
|
+
ctx.ui.notify("停止后台连接需要可见 Pi TUI 确认; 已保持服务运行。", "error");
|
|
523
|
+
return;
|
|
524
|
+
}
|
|
525
|
+
const confirmed = await ctx.ui.confirm(
|
|
526
|
+
"停止 Pi 微信会话枢纽?",
|
|
527
|
+
"确认后会停止接收新微信消息, 并等待已入队任务和正在处理的 Pi turn 收尾后关闭.",
|
|
528
|
+
);
|
|
529
|
+
if (!confirmed) {
|
|
530
|
+
ctx.ui.notify("已取消停止, 后台微信连接保持运行。", "info");
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
ctx.ui.notify("正在停止后台微信连接, 等待当前任务收尾...", "info");
|
|
534
|
+
const status = await serviceController.stop();
|
|
535
|
+
const lifecycleNotice = formatGatewayLifecycleResult("stop", status);
|
|
536
|
+
ctx.ui.notify(lifecycleNotice.message, lifecycleNotice.level);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
if (command.action === "restart") {
|
|
540
|
+
ctx.ui.notify("正在重启后台微信连接, 等待新服务就绪...", "info");
|
|
541
|
+
const status = await serviceController.restart();
|
|
542
|
+
const lifecycleNotice = formatGatewayLifecycleResult("restart", status);
|
|
543
|
+
ctx.ui.notify(lifecycleNotice.message, lifecycleNotice.level);
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
546
|
+
if (command.action === "autostart") {
|
|
547
|
+
await updateWindowsLogonAutoStart(store, createGatewayServiceControllerSpec(), command.enabled);
|
|
548
|
+
ctx.ui.notify(`Windows 用户登录自动启动已${command.enabled ? "开启" : "关闭"}.`, "info");
|
|
549
|
+
}
|
|
550
|
+
} catch (error) {
|
|
551
|
+
ctx.ui.notify(toUserMessage(error), "error");
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
|
|
555
|
+
const commandOptions = {
|
|
556
|
+
description: "管理独立后台微信连接和 Pi 会话",
|
|
557
|
+
getArgumentCompletions: getWechatManagerCommandCompletions,
|
|
558
|
+
handler: handleWechatManagerCommand,
|
|
559
|
+
};
|
|
560
|
+
pi.registerCommand("wx", commandOptions);
|
|
561
|
+
pi.registerCommand("wechat-manager", {
|
|
562
|
+
...commandOptions,
|
|
563
|
+
description: "兼容别名: 请优先使用 /wx",
|
|
564
|
+
});
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function toUserMessage(error: unknown): string {
|
|
568
|
+
if (error instanceof GatewayControlError && error.code === "timeout") {
|
|
569
|
+
return "后台操作尚未确认完成; 请执行 /wx status 查看当前状态。";
|
|
570
|
+
}
|
|
571
|
+
if (
|
|
572
|
+
error instanceof ProjectServiceError ||
|
|
573
|
+
error instanceof ConfigurationBusyError ||
|
|
574
|
+
error instanceof ConfigurationValidationError ||
|
|
575
|
+
error instanceof WechatManagerCommandParseError ||
|
|
576
|
+
error instanceof GatewayControlError ||
|
|
577
|
+
error instanceof WindowsLogonTaskManagerError ||
|
|
578
|
+
error instanceof IlinkApiError ||
|
|
579
|
+
error instanceof IlinkCredentialStoreError ||
|
|
580
|
+
error instanceof IlinkQrLoginError ||
|
|
581
|
+
error instanceof BackgroundWorkerManagerError ||
|
|
582
|
+
error instanceof UiWorkerManagerError ||
|
|
583
|
+
error instanceof UiWorkerIpcError ||
|
|
584
|
+
error instanceof PiCliUnavailableError
|
|
585
|
+
) {
|
|
586
|
+
return error.message;
|
|
587
|
+
}
|
|
588
|
+
return "操作失败, 请检查项目配置和本地目录权限。详细信息不会记录到普通日志。";
|
|
589
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "pi-wechat-session-hub",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "通过微信管理本机多个 Pi 会话的 Pi 扩展。",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"pi-package",
|
|
7
|
+
"pi",
|
|
8
|
+
"wechat",
|
|
9
|
+
"weixin",
|
|
10
|
+
"ilink",
|
|
11
|
+
"session-manager",
|
|
12
|
+
"remote-control"
|
|
13
|
+
],
|
|
14
|
+
"license": "AGPL-3.0-or-later",
|
|
15
|
+
"author": "yangfeng20",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/yangfeng20/pi-wechat-session-hub.git"
|
|
19
|
+
},
|
|
20
|
+
"bugs": {
|
|
21
|
+
"url": "https://github.com/yangfeng20/pi-wechat-session-hub/issues"
|
|
22
|
+
},
|
|
23
|
+
"homepage": "https://github.com/yangfeng20/pi-wechat-session-hub#readme",
|
|
24
|
+
"type": "module",
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22.19.0"
|
|
27
|
+
},
|
|
28
|
+
"files": [
|
|
29
|
+
"extensions/",
|
|
30
|
+
"src/",
|
|
31
|
+
"scripts/",
|
|
32
|
+
"docs/",
|
|
33
|
+
"README.md",
|
|
34
|
+
"LICENSE",
|
|
35
|
+
"tsconfig.json"
|
|
36
|
+
],
|
|
37
|
+
"scripts": {
|
|
38
|
+
"typecheck": "tsc --noEmit",
|
|
39
|
+
"test": "node --experimental-transform-types --test tests/config-store.test.ts tests/project-service.test.ts tests/project-command-parser.test.ts tests/registry.test.ts tests/pi-rpc-client.test.ts tests/background-worker.test.ts tests/background-worker-resume.test.ts tests/pi-cli.test.ts tests/durable-message-queue.test.ts tests/gateway-command-parser.test.ts tests/gateway-command-router.test.ts tests/durable-message-queue-context.test.ts tests/wechat-ilink.test.ts tests/credential-store.test.ts tests/ilink-qr-login.test.ts tests/gateway-runtime.test.ts tests/wechat-manager-command-parser.test.ts tests/ui-worker-manager.test.ts tests/windows-terminal-launcher.test.ts tests/gateway-service-controller.test.ts tests/windows-logon-task-manager.test.ts tests/ui-session-owner-handoff.test.ts tests/ui-resume-owner-liveness.test.ts tests/wechat-session-hub-command.test.ts",
|
|
40
|
+
"test:pi-runtime": "node scripts/pi-rpc-smoke.mjs"
|
|
41
|
+
},
|
|
42
|
+
"peerDependencies": {
|
|
43
|
+
"@earendil-works/pi-coding-agent": "*"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@earendil-works/pi-coding-agent": "0.85.1",
|
|
47
|
+
"@types/node": "^22.0.0",
|
|
48
|
+
"@types/qrcode-terminal": "0.12.2",
|
|
49
|
+
"typescript": "^5.9.3"
|
|
50
|
+
},
|
|
51
|
+
"pi": {
|
|
52
|
+
"extensions": [
|
|
53
|
+
"./extensions/*.ts"
|
|
54
|
+
]
|
|
55
|
+
},
|
|
56
|
+
"piCompatibility": {
|
|
57
|
+
"testedVersions": [
|
|
58
|
+
"0.85.1",
|
|
59
|
+
"1.0.0",
|
|
60
|
+
"1.3.0"
|
|
61
|
+
],
|
|
62
|
+
"supportedRange": ">=0.85.1 <2.0.0"
|
|
63
|
+
},
|
|
64
|
+
"dependencies": {
|
|
65
|
+
"qrcode-terminal": "0.12.0"
|
|
66
|
+
}
|
|
67
|
+
}
|