agent-bridge-qwenwork 1.0.24 → 1.0.25
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/dist/src-ts/agent.js
CHANGED
|
@@ -1,7 +1,42 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.AgentOperationError = exports.AgentError = void 0;
|
|
4
|
+
exports.abortable = abortable;
|
|
4
5
|
exports.errorDetails = errorDetails;
|
|
6
|
+
async function abortable(promise, signal) {
|
|
7
|
+
if (!signal)
|
|
8
|
+
return promise;
|
|
9
|
+
if (signal.aborted) {
|
|
10
|
+
// promise 已在调用方启动,先观察其拒绝,避免预取消时产生未处理拒绝。
|
|
11
|
+
void promise.catch(() => undefined);
|
|
12
|
+
signal.throwIfAborted();
|
|
13
|
+
}
|
|
14
|
+
return new Promise((resolve, reject) => {
|
|
15
|
+
let settled = false;
|
|
16
|
+
const cleanup = () => signal.removeEventListener("abort", abort);
|
|
17
|
+
const abort = () => {
|
|
18
|
+
if (settled)
|
|
19
|
+
return;
|
|
20
|
+
settled = true;
|
|
21
|
+
cleanup();
|
|
22
|
+
reject(signal.reason);
|
|
23
|
+
};
|
|
24
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
25
|
+
promise.then((value) => {
|
|
26
|
+
if (settled)
|
|
27
|
+
return;
|
|
28
|
+
settled = true;
|
|
29
|
+
cleanup();
|
|
30
|
+
resolve(value);
|
|
31
|
+
}, (error) => {
|
|
32
|
+
if (settled)
|
|
33
|
+
return;
|
|
34
|
+
settled = true;
|
|
35
|
+
cleanup();
|
|
36
|
+
reject(error);
|
|
37
|
+
});
|
|
38
|
+
});
|
|
39
|
+
}
|
|
5
40
|
class AgentError extends Error {
|
|
6
41
|
constructor(message, options) {
|
|
7
42
|
super(message, options);
|
|
@@ -22,8 +22,11 @@ async function findWindowsExecutable(fileName, configured) {
|
|
|
22
22
|
const configuredPath = (0, node_path_1.resolve)(configured);
|
|
23
23
|
if (fileName.toLowerCase() === "doubao.exe") {
|
|
24
24
|
let root = (0, node_path_1.dirname)(configuredPath);
|
|
25
|
-
while (/^app$/i.test((0, node_path_1.basename)(root)) || versionDirectory.test((0, node_path_1.basename)(root)))
|
|
25
|
+
while (/^(?:app|launcher|doubao_update)$/i.test((0, node_path_1.basename)(root)) || versionDirectory.test((0, node_path_1.basename)(root)))
|
|
26
26
|
root = (0, node_path_1.dirname)(root);
|
|
27
|
+
const updated = (0, node_path_1.join)(root, "Doubao_update", fileName);
|
|
28
|
+
if ((0, node_fs_1.existsSync)(updated))
|
|
29
|
+
return updated;
|
|
27
30
|
const latest = await findExecutableInTree(root, fileName, /^/, 3);
|
|
28
31
|
if (latest)
|
|
29
32
|
return latest;
|
|
@@ -64,8 +67,11 @@ async function search(directory, fileName, pattern, depth, insideProduct) {
|
|
|
64
67
|
const entries = await (0, promises_1.readdir)(directory, { withFileTypes: true });
|
|
65
68
|
// 豆包上层文件是启动器,优先查找新版目录或 app 中的实际程序。
|
|
66
69
|
if (insideProduct && depth > 0 && fileName.toLowerCase() === "doubao.exe") {
|
|
67
|
-
const versions = entries.filter(entry => entry.isDirectory() && (versionDirectory.test(entry.name) || /^app$/i.test(entry.name)));
|
|
68
|
-
versions.sort((left, right) =>
|
|
70
|
+
const versions = entries.filter(entry => entry.isDirectory() && (versionDirectory.test(entry.name) || /^(?:app|doubao_update)$/i.test(entry.name)));
|
|
71
|
+
versions.sort((left, right) => {
|
|
72
|
+
const rank = (name) => /^doubao_update$/i.test(name) ? 2 : /^app$/i.test(name) ? 0 : 1;
|
|
73
|
+
return rank(right.name) - rank(left.name) || right.name.replace(/^\D+/, "").localeCompare(left.name.replace(/^\D+/, ""), "en", { numeric: true });
|
|
74
|
+
});
|
|
69
75
|
for (const entry of versions) {
|
|
70
76
|
const found = await search((0, node_path_1.join)(directory, entry.name), fileName, pattern, depth - 1, true);
|
|
71
77
|
if (found)
|
|
@@ -73,7 +79,7 @@ async function search(directory, fileName, pattern, depth, insideProduct) {
|
|
|
73
79
|
}
|
|
74
80
|
}
|
|
75
81
|
for (const entry of entries)
|
|
76
|
-
if (entry.isFile() && insideProduct && entry.name.toLowerCase() === fileName.toLowerCase())
|
|
82
|
+
if (entry.isFile() && insideProduct && entry.name.toLowerCase() === fileName.toLowerCase() && !(fileName.toLowerCase() === "doubao.exe" && /^(?:launcher|doubao)$/i.test((0, node_path_1.basename)(directory))))
|
|
77
83
|
return (0, node_path_1.join)(directory, entry.name);
|
|
78
84
|
if (depth <= 0)
|
|
79
85
|
return undefined;
|
|
@@ -127,19 +127,40 @@ class QwenCdpClient {
|
|
|
127
127
|
const reply = await this.direct(`这是后台健康检测。请只回复 ${token},不要添加任何其它文字。`, 45_000, undefined, token);
|
|
128
128
|
verifyQwenHeartbeatReply(token, reply);
|
|
129
129
|
}
|
|
130
|
-
async createSession(_name) {
|
|
130
|
+
async createSession(_name, forceNew = false, preserveDraft = false) {
|
|
131
131
|
await this.ensureVisible();
|
|
132
|
-
|
|
132
|
+
if (!preserveDraft)
|
|
133
|
+
await this.recoverDraft();
|
|
133
134
|
const snapshot = `(() => ({ url: location.href, messages: document.querySelectorAll('[data-message-id]').length, input: document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText ?? null, blank: Boolean(document.querySelector('.new-task-model-selector')) }))()`;
|
|
134
135
|
const before = await this.evaluate(snapshot);
|
|
135
136
|
if (before.input?.trim())
|
|
136
137
|
throw new Error("千问输入框含有未发送内容,不能新建会话");
|
|
137
|
-
if (before.input !== null && before.messages === 0 && before.blank)
|
|
138
|
-
return;
|
|
139
|
-
const clicked = await this.evaluate(`(() => { const button = document.querySelector('button[aria-label="新任务"]'); if (!button || button.disabled || button.getAttribute('aria-disabled') === 'true') return false; button.click(); return true; })()`);
|
|
138
|
+
if (!forceNew && before.input !== null && before.messages === 0 && before.blank)
|
|
139
|
+
return this.currentSessionId();
|
|
140
|
+
const clicked = await this.evaluate(`(() => { if (document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText.trim() || document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')) throw new Error('千问当前有未发送内容或正在生成回复,不能新建会话'); const button = document.querySelector('button[aria-label="新任务"]'); if (!button || button.disabled || button.getAttribute('aria-disabled') === 'true') return false; button.click(); return true; })()`);
|
|
140
141
|
if (clicked !== true)
|
|
141
142
|
throw new Error("千问新任务入口未找到或不可用");
|
|
142
143
|
await this.waitFor(`(() => { const state = ${snapshot}; return state.input !== null && state.input.trim() === '' && state.messages === 0 && state.url !== ${JSON.stringify(before.url)}; })()`, "千问新会话状态校验失败");
|
|
144
|
+
return this.currentSessionId();
|
|
145
|
+
}
|
|
146
|
+
async currentSessionId() {
|
|
147
|
+
const href = String(await this.evaluate("location.href"));
|
|
148
|
+
try {
|
|
149
|
+
return new URL(href).searchParams.get("chat") ?? undefined;
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
return undefined;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async activateSession(sessionId) {
|
|
156
|
+
if (!sessionId.trim() || sessionId.length > 512 || /[\u0000-\u001f]/.test(sessionId))
|
|
157
|
+
throw new Error("千问模型会话标识无效");
|
|
158
|
+
await this.ensureVisible();
|
|
159
|
+
const target = new URL(String(await this.evaluate("location.href")));
|
|
160
|
+
target.searchParams.set("chat", sessionId);
|
|
161
|
+
if (target.href !== String(await this.evaluate("location.href")))
|
|
162
|
+
await this.evaluate(`(() => { if (document.querySelector(${JSON.stringify(exports.inputSelector)})?.innerText.trim() || document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')) throw new Error('千问当前有未发送内容或正在生成回复,不能切换会话'); location.href = ${JSON.stringify(target.href)}; })()`);
|
|
163
|
+
await this.waitFor(`location.href === ${JSON.stringify(target.href)} && Boolean(document.querySelector(${JSON.stringify(exports.inputSelector)}))`, "千问个人助理模型会话恢复失败");
|
|
143
164
|
}
|
|
144
165
|
async connect() {
|
|
145
166
|
if (this.connected())
|
|
@@ -204,7 +225,7 @@ class QwenCdpClient {
|
|
|
204
225
|
async direct(text, timeoutMs = 240_000, signal, expectedReply) {
|
|
205
226
|
return (await this.complete(text, timeoutMs, signal, expectedReply)).text;
|
|
206
227
|
}
|
|
207
|
-
async complete(text, timeoutMs = 240_000, signal, expectedReply, attachments, onMessage) {
|
|
228
|
+
async complete(text, timeoutMs = 240_000, signal, expectedReply, attachments, onMessage, preserveDraft = false) {
|
|
208
229
|
let stage = "准备千问办公桌面任务";
|
|
209
230
|
let code = "QWEN_TASK_FAILED";
|
|
210
231
|
try {
|
|
@@ -215,7 +236,8 @@ class QwenCdpClient {
|
|
|
215
236
|
throw new Error("千问输入框有用户草稿,跳过后台健康检测");
|
|
216
237
|
}
|
|
217
238
|
await this.ensureVisible();
|
|
218
|
-
|
|
239
|
+
if (!preserveDraft)
|
|
240
|
+
await this.recoverDraft();
|
|
219
241
|
const ready = await this.evaluate(`(() => { const input = document.querySelector(${JSON.stringify(exports.inputSelector)}); return Boolean(input && !input.innerText.trim() && !document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]')); })()`);
|
|
220
242
|
if (!ready)
|
|
221
243
|
throw new Error("千问输入框含有未发送内容或正在生成回复,未发送新消息");
|
|
@@ -254,23 +276,37 @@ class QwenCdpClient {
|
|
|
254
276
|
code = "QWEN_REPLY_FAILED";
|
|
255
277
|
let previousReply = "";
|
|
256
278
|
let stablePolls = 0;
|
|
279
|
+
let seenGenerating = false;
|
|
280
|
+
let stoppedPolls = 0;
|
|
257
281
|
const forwarded = new Set();
|
|
258
282
|
const deadline = Date.now() + timeoutMs;
|
|
259
|
-
while (Date.now() < deadline) {
|
|
260
|
-
|
|
283
|
+
while (Date.now() < deadline || signal?.aborted) {
|
|
284
|
+
// 上游取消不停止桌面生成;确认结束前保留插件队列。
|
|
285
|
+
await wait(2_000);
|
|
261
286
|
const messagesJson = await this.evaluate(`JSON.stringify([...document.querySelectorAll(${JSON.stringify(exports.assistantMessageSelector)})].map(element => ({ id: element.getAttribute('data-message-id'), text: element.innerText })))`);
|
|
262
|
-
const
|
|
287
|
+
const messages = JSON.parse(messagesJson || "[]");
|
|
288
|
+
const fresh = freshAssistantMessages(beforeIds, messages);
|
|
263
289
|
const reply = fresh.at(-1)?.text.trim() ?? "";
|
|
264
290
|
stablePolls = reply && reply === previousReply ? stablePolls + 1 : 0;
|
|
265
291
|
previousReply = reply;
|
|
266
292
|
if (reply && stablePolls >= 3 && isQwenApiUnavailableReply(reply))
|
|
267
293
|
throw new Error("QWEN_REMOTE_ERROR:千问生成接口不可用;桌面仅返回通用错误,未提供服务端错误码;CDP 仍连接,未重启或重新提交任务");
|
|
268
294
|
const generating = await this.evaluate(`Boolean(document.querySelector('button[aria-label="停止"],button[aria-label="停止生成"],button[aria-label="Stop generating"]'))`);
|
|
295
|
+
seenGenerating ||= generating === true;
|
|
296
|
+
stoppedPolls = seenGenerating && generating === false ? stoppedPolls + 1 : 0;
|
|
297
|
+
if (signal?.aborted && !reply && stoppedPolls >= 2 && messages.some(message => message.id && !beforeIds.has(message.id))) {
|
|
298
|
+
const attachments = expectedReply ? [] : await this.readArtifacts(beforeIds, sessionUrl);
|
|
299
|
+
if (attachments.length)
|
|
300
|
+
return { text: "", sessionId: new URL(sessionUrl).searchParams.get("chat") ?? undefined, attachments };
|
|
301
|
+
code = "QWEN_REQUEST_CANCELLED";
|
|
302
|
+
throw new Error("请求已取消,已确认本轮桌面生成结束,未返回正文或附件");
|
|
303
|
+
}
|
|
269
304
|
if (!generating && (expectedReply ? isQwenHeartbeatReplyComplete(reply, expectedReply) && stablePolls >= 1 : reply && stablePolls >= 3)) {
|
|
270
305
|
stage = "读取千问办公已完成任务的产物(尚未上传 AUN FS)";
|
|
271
306
|
code = "QWEN_ARTIFACT_READ_FAILED";
|
|
272
307
|
const attachments = expectedReply ? [] : await this.readArtifacts(beforeIds, sessionUrl);
|
|
273
|
-
|
|
308
|
+
const sessionId = new URL(sessionUrl).searchParams.get("chat") ?? undefined;
|
|
309
|
+
return { text: reply, ...(sessionId ? { sessionId } : {}), ...(attachments.length ? { attachments } : {}) };
|
|
274
310
|
}
|
|
275
311
|
if (onMessage && generating && reply && stablePolls >= 1 && !forwarded.has(reply) && !isQwenApiUnavailableReply(reply)) {
|
|
276
312
|
await onMessage(reply);
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.QwenworkPlugin = exports.qwenworkManifest = void 0;
|
|
4
4
|
exports.createQwenworkPlugin = createQwenworkPlugin;
|
|
5
|
+
const promises_1 = require("node:fs/promises");
|
|
6
|
+
const node_path_1 = require("node:path");
|
|
5
7
|
const agent_1 = require("../../agent");
|
|
6
8
|
const openai_adapter_1 = require("./openai-adapter");
|
|
7
9
|
const cdp_client_1 = require("./cdp-client");
|
|
@@ -10,21 +12,29 @@ const desktop_launch_1 = require("../desktop-launch");
|
|
|
10
12
|
const session_history_1 = require("./session-history");
|
|
11
13
|
exports.qwenworkManifest = {
|
|
12
14
|
id: "qwenwork",
|
|
13
|
-
version: "1.0.
|
|
15
|
+
version: "1.0.25",
|
|
14
16
|
displayName: "千问办公",
|
|
15
17
|
entry: "dist/index.js",
|
|
16
18
|
apiVersion: "1",
|
|
17
19
|
process: "in-process",
|
|
18
|
-
capabilities: ["chat", "openai-compatible", "health"],
|
|
20
|
+
capabilities: ["chat", "openai-compatible", "health", "model-provider"],
|
|
19
21
|
configSchema: "config.schema.json",
|
|
20
22
|
defaults: { cdpPort: 9228, httpPort: 17893 },
|
|
21
23
|
};
|
|
22
24
|
function asNumber(value, fallback) {
|
|
23
25
|
return typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
|
24
26
|
}
|
|
27
|
+
function validModelSessionId(value) {
|
|
28
|
+
return typeof value === "string" && Boolean(value.trim()) && value.length <= 512 && !/[\u0000-\u001f]/.test(value);
|
|
29
|
+
}
|
|
25
30
|
/** 千问插件由后台守护,所有通道共用请求队列和恢复流程。 */
|
|
26
31
|
class QwenworkPlugin {
|
|
27
32
|
manifest = exports.qwenworkManifest;
|
|
33
|
+
get modelProvider() {
|
|
34
|
+
if (this.relayTarget || !this.client?.complete || !this.client.createSession || !this.client.activateSession)
|
|
35
|
+
return undefined;
|
|
36
|
+
return { complete: (request) => this.completeModelProvider(request) };
|
|
37
|
+
}
|
|
28
38
|
sessionHistory;
|
|
29
39
|
get attachmentInput() { return Boolean(this.relayTarget || this.client?.attachmentInput); }
|
|
30
40
|
sessionOperations = [];
|
|
@@ -42,6 +52,7 @@ class QwenworkPlugin {
|
|
|
42
52
|
state = "stopped";
|
|
43
53
|
message = "";
|
|
44
54
|
healthIntervalMs;
|
|
55
|
+
restartDesktopHook;
|
|
45
56
|
healthTimer;
|
|
46
57
|
recovery;
|
|
47
58
|
context;
|
|
@@ -53,11 +64,14 @@ class QwenworkPlugin {
|
|
|
53
64
|
busy = false;
|
|
54
65
|
taskCount = 0;
|
|
55
66
|
stopped = true;
|
|
67
|
+
modelSessions = new Map();
|
|
68
|
+
modelSessionsPath;
|
|
56
69
|
constructor(options = {}) {
|
|
57
70
|
this.injectedClient = options.client;
|
|
58
71
|
this.configuredCdpPort = options.cdpPort;
|
|
59
72
|
this.configuredHttpPort = options.httpPort;
|
|
60
73
|
this.healthIntervalMs = options.healthIntervalMs ?? 30_000;
|
|
74
|
+
this.restartDesktopHook = options.restartDesktop;
|
|
61
75
|
}
|
|
62
76
|
async activate(context) {
|
|
63
77
|
if (this.state === "ready")
|
|
@@ -68,6 +82,21 @@ class QwenworkPlugin {
|
|
|
68
82
|
this.lastHeartbeat = undefined;
|
|
69
83
|
this.context = context;
|
|
70
84
|
try {
|
|
85
|
+
this.modelSessions.clear();
|
|
86
|
+
this.modelSessionsPath = typeof context.dataDir === "string" && context.dataDir ? (0, node_path_1.join)(context.dataDir, "model-provider-sessions.json") : undefined;
|
|
87
|
+
try {
|
|
88
|
+
if (!this.modelSessionsPath)
|
|
89
|
+
throw Object.assign(new Error("无持久化目录"), { code: "ENOENT" });
|
|
90
|
+
const saved = JSON.parse(await (0, promises_1.readFile)(this.modelSessionsPath, "utf8"));
|
|
91
|
+
if (!saved || typeof saved !== "object" || Array.isArray(saved) || Object.entries(saved).some(([key, value]) => !validModelSessionId(key) || !validModelSessionId(value)))
|
|
92
|
+
throw new Error("千问个人助理模型会话记录无效");
|
|
93
|
+
for (const [key, value] of Object.entries(saved))
|
|
94
|
+
this.modelSessions.set(key, value);
|
|
95
|
+
}
|
|
96
|
+
catch (error) {
|
|
97
|
+
if (error.code !== "ENOENT")
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
71
100
|
const config = context.config;
|
|
72
101
|
const relayTarget = config.relayTarget;
|
|
73
102
|
if (relayTarget !== undefined && relayTarget !== "dsh")
|
|
@@ -106,6 +135,7 @@ class QwenworkPlugin {
|
|
|
106
135
|
if (!executable)
|
|
107
136
|
throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
|
|
108
137
|
context.logger?.info(`正在启动千问办公,等待 CDP ${this.activeCdpPort}`, { executablePath: executable });
|
|
138
|
+
await this.restartDesktopProcess(executable);
|
|
109
139
|
try {
|
|
110
140
|
await (0, desktop_launch_1.launchAndWait)(executable, [`--remote-debugging-port=${this.activeCdpPort}`], () => client.connect(), typeof config.startupTimeoutMs === "number" ? config.startupTimeoutMs : 30_000);
|
|
111
141
|
}
|
|
@@ -140,8 +170,15 @@ class QwenworkPlugin {
|
|
|
140
170
|
throw error;
|
|
141
171
|
}
|
|
142
172
|
}
|
|
143
|
-
async deactivate(
|
|
173
|
+
async deactivate(reason) {
|
|
174
|
+
const reloadDesktop = reason === "reload" && Boolean(this.client) && !this.relayTarget;
|
|
144
175
|
await this.cleanup();
|
|
176
|
+
if (reloadDesktop) {
|
|
177
|
+
if (this.restartDesktopHook)
|
|
178
|
+
await this.restartDesktopHook();
|
|
179
|
+
else if (!this.injectedClient && process.platform === "win32")
|
|
180
|
+
await this.restartDesktopProcess();
|
|
181
|
+
}
|
|
145
182
|
this.state = "stopped";
|
|
146
183
|
this.stopped = true;
|
|
147
184
|
}
|
|
@@ -204,7 +241,7 @@ class QwenworkPlugin {
|
|
|
204
241
|
throw error;
|
|
205
242
|
}
|
|
206
243
|
}
|
|
207
|
-
async completeRequest(request) {
|
|
244
|
+
async completeRequest(request, modelRequest = false) {
|
|
208
245
|
if (this.relayTarget) {
|
|
209
246
|
return this.callPlugin(this.relayTarget, request);
|
|
210
247
|
}
|
|
@@ -217,8 +254,8 @@ class QwenworkPlugin {
|
|
|
217
254
|
throw new Error("千问当前客户端不支持附件输入");
|
|
218
255
|
const timeoutMs = request.timeoutMs ?? asNumber(this.context?.config.timeoutMs, 240_000);
|
|
219
256
|
const response = this.client.complete
|
|
220
|
-
? await this.client.complete(request.task, timeoutMs,
|
|
221
|
-
: { text: await this.complete(request.task, timeoutMs) };
|
|
257
|
+
? await this.client.complete(request.task, timeoutMs, request.signal, undefined, request.attachments, request.onMessage, modelRequest)
|
|
258
|
+
: { text: await this.complete(request.task, timeoutMs, request.signal) };
|
|
222
259
|
if ((0, cdp_client_1.isQwenApiUnavailableReply)(response.text))
|
|
223
260
|
throw new agent_1.AgentOperationError("QWEN_REMOTE_ERROR", "等待千问办公回复", new Error("千问生成接口不可用;桌面未提供具体服务端错误码,CDP 仍连接,未重启或重新提交任务"));
|
|
224
261
|
this.failures = 0;
|
|
@@ -227,12 +264,66 @@ class QwenworkPlugin {
|
|
|
227
264
|
return response;
|
|
228
265
|
}
|
|
229
266
|
catch (error) {
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
267
|
+
if (!request.signal?.aborted && !modelRequest) {
|
|
268
|
+
this.message = error instanceof Error ? error.message : String(error);
|
|
269
|
+
this.failures = this.client.connected() ? 0 : 2;
|
|
270
|
+
this.state = "degraded";
|
|
271
|
+
}
|
|
233
272
|
throw error;
|
|
234
273
|
}
|
|
235
274
|
}
|
|
275
|
+
async completeModelProvider(request) {
|
|
276
|
+
let stage = "千问办公模型排队(queue)";
|
|
277
|
+
try {
|
|
278
|
+
request.signal.throwIfAborted();
|
|
279
|
+
const run = this.enqueueTask(async () => {
|
|
280
|
+
request.signal.throwIfAborted();
|
|
281
|
+
stage = "连接千问办公模型(connect)";
|
|
282
|
+
const client = this.client;
|
|
283
|
+
if (this.state !== "ready" || !client?.connected() || !client.createSession || !client.activateSession || !client.complete)
|
|
284
|
+
throw new Error("千问办公未连接或不支持隔离模型会话,模型请求不会启动或重启桌面");
|
|
285
|
+
const previousSessionId = await client.currentSessionId?.();
|
|
286
|
+
try {
|
|
287
|
+
stage = "准备千问办公模型会话(submit)";
|
|
288
|
+
const desktopSessionId = this.modelSessions.get(request.sessionId);
|
|
289
|
+
if (desktopSessionId)
|
|
290
|
+
await client.activateSession(desktopSessionId);
|
|
291
|
+
else
|
|
292
|
+
await client.createSession(undefined, true, true);
|
|
293
|
+
request.signal.throwIfAborted();
|
|
294
|
+
stage = "等待千问办公模型生成(generate)";
|
|
295
|
+
const response = await this.completeRequest({ task: request.prompt, sessionId: request.sessionId, timeoutMs: request.timeoutMs, signal: request.signal }, true);
|
|
296
|
+
const actualSessionId = response.sessionId ?? await client.currentSessionId?.();
|
|
297
|
+
if (!validModelSessionId(actualSessionId))
|
|
298
|
+
throw new Error("千问未返回可恢复的个人助理模型会话标识");
|
|
299
|
+
if (actualSessionId !== desktopSessionId) {
|
|
300
|
+
this.modelSessions.set(request.sessionId, actualSessionId);
|
|
301
|
+
const path = this.modelSessionsPath;
|
|
302
|
+
if (path) {
|
|
303
|
+
await (0, promises_1.mkdir)(this.context.dataDir ?? ".", { recursive: true });
|
|
304
|
+
await (0, promises_1.writeFile)(`${path}.tmp`, JSON.stringify(Object.fromEntries(this.modelSessions)), { mode: 0o600 });
|
|
305
|
+
await (0, promises_1.rename)(`${path}.tmp`, path);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
return { text: response.text };
|
|
309
|
+
}
|
|
310
|
+
finally {
|
|
311
|
+
if (client.connected()) {
|
|
312
|
+
if (previousSessionId)
|
|
313
|
+
await client.activateSession(previousSessionId);
|
|
314
|
+
else
|
|
315
|
+
await client.createSession(undefined, false, true);
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
});
|
|
319
|
+
return await (0, agent_1.abortable)(run, request.signal);
|
|
320
|
+
}
|
|
321
|
+
catch (error) {
|
|
322
|
+
if (error instanceof agent_1.AgentOperationError)
|
|
323
|
+
throw error;
|
|
324
|
+
throw new agent_1.AgentOperationError("QWEN_MODEL_FAILED", stage, error);
|
|
325
|
+
}
|
|
326
|
+
}
|
|
236
327
|
registerRoutes(http) {
|
|
237
328
|
if (!this.adapter)
|
|
238
329
|
return;
|
|
@@ -262,6 +353,14 @@ class QwenworkPlugin {
|
|
|
262
353
|
this.callPlugin = undefined;
|
|
263
354
|
this.pluginStatus = undefined;
|
|
264
355
|
}
|
|
356
|
+
async restartDesktopProcess(configuredExecutable) {
|
|
357
|
+
const config = this.context?.config;
|
|
358
|
+
const executable = configuredExecutable ?? await (0, desktop_launch_1.findWindowsExecutable)("QwenWorkCN.exe", typeof config?.executablePath === "string" ? config.executablePath : undefined);
|
|
359
|
+
if (!executable)
|
|
360
|
+
throw new Error("未找到 QwenWorkCN.exe,请配置 executablePath");
|
|
361
|
+
const processIds = await (0, desktop_launch_1.terminateWindowsDesktop)(executable);
|
|
362
|
+
this.context?.logger?.info("千问办公重载前已清理旧进程,将以 CDP 模式启动", { processIds, executable });
|
|
363
|
+
}
|
|
265
364
|
startHealthWatch() {
|
|
266
365
|
if (this.relayTarget || !this.client || this.healthTimer)
|
|
267
366
|
return;
|
package/package.json
CHANGED
package/plugin.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"id": "qwenwork",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.25",
|
|
4
4
|
"type": "agent",
|
|
5
5
|
"displayName": "千问办公",
|
|
6
6
|
"entry": "dist/src-ts/plugins/qwenwork/index.js",
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
"capabilities": [
|
|
10
10
|
"chat",
|
|
11
11
|
"openai-compatible",
|
|
12
|
-
"health"
|
|
12
|
+
"health",
|
|
13
|
+
"model-provider"
|
|
13
14
|
],
|
|
14
15
|
"configSchema": "config.schema.json",
|
|
15
16
|
"clientDownloadUrl": "https://qwenwork.cn/download"
|