agent-bridge-qwenwork 1.0.16 → 1.0.20

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 CHANGED
@@ -8,6 +8,8 @@
8
8
 
9
9
  后台每 30 秒检查主页面与 CDP 连接,空闲时每 2 小时最多发送一条带随机校验码的真实测试消息。首次启动及 CDP 恢复后必须完成真实对话,只有千问原样返回本次校验码才判定可用。任务或 `/new` 执行期间不发送检测消息、不执行恢复。普通 API/UI 错误或健康通信失败但 CDP 仍连接时只标记降级;只有 CDP 已断开才允许自动重启千问并重连。AUN、飞书和 HTTP 共用请求队列,恢复不修改 AID 或 owner 配置。`autoStart: false` 禁止自动启动和重启。
10
10
 
11
+ 原生历史读取目前明确不支持:已核验的 CDP/tRPC 客户端只有任务提交等操作,没有只读会话枚举或历史读取接口。插件不会猜测 RPC、把配置中的 `chatId`/`subChatId` 当作当前身份,也不会为读取历史而点击、切换或发送内容;`sessionHistory` 的 scope 固定为本插件配置的 CDP 端口。中继、忙碌、恢复中、离线或未就绪时会返回对应拒绝原因。
12
+
11
13
  请求超时或明确返回“API不可用”时只结束本次请求,已经发送的任务不自动重发,避免重复执行。健康接口 `/api/plugins/qwenwork/health` 的 `lastHeartbeat` 表示最近真实对话验证通过时间,同时返回 `restarts` 和 `recovering`;日志可搜索“千问真实对话心跳通过”“千问心跳失败”“千问自动恢复成功”。自动恢复只在 CDP 断开且当前无任务时结束千问进程及其子进程;daemon 应在已登录的 Windows 用户桌面会话运行。
12
14
 
13
15
  `/new` 在已确认的空白新任务页可重复执行。远程消息和 `/new` 遇到输入框残留时,先将原文、页面地址和时间追加到插件数据目录的 `draft-recovery.jsonl`,再通过编辑器原生删除操作清理;备份失败、内容发生变化或正在生成回复时不清理。后台心跳只清理桥接自己的检测文本,遇到普通用户草稿则跳过。发送消息会点击桌面端“发送消息”按钮并确认输入框清空,避免仅按 Enter 后消息仍停留在输入框。真实通信失败后保持降级,普通 CDP 检查通过不会把状态改回就绪,须有真实回复或真实对话心跳通过。
@@ -512,6 +512,14 @@ class QwenCdpClient {
512
512
  }
513
513
  throw new Error(`tRPC ${path} 超时`);
514
514
  }
515
+ /** 仅开放已核实的会话历史只读查询,不允许从历史 provider 调用 mutation。 */
516
+ async queryHistory(path, input) {
517
+ const result = await this.trpc(path, "query", input);
518
+ const envelope = result;
519
+ if (envelope?.result?.type === "data")
520
+ return envelope.result.data?.json;
521
+ throw new Error(envelope?.result?.error?.json?.message ?? `千问历史查询 ${path} 失败`);
522
+ }
515
523
  async waitFor(expression, message) {
516
524
  const deadline = Date.now() + this.options.timeoutMs;
517
525
  while (Date.now() < deadline) {
@@ -8,10 +8,11 @@ const openai_adapter_1 = require("./openai-adapter");
8
8
  const cdp_client_1 = require("./cdp-client");
9
9
  const plugin_1 = require("../../plugin");
10
10
  const desktop_launch_1 = require("../desktop-launch");
11
+ const session_history_1 = require("./session-history");
11
12
  const CHAT_HEARTBEAT_INTERVAL_MS = 2 * 60 * 60_000;
12
13
  exports.qwenworkManifest = {
13
14
  id: "qwenwork",
14
- version: "1.0.16",
15
+ version: "1.0.20",
15
16
  displayName: "千问办公",
16
17
  entry: "dist/index.js",
17
18
  apiVersion: "1",
@@ -26,6 +27,7 @@ function asNumber(value, fallback) {
26
27
  /** 千问插件由后台守护,所有通道共用请求队列和恢复流程。 */
27
28
  class QwenworkPlugin {
28
29
  manifest = exports.qwenworkManifest;
30
+ sessionHistory;
29
31
  get attachmentInput() { return Boolean(this.relayTarget || this.client?.attachmentInput); }
30
32
  sessionOperations = [];
31
33
  injectedClient;
@@ -81,6 +83,15 @@ class QwenworkPlugin {
81
83
  this.callPlugin = context.callPlugin;
82
84
  this.pluginStatus = context.pluginStatus;
83
85
  this.activeCdpPort = (0, plugin_1.resolveRuntimePort)(config, context.runtime, "qwenwork", "QWEN_CDP_PORT", this.configuredCdpPort ?? exports.qwenworkManifest.defaults.cdpPort);
86
+ this.sessionHistory = new session_history_1.QwenworkSessionHistoryProvider({
87
+ scope: `qwenwork:cdp:${this.activeCdpPort}`,
88
+ unavailableReason: () => this.relayTarget ? "千问办公中继模式不支持原生历史读取" : this.busy ? "千问办公当前忙,暂不读取历史" : this.recovery ? "千问办公正在恢复,暂不读取历史" : this.client && !this.client.connected() ? "千问办公当前离线,暂不读取历史" : this.state !== "ready" ? "千问办公当前未就绪,暂不读取历史" : "",
89
+ query: async (path, input) => {
90
+ if (!this.client?.queryHistory)
91
+ throw new Error("当前千问客户端没有只读会话查询能力");
92
+ return this.client.queryHistory(path, input);
93
+ },
94
+ });
84
95
  if (!this.relayTarget) {
85
96
  const client = this.injectedClient ?? new cdp_client_1.QwenCdpClient({
86
97
  port: this.activeCdpPort,
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QwenworkSessionHistoryProvider = void 0;
4
+ const node_crypto_1 = require("node:crypto");
5
+ const MAX_SESSIONS = 1000;
6
+ const MAX_MESSAGE_PAGES = 20;
7
+ const MESSAGE_PAGE_SIZE = 100;
8
+ const MAX_READ_TURNS = MAX_MESSAGE_PAGES * MESSAGE_PAGE_SIZE;
9
+ function object(value) {
10
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
11
+ }
12
+ function rows(value) {
13
+ if (!Array.isArray(value))
14
+ return { rows: [], malformed: true };
15
+ const valid = value.filter((item) => typeof object(item)?.id === "string");
16
+ return { rows: valid, malformed: valid.length !== value.length };
17
+ }
18
+ function asTime(value) {
19
+ const time = value instanceof Date ? value.toISOString() : typeof value === "string" ? value : undefined;
20
+ return time && Number.isFinite(Date.parse(time)) ? new Date(time).toISOString() : undefined;
21
+ }
22
+ function subChats(value) {
23
+ const chat = object(value);
24
+ if (!Array.isArray(chat?.subChats))
25
+ return { rows: [], malformed: true };
26
+ const valid = chat.subChats.filter((item) => typeof object(item)?.id === "string");
27
+ return { rows: valid, malformed: valid.length !== chat.subChats.length };
28
+ }
29
+ function sessionFromChat(chat) {
30
+ const updatedAt = asTime(chat.updatedAt);
31
+ return { id: chat.id, title: typeof chat.name === "string" && chat.name.trim() ? chat.name.trim() : "未命名会话", ...(updatedAt ? { updatedAt } : {}) };
32
+ }
33
+ function fingerprint(value) {
34
+ return (0, node_crypto_1.createHash)("sha256").update(JSON.stringify(value)).digest("hex");
35
+ }
36
+ /** 千问桌面端内置数据库的只读 tRPC 会话接口。 */
37
+ class QwenworkSessionHistoryProvider {
38
+ mode = "all";
39
+ scope;
40
+ limitation = "读取千问桌面端可列出的任务及其 sub-chat;每个会话最多读取 20 页消息。";
41
+ unavailableReason;
42
+ query;
43
+ cursors = new Map();
44
+ constructor(options) {
45
+ this.scope = options.scope;
46
+ this.unavailableReason = options.unavailableReason;
47
+ this.query = options.query;
48
+ }
49
+ async listSessions(query) {
50
+ if (!this.available())
51
+ return { supported: false, reason: this.unavailableReason() };
52
+ const cursor = this.resolveCursor(query.cursor, "list");
53
+ if (!cursor)
54
+ return { supported: false, reason: "千问会话目录游标无效或已过期,请重新列举" };
55
+ try {
56
+ const [active, archived, deleted] = await Promise.all([
57
+ this.query("chats.list", {}), this.query("chats.listArchived", {}), this.query("chats.listDeleted", {}),
58
+ ]);
59
+ const parsedLists = [rows(active), rows(archived), rows(deleted)];
60
+ if (parsedLists.some(result => result.malformed && result.rows.length === 0))
61
+ return { supported: false, reason: "千问会话目录返回了无法识别的结构" };
62
+ const combined = new Map();
63
+ for (const chat of parsedLists.flatMap(result => result.rows))
64
+ combined.set(chat.id, chat);
65
+ const all = [...combined.values()].sort((a, b) => (asTime(b.updatedAt) ?? "").localeCompare(asTime(a.updatedAt) ?? ""));
66
+ const dataFingerprint = fingerprint(all);
67
+ if (query.cursor && cursor.fingerprint !== dataFingerprint)
68
+ return { supported: false, reason: "千问会话目录在分页期间发生变化,请重新列举" };
69
+ const capReached = all.length > MAX_SESSIONS;
70
+ const limited = all.slice(0, MAX_SESSIONS);
71
+ const limit = Math.max(1, Math.min(100, Math.floor(query.limit) || 50));
72
+ const page = limited.slice(cursor.offset, cursor.offset + limit);
73
+ const nextOffset = cursor.offset + page.length;
74
+ const nextCursor = nextOffset < limited.length ? this.createCursor({ kind: "list", offset: nextOffset, fingerprint: dataFingerprint }) : undefined;
75
+ const missingReasons = [];
76
+ if (parsedLists.some(result => result.malformed))
77
+ missingReasons.push("千问会话目录含有无法识别的条目");
78
+ if (capReached)
79
+ missingReasons.push(`千问会话超过 ${MAX_SESSIONS} 项读取上限`);
80
+ if (page.some(chat => !asTime(chat.updatedAt)))
81
+ missingReasons.push("部分会话缺少有效更新时间,无法判断是否属于今天");
82
+ return {
83
+ supported: true,
84
+ sessions: page.map(sessionFromChat),
85
+ ...(nextCursor ? { nextCursor } : {}),
86
+ complete: !capReached && missingReasons.length === 0,
87
+ missingReasons,
88
+ readAt: new Date().toISOString(),
89
+ };
90
+ }
91
+ catch {
92
+ return { supported: false, reason: "千问会话目录只读查询失败" };
93
+ }
94
+ }
95
+ async readSession(query) {
96
+ if (!this.available())
97
+ return { supported: false, reason: this.unavailableReason() };
98
+ const since = query.since === undefined ? undefined : asTime(query.since);
99
+ if (query.since !== undefined && !since)
100
+ return { supported: false, reason: "千问 since 时间格式无效" };
101
+ const cursor = this.resolveCursor(query.cursor, "read", query.sessionId, since);
102
+ if (!cursor)
103
+ return { supported: false, reason: "千问消息游标无效或已过期,请重新读取会话" };
104
+ try {
105
+ const rawChat = await this.query("chats.get", { id: query.sessionId });
106
+ const chat = object(rawChat);
107
+ if (!chat || chat.id !== query.sessionId)
108
+ return { supported: false, reason: "千问会话不存在或已不可读取" };
109
+ const parsedChildren = subChats(chat);
110
+ const children = parsedChildren.rows;
111
+ const missingReasons = [];
112
+ if (parsedChildren.malformed)
113
+ missingReasons.push("千问 sub-chat 目录缺失或含有无法识别的条目");
114
+ const turns = [];
115
+ const fingerprintMessages = [];
116
+ for (const child of children) {
117
+ let beforeSequence;
118
+ let pageCount = 0;
119
+ let moreBefore = false;
120
+ while (pageCount < MAX_MESSAGE_PAGES) {
121
+ const input = { subChatId: child.id, limit: MESSAGE_PAGE_SIZE, ...(beforeSequence === undefined ? {} : { beforeSequence }) };
122
+ const result = object(await this.query("chats.listBySubChat", input));
123
+ const messages = Array.isArray(result?.messages) ? result.messages : undefined;
124
+ if (!messages) {
125
+ missingReasons.push(`sub-chat ${child.id} 消息列表格式无效`);
126
+ fingerprintMessages.push({ subChatId: child.id, malformed: true, response: result });
127
+ break;
128
+ }
129
+ fingerprintMessages.push({ subChatId: child.id, beforeSequence, result });
130
+ for (const rawMessage of messages) {
131
+ const message = object(rawMessage);
132
+ if (!message) {
133
+ missingReasons.push(`sub-chat ${child.id} 含有无法识别的消息`);
134
+ continue;
135
+ }
136
+ if (message.role !== "user" && message.role !== "assistant")
137
+ continue;
138
+ const time = asTime(message.createdAt);
139
+ if (!time)
140
+ missingReasons.push(`消息 ${String(message.id ?? "未知 ID")} 缺少有效创建时间`);
141
+ if (since && time && Date.parse(time) < Date.parse(since))
142
+ continue;
143
+ if (!Array.isArray(message.parts)) {
144
+ missingReasons.push(`消息 ${String(message.id ?? "未知 ID")} 的 parts 格式无效`);
145
+ continue;
146
+ }
147
+ const visibleParts = [];
148
+ let malformedParts = false;
149
+ for (const rawPart of message.parts) {
150
+ const part = object(rawPart);
151
+ if (!part || typeof part.type !== "string") {
152
+ malformedParts = true;
153
+ continue;
154
+ }
155
+ if (part.type === "text") {
156
+ if (typeof part.text !== "string")
157
+ malformedParts = true;
158
+ else
159
+ visibleParts.push(part.text);
160
+ }
161
+ else if (part.type === "data-file") {
162
+ visibleParts.push(`[附件:${typeof part.filename === "string" ? part.filename : "附件"}]`);
163
+ }
164
+ else if (part.type === "artifact") {
165
+ visibleParts.push(`[文件产物:${typeof part.fileName === "string" ? part.fileName : typeof part.mediaType === "string" ? part.mediaType : "产物"}]`);
166
+ }
167
+ else if (part.type.startsWith("tool-") || ["reasoning", "tool-call", "tool-Thinking", "thinking"].includes(part.type)) {
168
+ // 思考过程和工具调用属于执行细节,不作为用户可见正文。
169
+ }
170
+ else {
171
+ malformedParts = true;
172
+ }
173
+ }
174
+ if (malformedParts)
175
+ missingReasons.push(`消息 ${String(message.id ?? "未知 ID")} 含有无法识别的 parts`);
176
+ const text = visibleParts.join("\n").trim();
177
+ if (!text)
178
+ continue;
179
+ turns.push({ role: message.role, text, ...(typeof message.id === "string" ? { id: message.id } : {}), ...(time ? { time } : {}) });
180
+ }
181
+ pageCount++;
182
+ moreBefore = result?.hasMoreBefore === true;
183
+ if (!moreBefore)
184
+ break;
185
+ const oldest = Number(result?.oldestSequence);
186
+ if (!Number.isSafeInteger(oldest) || oldest < 0 || beforeSequence === oldest) {
187
+ missingReasons.push(`sub-chat ${child.id} 消息分页游标无效`);
188
+ break;
189
+ }
190
+ beforeSequence = oldest;
191
+ }
192
+ if (pageCount === MAX_MESSAGE_PAGES && moreBefore)
193
+ missingReasons.push(`sub-chat ${child.id} 超过 ${MAX_MESSAGE_PAGES} 页读取上限`);
194
+ }
195
+ const unique = new Map();
196
+ for (const turn of turns)
197
+ unique.set(turn.id ?? `${turn.role}:${turn.time ?? ""}:${turn.text}`, turn);
198
+ const allTurns = [...unique.values()].sort((a, b) => (a.time ?? "").localeCompare(b.time ?? "") || (a.id ?? "").localeCompare(b.id ?? ""));
199
+ if (allTurns.length > MAX_READ_TURNS)
200
+ missingReasons.push(`千问会话消息超过 ${MAX_READ_TURNS} 条读取上限`);
201
+ const limitedTurns = allTurns.slice(0, MAX_READ_TURNS);
202
+ const dataFingerprint = fingerprint({ chat, messages: fingerprintMessages });
203
+ if (query.cursor && cursor.fingerprint !== dataFingerprint)
204
+ return { supported: false, reason: "千问会话正文在分页期间发生变化,请重新读取会话" };
205
+ const limit = Math.max(1, Math.min(200, Math.floor(query.limit) || 100));
206
+ const pageTurns = limitedTurns.slice(cursor.offset, cursor.offset + limit);
207
+ const nextOffset = cursor.offset + pageTurns.length;
208
+ const nextCursor = nextOffset < limitedTurns.length ? this.createCursor({ kind: "read", offset: nextOffset, fingerprint: dataFingerprint, sessionId: query.sessionId, ...(since ? { since } : {}) }) : undefined;
209
+ return {
210
+ supported: true,
211
+ session: sessionFromChat(chat),
212
+ turns: pageTurns,
213
+ ...(nextCursor ? { nextCursor } : {}),
214
+ complete: missingReasons.length === 0,
215
+ missingReasons: [...new Set(missingReasons)],
216
+ readAt: new Date().toISOString(),
217
+ };
218
+ }
219
+ catch {
220
+ return { supported: false, reason: "千问会话正文只读查询失败" };
221
+ }
222
+ }
223
+ resolveCursor(token, kind, sessionId, since) {
224
+ const now = Date.now();
225
+ for (const [key, value] of this.cursors)
226
+ if (value.expires <= now)
227
+ this.cursors.delete(key);
228
+ if (token === undefined)
229
+ return { kind, offset: 0, fingerprint: "", ...(sessionId ? { sessionId } : {}), ...(since ? { since } : {}), expires: now + 5 * 60_000 };
230
+ const cursor = this.cursors.get(token);
231
+ if (!cursor || cursor.kind !== kind || cursor.sessionId !== sessionId || cursor.since !== since)
232
+ return undefined;
233
+ this.cursors.delete(token);
234
+ return cursor;
235
+ }
236
+ createCursor(cursor) {
237
+ if (this.cursors.size >= 1000)
238
+ this.cursors.delete(this.cursors.keys().next().value);
239
+ const token = `qwen:${(0, node_crypto_1.randomUUID)()}`;
240
+ this.cursors.set(token, { ...cursor, expires: Date.now() + 5 * 60_000 });
241
+ return token;
242
+ }
243
+ available() { return !this.unavailableReason(); }
244
+ }
245
+ exports.QwenworkSessionHistoryProvider = QwenworkSessionHistoryProvider;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-bridge-qwenwork",
3
- "version": "1.0.16",
3
+ "version": "1.0.20",
4
4
  "description": "agent-bridge 的千问办公插件。",
5
5
  "keywords": [
6
6
  "mu-agent-bridge-plugin",
package/plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "id": "qwenwork",
3
- "version": "1.0.16",
3
+ "version": "1.0.20",
4
4
  "type": "agent",
5
5
  "displayName": "千问办公",
6
6
  "entry": "dist/src-ts/plugins/qwenwork/index.js",