agent-bridge-qwenwork 1.0.37 → 1.0.40
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/README.md +8 -2
- package/dist/src-ts/plugins/agent-task-abilities.js +125 -0
- package/dist/src-ts/plugins/agent-task-ability.js +26 -10
- package/dist/src-ts/plugins/desktop-launch.js +98 -29
- package/dist/src-ts/plugins/desktop-runtime.js +29 -0
- package/dist/src-ts/plugins/qwenwork/cdp-client.js +322 -71
- package/dist/src-ts/plugins/qwenwork/index.js +175 -16
- package/dist/src-ts/plugins/qwenwork/openai-adapter.js +17 -6
- package/dist/src-ts/plugins/qwenwork/session-history.js +4 -4
- package/package.json +1 -1
- package/plugin.json +1 -1
package/README.md
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
后台每 30 秒只读取已有 CDP 连接状态,不发送测试聊天、不探测页面、不启动或重启桌面。用户关闭千问后保持离线;收到 Peer AID 消息或其它真实请求时,才按需连接或启动桌面。ABWeb 中显式启动、重载和重启桌面仍可启动程序。AUN、飞书和 HTTP 共用请求队列,恢复不修改 AID 或 owner 配置。`autoStart: false` 禁止请求自动启动桌面。
|
|
10
10
|
|
|
11
|
-
|
|
11
|
+
原生 CDP 历史读取使用桌面端只读 tRPC 接口列出任务及其 sub-chat,并分页读取用户和助手正文;读取不会点击、切换或发送消息,也不会把配置中的 `chatId`/`subChatId` 当作当前身份。目录和正文受读取上限及客户端返回范围限制,完整性以 `complete` 和 `missingReasons` 为准;`sessionHistory` 的 scope 绑定本插件配置的 CDP 端口。中继、忙碌、恢复中、离线或未就绪时会返回对应拒绝原因。
|
|
12
12
|
|
|
13
13
|
请求超时或明确返回“API不可用”时只结束本次请求,已经发送的任务不自动重发,避免重复执行。健康接口 `/api/plugins/qwenwork/health` 返回连接状态、`restarts` 和 `recovering`;`lastHeartbeat` 为旧接口兼容字段,当前不会产生心跳。日志可搜索“千问 CDP 自动重连开始”和“千问 CDP 自动重连成功”。daemon 应在已登录的 Windows 用户桌面会话运行。
|
|
14
14
|
|
|
@@ -22,4 +22,10 @@
|
|
|
22
22
|
|
|
23
23
|
## 远端任务 Ability
|
|
24
24
|
|
|
25
|
-
|
|
25
|
+
当前源码声明 `agent/task/run`、`agent/task/recent`、`agent/task/read`、`agent/task/switch` 和 `agent/task/new`。原生 CDP 的 `run` 接受 `{"task":"需要执行的自然语言任务"}`,未选择任务时独立新建;`switch` 或 `new` 成功后,同一 Provider 与已认证 Peer 的后续 `run` 续聊并返回 `text`、`sessionId`,重载清除选择。切换前后核对真实活动 ID,目标不存在时不新建替代任务。
|
|
26
|
+
|
|
27
|
+
任务身份来自唯一可见编辑器的原生 `chatId`、`subChatId`,并经当前账号 scope 查询验证;URL 和“新任务”外观不能证明身份。切换到其他任务需要该任务已加载的唯一原生侧栏入口;入口缺失或不唯一时明确拒绝,不改写 URL 或猜测目标。
|
|
28
|
+
|
|
29
|
+
尚未分配原生 ID 的空白页返回 `qwenwork-pending:` 临时句柄,首轮 `run` 后更新为原生 ID;页面状态变化后失效,`read` 不接受临时句柄。relay 中继及仅有 direct 接口的 CLI 客户端明确不支持四项管理能力,`run` 保留原文字契约,不声称返回本地原生会话 ID。
|
|
30
|
+
|
|
31
|
+
需在 AUN 中验证 Provider 的 Owner、选择发布并逐次确认执行;升级不会自动公开。任务按目标 Agent 的权限执行,Ability 仅交付文字,附件会明确提示尚未交付。参数和契约见仓库[桌面 Agent Ability 使用说明](../../docs/desktop-agent-ability.md)。
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AgentTaskAbilities = void 0;
|
|
4
|
+
const agent_task_ability_1 = require("./agent-task-ability");
|
|
5
|
+
const idSchema = { type: "string", minLength: 1, maxLength: 512 };
|
|
6
|
+
const sessionSchema = { type: "object", required: ["id", "title"], properties: { id: idSchema, title: { type: "string" }, updatedAt: { type: "string" }, updatedLabel: { type: "string" }, active: { type: "boolean" } }, additionalProperties: false };
|
|
7
|
+
const pageProperties = { scope: { type: "string" }, complete: { type: "boolean" }, missingReasons: { type: "array", items: { type: "string" } }, readAt: { type: "string" }, nextCursor: { type: "string" } };
|
|
8
|
+
function params(value, fields) {
|
|
9
|
+
if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).some(key => !fields.includes(key)))
|
|
10
|
+
throw new Error("任务能力参数无效或含未知字段");
|
|
11
|
+
return value;
|
|
12
|
+
}
|
|
13
|
+
function string(value, name, max) {
|
|
14
|
+
if (typeof value !== "string" || !value.trim() || value.length > max || /[\u0000-\u001f]/.test(value))
|
|
15
|
+
throw new Error(`任务${name}参数无效`);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function limit(value, max) {
|
|
19
|
+
if (value === undefined)
|
|
20
|
+
return 20;
|
|
21
|
+
if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > max)
|
|
22
|
+
throw new Error(`任务分页参数必须为 1–${max}`);
|
|
23
|
+
return Number(value);
|
|
24
|
+
}
|
|
25
|
+
/** 只统一任务契约和远程选择;桌面身份、队列及会话恢复由插件验证。 */
|
|
26
|
+
class AgentTaskAbilities {
|
|
27
|
+
adapter;
|
|
28
|
+
selected = new Map();
|
|
29
|
+
generation = 0;
|
|
30
|
+
abilities;
|
|
31
|
+
constructor(adapter, outputs = []) {
|
|
32
|
+
this.adapter = adapter;
|
|
33
|
+
const task = (0, agent_task_ability_1.createTaskAbility)(async () => { throw new Error("任务入口未绑定"); });
|
|
34
|
+
this.abilities = [{
|
|
35
|
+
definition: { ...task.definition, contract_revision: "3", summary: "执行自然语言任务;本 Provider 与 Peer 经 switch/new 选择后续聊,否则独立新建。重载清除选择。空白页可能返回带 pending 前缀的临时逻辑句柄,首轮成功后返回原生 ID。返回文字及实际生成附件的 AUN FS 引用,上传失败则调用失败,逐次确认。", result_schema: { ...task.definition.result_schema, required: ["text", "sessionId"], properties: { ...task.definition.result_schema.properties, sessionId: idSchema } } },
|
|
36
|
+
handler: async (value, context) => {
|
|
37
|
+
const generation = this.generation;
|
|
38
|
+
let sessionId = "";
|
|
39
|
+
const run = (0, agent_task_ability_1.createTaskAbility)(request => this.execute(context, "run", async () => {
|
|
40
|
+
const key = context.callerAid ? this.key(context) : undefined;
|
|
41
|
+
const selectedId = key ? this.selected.get(key) : undefined;
|
|
42
|
+
const response = await this.adapter.run(request, selectedId, context);
|
|
43
|
+
context.signal.throwIfAborted();
|
|
44
|
+
this.checkGeneration(generation);
|
|
45
|
+
sessionId = string(response.sessionId, "标识", 512);
|
|
46
|
+
if (key && selectedId)
|
|
47
|
+
this.selected.set(key, sessionId);
|
|
48
|
+
return response;
|
|
49
|
+
}));
|
|
50
|
+
return { ...await run.handler(value, context), sessionId };
|
|
51
|
+
},
|
|
52
|
+
}, this.ability("recent", "最近任务", "只读目标插件原生任务目录,不切换或发送消息;scope、complete、missingReasons 说明目录范围。部分传输不支持。", { limit: { type: "integer", minimum: 1, maximum: 50 } }, [], { type: "object", required: ["sessions", "scope", "complete", "missingReasons", "readAt"], properties: { sessions: { type: "array", maxItems: 50, items: sessionSchema }, ...pageProperties }, additionalProperties: false }, ["state.read", "data.egress"], async (value, context) => {
|
|
53
|
+
const count = limit(params(value, ["limit"]).limit, 50);
|
|
54
|
+
return this.execute(context, "recent", async () => {
|
|
55
|
+
const page = await this.adapter.recent(count, context);
|
|
56
|
+
if (!page.supported)
|
|
57
|
+
throw new Error(page.reason);
|
|
58
|
+
if (page.sessions.length > count)
|
|
59
|
+
throw new Error("任务目录返回数量超过 limit,未截断或宣称完整");
|
|
60
|
+
const { supported: _supported, ...result } = page;
|
|
61
|
+
return { ...result, scope: this.adapter.scope("recent") };
|
|
62
|
+
});
|
|
63
|
+
}), this.ability("read", "读取任务正文", "只读指定任务可验证的用户和助理文字,不切换或发送;部分客户端要求先 switch。范围由 scope 和完整性字段说明。", { sessionId: idSchema, limit: { type: "integer", minimum: 1, maximum: 100 }, cursor: { type: "string", minLength: 1, maxLength: 4096 } }, ["sessionId"], { type: "object", required: ["session", "turns", "scope", "complete", "missingReasons", "readAt"], properties: { session: sessionSchema, turns: { type: "array", maxItems: 100, items: { type: "object", required: ["role", "text"], properties: { id: { type: "string" }, role: { type: "string", enum: ["user", "assistant"] }, text: { type: "string", maxLength: 60_000 }, time: { type: "string" } }, additionalProperties: false } }, ...pageProperties }, additionalProperties: false }, ["state.read", "data.egress"], async (value, context) => {
|
|
64
|
+
const input = params(value, ["sessionId", "limit", "cursor"]);
|
|
65
|
+
const query = { sessionId: string(input.sessionId, "标识", 512), limit: limit(input.limit, 100), ...(input.cursor === undefined ? {} : { cursor: string(input.cursor, "游标", 4096) }) };
|
|
66
|
+
return this.execute(context, "read", async () => {
|
|
67
|
+
const page = await this.adapter.read(query, context);
|
|
68
|
+
if (!page.supported)
|
|
69
|
+
throw new Error(page.reason);
|
|
70
|
+
if (page.session.id !== query.sessionId)
|
|
71
|
+
throw new Error("任务正文身份与请求不一致,未返回其他任务内容");
|
|
72
|
+
if (page.turns.length > query.limit || page.turns.reduce((total, turn) => total + turn.text.length, 0) > 60_000)
|
|
73
|
+
throw new Error("任务正文超过分页或 60,000 字符上限,请减小 limit;未截断");
|
|
74
|
+
const { supported: _supported, ...result } = page;
|
|
75
|
+
return { ...result, scope: this.adapter.scope("read") };
|
|
76
|
+
});
|
|
77
|
+
}), this.ability("switch", "切换任务", "只选择精确 ID 的已有任务,不发送消息;之后仅此 Provider 与认证 Peer 的 run 续聊。具体客户端不支持安全切换时明确报错。", { sessionId: idSchema }, ["sessionId"], this.selectionSchema(), ["state.read", "state.write", "system.interact"], (value, context) => this.select(value, context, false)),
|
|
78
|
+
this.ability("new", "新建任务", "新建并选择空白任务,不发送消息。未分配原生 ID 时返回带 pending 前缀的临时逻辑句柄,首轮 run 后返回原生 ID。仅本 Provider 与认证 Peer 使用,重载清除选择。", {}, [], this.selectionSchema(), ["state.read", "state.write", "system.interact"], (value, context) => this.select(value, context, true))];
|
|
79
|
+
this.abilities.push(...(0, agent_task_ability_1.createTaskAliases)(this.abilities[0], outputs));
|
|
80
|
+
}
|
|
81
|
+
reset() { this.generation++; this.selected.clear(); }
|
|
82
|
+
checkGeneration(generation) {
|
|
83
|
+
if (generation !== this.generation)
|
|
84
|
+
throw new Error("任务能力实例已重载,旧调用及选择已失效,请重新调用");
|
|
85
|
+
}
|
|
86
|
+
key(context) {
|
|
87
|
+
if (!context.callerAid)
|
|
88
|
+
throw new Error("缺少宿主认证的调用者身份,请升级 AUN 插件与后台后重新调用");
|
|
89
|
+
return JSON.stringify([context.providerAid, context.callerAid]);
|
|
90
|
+
}
|
|
91
|
+
async execute(context, action, work) {
|
|
92
|
+
const generation = this.generation;
|
|
93
|
+
context.signal.throwIfAborted();
|
|
94
|
+
return this.adapter.execute(context, action, async () => {
|
|
95
|
+
context.signal.throwIfAborted();
|
|
96
|
+
this.checkGeneration(generation);
|
|
97
|
+
const result = await work();
|
|
98
|
+
context.signal.throwIfAborted();
|
|
99
|
+
this.checkGeneration(generation);
|
|
100
|
+
return result;
|
|
101
|
+
});
|
|
102
|
+
}
|
|
103
|
+
async select(value, context, create) {
|
|
104
|
+
const generation = this.generation;
|
|
105
|
+
const input = params(value, create ? [] : ["sessionId"]);
|
|
106
|
+
const target = create ? undefined : string(input.sessionId, "标识", 512);
|
|
107
|
+
const key = this.key(context);
|
|
108
|
+
return this.execute(context, create ? "new" : "switch", async () => {
|
|
109
|
+
const selection = await this.adapter.select(target, context);
|
|
110
|
+
string(selection.sessionId, "标识", 512);
|
|
111
|
+
if (target && target !== selection.sessionId)
|
|
112
|
+
throw new Error("任务切换身份不一致,选择未保存");
|
|
113
|
+
context.signal.throwIfAborted();
|
|
114
|
+
this.checkGeneration(generation);
|
|
115
|
+
this.selected.set(key, selection.sessionId);
|
|
116
|
+
return selection;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
selectionSchema() { return { type: "object", required: ["sessionId", "title"], properties: { sessionId: idSchema, title: { type: "string" } }, additionalProperties: false }; }
|
|
120
|
+
ability(action, name, summary, properties, required, result_schema, effects, handler) {
|
|
121
|
+
const definition = { path: `agent/task/${action}`, name, summary, contract_revision: "1", params_schema: { type: "object", properties, required, additionalProperties: false }, result_schema, effects, auth_required: true, require_confirm: true, idempotency: "keyed", allowed_modes: ["explicit"], aggregation: "none", dedupe_retention_seconds: 3600 };
|
|
122
|
+
return { definition, handler };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
exports.AgentTaskAbilities = AgentTaskAbilities;
|
|
@@ -1,36 +1,52 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.createTaskAbility = createTaskAbility;
|
|
4
|
+
exports.createTaskAliases = createTaskAliases;
|
|
4
5
|
const node_crypto_1 = require("node:crypto");
|
|
5
6
|
const agent_1 = require("../agent");
|
|
7
|
+
const attachments_1 = require("../attachments");
|
|
6
8
|
function createTaskAbility(handle) {
|
|
7
9
|
return {
|
|
8
10
|
definition: {
|
|
9
11
|
path: "agent/task/run",
|
|
10
12
|
name: "执行大模型任务",
|
|
11
|
-
summary: "
|
|
12
|
-
contract_revision: "
|
|
13
|
+
summary: "在独立新会话中执行自然语言任务,返回文字和目标 Agent 实际生成的图片、视频、文档等附件的 AUN FS 引用;可能使用工具、读写文件及访问网络,须逐次确认。附件上传失败则调用失败。",
|
|
14
|
+
contract_revision: "2",
|
|
13
15
|
params_schema: { type: "object", required: ["task"], properties: { task: { type: "string", minLength: 1, maxLength: 20_000, pattern: "\\S" } }, additionalProperties: false },
|
|
14
|
-
result_schema: { type: "object", required: ["text"], properties: { text: { type: "string", minLength: 1, maxLength: 60_000 },
|
|
16
|
+
result_schema: { type: "object", required: ["text"], properties: { text: { type: "string", minLength: 1, maxLength: 60_000 }, attachments: { type: "array", minItems: 1, maxItems: 8, items: { type: "object", required: ["owner_aid", "object_key", "filename", "content_type", "size_bytes", "sha256"], properties: { owner_aid: { type: "string", minLength: 1 }, object_key: { type: "string", minLength: 1 }, filename: { type: "string", minLength: 1 }, content_type: { type: "string", minLength: 1 }, size_bytes: { type: "integer", minimum: 1 }, sha256: { type: "string", pattern: "^[a-f0-9]{64}$" } }, additionalProperties: false } } }, additionalProperties: false },
|
|
15
17
|
effects: ["state.read", "state.write", "data.egress", "data.local_write", "credential.access", "code.execute", "system.interact"],
|
|
16
18
|
auth_required: true, require_confirm: true, idempotency: "keyed",
|
|
17
19
|
allowed_modes: ["explicit"], aggregation: "none", dedupe_retention_seconds: 3600,
|
|
18
20
|
},
|
|
19
|
-
handler: async (params, { signal }) => {
|
|
21
|
+
handler: async (params, { signal, uploadAttachments }) => {
|
|
20
22
|
signal.throwIfAborted();
|
|
21
23
|
const task = params?.task;
|
|
22
24
|
if (!params || typeof params !== "object" || Array.isArray(params) || Object.keys(params).length !== 1 || typeof task !== "string" || !task.trim() || task.length > 20_000)
|
|
23
25
|
throw new Error("任务参数必须仅包含 1 至 20,000 字符的非空 task");
|
|
24
|
-
const response = await (0, agent_1.abortable)(handle({ task, sessionId: (0, node_crypto_1.randomUUID)(), newSession: true, signal, attachmentOutput:
|
|
25
|
-
const
|
|
26
|
+
const response = await (0, agent_1.abortable)(handle({ task, sessionId: (0, node_crypto_1.randomUUID)(), newSession: true, signal, attachmentOutput: true }), signal);
|
|
27
|
+
const items = response.attachments?.length ? response.attachments : (0, attachments_1.asAttachments)(response.images);
|
|
28
|
+
(0, attachments_1.validateAttachments)(items);
|
|
26
29
|
let text = response.text?.trim() ?? "";
|
|
27
|
-
if (
|
|
28
|
-
text += `${text ? "\n\n" : ""}附件尚未通过本次 Ability 交付(${omitted} 个);请使用现有聊天附件入口获取。`;
|
|
29
|
-
if (!text)
|
|
30
|
+
if (!text && !items.length)
|
|
30
31
|
throw new Error("任务未返回文字或附件,不能确认执行结果");
|
|
31
32
|
if (text.length > 60_000)
|
|
32
33
|
throw new Error("任务返回文字超过 60,000 字符,未截断或宣称交付完成");
|
|
33
|
-
|
|
34
|
+
if (!items.length)
|
|
35
|
+
return { text };
|
|
36
|
+
if (!uploadAttachments)
|
|
37
|
+
throw new Error("宿主未提供认证附件上传入口,附件未交付");
|
|
38
|
+
const attachments = await (0, agent_1.abortable)(uploadAttachments(items), signal);
|
|
39
|
+
signal.throwIfAborted();
|
|
40
|
+
if (!Array.isArray(attachments) || attachments.length !== items.length)
|
|
41
|
+
throw new Error("AUN FS 附件上传结果不完整,不能确认交付");
|
|
42
|
+
return { text: text || "附件已通过 AUN FS 交付。", attachments };
|
|
34
43
|
},
|
|
35
44
|
};
|
|
36
45
|
}
|
|
46
|
+
/** 具体入口复用原任务执行、审批及会话隔离,只声明已有传输能交付的类型。 */
|
|
47
|
+
function createTaskAliases(task, outputs = []) {
|
|
48
|
+
return [
|
|
49
|
+
{ path: "agent/chat/run", name: "桌面 AI 聊天", summary: "向目标桌面 Agent 提交自然语言聊天任务。" },
|
|
50
|
+
...outputs.map(kind => ({ path: `agent/${kind}/generate`, name: { image: "生成图片", video: "生成视频", document: "生成文档" }[kind], summary: { image: "请求目标桌面 Agent 生成图片,回传其实际生成的图片附件。", video: "请求目标桌面 Agent 生成视频,回传其实际生成的视频附件。", document: "请求目标桌面 Agent 生成文档,回传其本轮明确交付的文件。" }[kind] })),
|
|
51
|
+
].map(({ path, name, summary }) => ({ definition: { ...task.definition, path, name, summary: `${summary}复用 agent/task/run 的执行范围和限制;是否生成成功以实际结果为准,附件通过 AUN FS 引用交付,上传失败则调用失败。逐次 Owner 确认。` }, handler: task.handler }));
|
|
52
|
+
}
|
|
@@ -10,6 +10,7 @@ exports.launchManagedAndWait = launchManagedAndWait;
|
|
|
10
10
|
exports.restartOwnedAndWait = restartOwnedAndWait;
|
|
11
11
|
exports.selectDesktopPort = selectDesktopPort;
|
|
12
12
|
exports.prepareDesktopPort = prepareDesktopPort;
|
|
13
|
+
exports.errorHasCode = errorHasCode;
|
|
13
14
|
exports.terminateWindowsDesktop = terminateWindowsDesktop;
|
|
14
15
|
exports.terminateOwnedProcess = terminateOwnedProcess;
|
|
15
16
|
exports.findChatgptExecutable = findChatgptExecutable;
|
|
@@ -185,9 +186,11 @@ async function launchAndWait(executable, args, connect, timeoutMs, launch = (fil
|
|
|
185
186
|
child.unref();
|
|
186
187
|
return waitFor(connect, timeoutMs, 250);
|
|
187
188
|
}
|
|
188
|
-
async function launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess, launch = (file, argv) => (0, node_child_process_1.spawn)(file, argv, { env: desktopLaunchEnvironment(), detached: true, stdio: "ignore", windowsHide: false })) {
|
|
189
|
+
async function launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess, launch = (file, argv) => (0, node_child_process_1.spawn)(file, argv, { env: desktopLaunchEnvironment(), detached: true, stdio: "ignore", windowsHide: false }), signal) {
|
|
190
|
+
signal?.throwIfAborted();
|
|
189
191
|
if (profileDirectory)
|
|
190
192
|
await (0, promises_1.mkdir)(profileDirectory, { recursive: true });
|
|
193
|
+
signal?.throwIfAborted();
|
|
191
194
|
const child = launch(executable, profileDirectory ? [...args, `--user-data-dir=${profileDirectory}`] : args);
|
|
192
195
|
// 先等待 spawn,避免异步 error 终止 daemon 或在启动失败后继续轮询。
|
|
193
196
|
const events = child;
|
|
@@ -197,45 +200,80 @@ async function launchManagedAndWait(executable, args, profileDirectory, connect,
|
|
|
197
200
|
}) : Promise.resolve();
|
|
198
201
|
child.unref();
|
|
199
202
|
onProcess(child);
|
|
203
|
+
let onAbort;
|
|
204
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
205
|
+
if (signal?.aborted)
|
|
206
|
+
reject(signal.reason);
|
|
207
|
+
else if (signal) {
|
|
208
|
+
onAbort = () => reject(signal.reason);
|
|
209
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
210
|
+
}
|
|
211
|
+
});
|
|
200
212
|
try {
|
|
201
|
-
await started;
|
|
202
|
-
return await waitFor(connect, timeoutMs, 250);
|
|
213
|
+
await (signal ? Promise.race([started, aborted]) : started);
|
|
214
|
+
return await waitFor(connect, timeoutMs, 250, signal);
|
|
203
215
|
}
|
|
204
216
|
catch (error) {
|
|
205
|
-
|
|
217
|
+
try {
|
|
218
|
+
await terminateOwnedProcess(child);
|
|
219
|
+
}
|
|
220
|
+
catch (cleanupError) {
|
|
221
|
+
throw new Error(`桌面启动取消后清理托管进程失败:${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`, { cause: cleanupError });
|
|
222
|
+
}
|
|
206
223
|
onProcess(undefined);
|
|
207
224
|
throw error;
|
|
208
225
|
}
|
|
226
|
+
finally {
|
|
227
|
+
if (signal && onAbort)
|
|
228
|
+
signal.removeEventListener("abort", onAbort);
|
|
229
|
+
}
|
|
209
230
|
}
|
|
210
|
-
async function restartOwnedAndWait(child, executable, args, profileDirectory, connect, timeoutMs, onProcess) {
|
|
231
|
+
async function restartOwnedAndWait(child, executable, args, profileDirectory, connect, timeoutMs, onProcess, signal) {
|
|
211
232
|
await terminateOwnedProcess(child);
|
|
212
233
|
onProcess(undefined);
|
|
213
|
-
return launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess);
|
|
234
|
+
return launchManagedAndWait(executable, args, profileDirectory, connect, timeoutMs, onProcess, undefined, signal);
|
|
214
235
|
}
|
|
215
|
-
async function selectDesktopPort(preferred) {
|
|
236
|
+
async function selectDesktopPort(preferred, forceNew = false) {
|
|
216
237
|
const available = (port) => new Promise(resolve => {
|
|
217
238
|
const server = (0, node_net_1.createServer)();
|
|
218
239
|
server.once("error", () => resolve(false));
|
|
219
240
|
server.listen(port, "127.0.0.1", () => server.close(error => resolve(!error)));
|
|
220
241
|
});
|
|
221
|
-
if (await available(preferred))
|
|
242
|
+
if (!forceNew && await available(preferred))
|
|
222
243
|
return preferred;
|
|
223
|
-
|
|
224
|
-
const
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
244
|
+
for (let attempt = 0; attempt < 8; attempt++) {
|
|
245
|
+
const port = await new Promise((resolve, reject) => {
|
|
246
|
+
const server = (0, node_net_1.createServer)();
|
|
247
|
+
server.once("error", reject);
|
|
248
|
+
server.listen(0, "127.0.0.1", () => {
|
|
249
|
+
const address = server.address();
|
|
250
|
+
server.close(error => error ? reject(error) : address && typeof address !== "string" ? resolve(address.port) : reject(new Error("无法分配桌面 CDP 端口")));
|
|
251
|
+
});
|
|
229
252
|
});
|
|
230
|
-
|
|
253
|
+
if (!forceNew || port !== preferred)
|
|
254
|
+
return port;
|
|
255
|
+
}
|
|
256
|
+
throw new Error(`无法为桌面分配不同于 ${preferred} 的 CDP 端口`);
|
|
231
257
|
}
|
|
232
258
|
/** 启动桥接桌面前清理同一安装路径的旧实例,再选择可用 CDP 端口。 */
|
|
233
|
-
async function prepareDesktopPort(executable, preferred, platform = process.platform, terminate = terminateWindowsDesktop) {
|
|
259
|
+
async function prepareDesktopPort(executable, preferred, platform = process.platform, terminate = terminateWindowsDesktop, forceNew = false) {
|
|
234
260
|
if (platform === "win32")
|
|
235
261
|
await terminate(executable);
|
|
236
|
-
return selectDesktopPort(preferred);
|
|
262
|
+
return selectDesktopPort(preferred, forceNew);
|
|
237
263
|
}
|
|
238
|
-
|
|
264
|
+
function errorHasCode(error, code) {
|
|
265
|
+
const seen = new Set();
|
|
266
|
+
let current = error;
|
|
267
|
+
while (current && typeof current === "object" && !seen.has(current)) {
|
|
268
|
+
seen.add(current);
|
|
269
|
+
const candidate = current;
|
|
270
|
+
if (candidate.code === code)
|
|
271
|
+
return true;
|
|
272
|
+
current = candidate.cause;
|
|
273
|
+
}
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
/** 清理同一用户、同一安装路径的主进程,包括没有 CDP 参数的旧单实例。 */
|
|
239
277
|
async function terminateWindowsDesktop(executable, keepPort, platform = process.platform, run = execFileAsync) {
|
|
240
278
|
if (platform !== "win32")
|
|
241
279
|
return [];
|
|
@@ -248,8 +286,13 @@ $ProgressPreference = 'SilentlyContinue'
|
|
|
248
286
|
$target = '${(0, node_path_1.resolve)(executable).replace(/'/g, "''")}'
|
|
249
287
|
$sid = [Security.Principal.WindowsIdentity]::GetCurrent().User.Value
|
|
250
288
|
$all = @(Get-CimInstance Win32_Process)
|
|
251
|
-
$
|
|
252
|
-
$processes = @($all | Where-Object {
|
|
289
|
+
$escapedTarget = [regex]::Escape($target)
|
|
290
|
+
$processes = @($all | Where-Object {
|
|
291
|
+
$command = [string]$_.CommandLine
|
|
292
|
+
$_.ExecutablePath -ieq $target -and $command -and
|
|
293
|
+
($command -match '(?i)(?:^|[\\s"])--remote-debugging-(?:port|address)(?:=|\\s|")' -or $command.Trim() -match ('^"?' + $escapedTarget + '"?\\s*$')) -and
|
|
294
|
+
$command -notmatch '(?i)(?:^|[\\s"])--type(?:=|\\s|")|browser-extension-relay-worker'
|
|
295
|
+
} | Where-Object { (Invoke-CimMethod -InputObject $_ -MethodName GetOwnerSid).Sid -eq $sid })
|
|
253
296
|
$ids = @($processes.ProcessId)
|
|
254
297
|
$roots = @($processes | Where-Object { $ids -notcontains $_.ParentProcessId })
|
|
255
298
|
${keepPort === undefined ? "" : `
|
|
@@ -296,7 +339,7 @@ async function terminateOwnedProcess(child, platform = process.platform, run = a
|
|
|
296
339
|
await run("taskkill.exe", ["/PID", String(pid), "/T", "/F"]);
|
|
297
340
|
}
|
|
298
341
|
catch (error) {
|
|
299
|
-
if (
|
|
342
|
+
if (child.exitCode === null && !child.signalCode && error.code !== "ESRCH")
|
|
300
343
|
throw error;
|
|
301
344
|
}
|
|
302
345
|
}
|
|
@@ -324,17 +367,43 @@ async function findChatgptExecutable(configured) {
|
|
|
324
367
|
return undefined;
|
|
325
368
|
}
|
|
326
369
|
}
|
|
327
|
-
async function waitFor(action, timeoutMs, intervalMs = 500) {
|
|
370
|
+
async function waitFor(action, timeoutMs, intervalMs = 500, signal) {
|
|
371
|
+
signal?.throwIfAborted();
|
|
328
372
|
const deadline = Date.now() + timeoutMs;
|
|
329
373
|
let last;
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
374
|
+
let onAbort;
|
|
375
|
+
const aborted = signal && new Promise((_resolve, reject) => {
|
|
376
|
+
if (signal.aborted)
|
|
377
|
+
reject(signal.reason);
|
|
378
|
+
else {
|
|
379
|
+
onAbort = () => reject(signal.reason);
|
|
380
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
333
381
|
}
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
382
|
+
});
|
|
383
|
+
try {
|
|
384
|
+
while (Date.now() < deadline) {
|
|
385
|
+
signal?.throwIfAborted();
|
|
386
|
+
try {
|
|
387
|
+
return await (aborted ? Promise.race([action(), aborted]) : action());
|
|
388
|
+
}
|
|
389
|
+
catch (error) {
|
|
390
|
+
if (signal?.aborted)
|
|
391
|
+
throw signal.reason;
|
|
392
|
+
last = error;
|
|
393
|
+
let timer;
|
|
394
|
+
try {
|
|
395
|
+
const delay = new Promise(resolve => { timer = setTimeout(resolve, intervalMs); });
|
|
396
|
+
await (aborted ? Promise.race([delay, aborted]) : delay);
|
|
397
|
+
}
|
|
398
|
+
finally {
|
|
399
|
+
clearTimeout(timer);
|
|
400
|
+
}
|
|
401
|
+
}
|
|
337
402
|
}
|
|
403
|
+
throw last instanceof Error ? last : new Error("桌面程序启动超时");
|
|
404
|
+
}
|
|
405
|
+
finally {
|
|
406
|
+
if (signal && onAbort)
|
|
407
|
+
signal.removeEventListener("abort", onAbort);
|
|
338
408
|
}
|
|
339
|
-
throw last instanceof Error ? last : new Error("桌面程序启动超时");
|
|
340
409
|
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.recoverDesktop = recoverDesktop;
|
|
4
|
+
exports.retainDesktop = retainDesktop;
|
|
5
|
+
const desktop_launch_1 = require("./desktop-launch");
|
|
6
|
+
/** 新后台和独立插件共用的恢复流程,旧后台也能通过插件更新获得修复。 */
|
|
7
|
+
async function recoverDesktop(request) {
|
|
8
|
+
const { signal } = request;
|
|
9
|
+
signal?.throwIfAborted();
|
|
10
|
+
if (request.ownedProcess) {
|
|
11
|
+
await (0, desktop_launch_1.terminateOwnedProcess)(request.ownedProcess);
|
|
12
|
+
request.onProcess(undefined);
|
|
13
|
+
}
|
|
14
|
+
signal?.throwIfAborted();
|
|
15
|
+
let port;
|
|
16
|
+
try {
|
|
17
|
+
port = await (0, desktop_launch_1.prepareDesktopPort)(request.executable, request.preferredPort, process.platform, desktop_launch_1.terminateWindowsDesktop, request.forceNewPort);
|
|
18
|
+
}
|
|
19
|
+
catch (cause) {
|
|
20
|
+
throw new Error(`桌面恢复前清理旧实例或分配端口失败:${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
21
|
+
}
|
|
22
|
+
signal?.throwIfAborted();
|
|
23
|
+
await request.beforeLaunch?.(port);
|
|
24
|
+
signal?.throwIfAborted();
|
|
25
|
+
return (0, desktop_launch_1.launchManagedAndWait)(request.executable, request.args(port), request.profileDirectory, request.connect, request.timeoutMs, request.onProcess, request.launch, signal);
|
|
26
|
+
}
|
|
27
|
+
async function retainDesktop(executable, port) {
|
|
28
|
+
await (0, desktop_launch_1.terminateWindowsDesktop)(executable, port);
|
|
29
|
+
}
|