opencode-plugin-wecom 0.1.1 → 0.2.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/README.md +21 -7
- package/dist/gui-experimental.cjs +40 -4
- package/dist/index.d.ts +20 -7
- package/dist/index.js +1060 -855
- package/dist/{rpc-D5Bs48Ma.d.ts → rpc-BI3X82Bx.d.ts} +11 -0
- package/dist/{rpc-CDRXKJwO.js → rpc-D5y1uowA.js} +4 -0
- package/dist/rpc.d.ts +1 -1
- package/dist/rpc.js +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as WecomRpc, t as PLUGIN_ID } from "./rpc-
|
|
1
|
+
import { n as WecomRpc, t as PLUGIN_ID } from "./rpc-D5y1uowA.js";
|
|
2
2
|
import { Plugin } from "@opencode/plugin";
|
|
3
3
|
import { createHash, randomUUID } from "node:crypto";
|
|
4
4
|
import { execFile } from "node:child_process";
|
|
@@ -85,9 +85,9 @@ const PRE_SEND_ERRNO = new Set([
|
|
|
85
85
|
]);
|
|
86
86
|
function isPreSendError(err) {
|
|
87
87
|
if (!err || typeof err !== "object") return false;
|
|
88
|
-
const record = err;
|
|
89
|
-
if (typeof record.code === "string" && PRE_SEND_ERRNO.has(record.code)) return true;
|
|
90
|
-
if (record.cause && record.cause !== err) return isPreSendError(record.cause);
|
|
88
|
+
const record$1 = err;
|
|
89
|
+
if (typeof record$1.code === "string" && PRE_SEND_ERRNO.has(record$1.code)) return true;
|
|
90
|
+
if (record$1.cause && record$1.cause !== err) return isPreSendError(record$1.cause);
|
|
91
91
|
return false;
|
|
92
92
|
}
|
|
93
93
|
async function readBoundedText(response, maxBytes) {
|
|
@@ -158,938 +158,1117 @@ function createFetchTransport(fetchImpl = fetch) {
|
|
|
158
158
|
}
|
|
159
159
|
|
|
160
160
|
//#endregion
|
|
161
|
-
//#region src/
|
|
162
|
-
const
|
|
163
|
-
const
|
|
164
|
-
const
|
|
165
|
-
const
|
|
166
|
-
const
|
|
167
|
-
const
|
|
168
|
-
const
|
|
169
|
-
const
|
|
170
|
-
const
|
|
171
|
-
const
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
function
|
|
178
|
-
|
|
179
|
-
const trimmed = value.trim();
|
|
180
|
-
if (!trimmed || trimmed.length > maxLength || hasControlChar(trimmed, { allowWhitespace: true })) throw new WecomError(`INVALID_${field.toUpperCase()}`, true);
|
|
181
|
-
return trimmed;
|
|
182
|
-
}
|
|
183
|
-
function cleanOptionalText(value, field, maxLength = 500) {
|
|
184
|
-
if (value === void 0 || value === null || value === "") return void 0;
|
|
185
|
-
return cleanText(value, field, maxLength);
|
|
186
|
-
}
|
|
187
|
-
function assertSafeId(value, field) {
|
|
188
|
-
const trimmed = value.trim();
|
|
189
|
-
if (!SAFE_ID_RE.test(trimmed)) throw new WecomError(`INVALID_${field.toUpperCase()}`, true);
|
|
190
|
-
return trimmed;
|
|
191
|
-
}
|
|
192
|
-
function normalizeWaitSeconds(value) {
|
|
193
|
-
if (value === void 0) return DEFAULT_WAIT_SECONDS;
|
|
194
|
-
if (!Number.isFinite(value) || value < 0) return 0;
|
|
195
|
-
return Math.min(Math.floor(value), MAX_WAIT_SECONDS$1);
|
|
161
|
+
//#region src/auth/workbuddy.ts
|
|
162
|
+
const WORKBUDDY_ORIGIN = "https://www.workbuddy.cn";
|
|
163
|
+
const WORKBUDDY_PREFIX = "/v2/plugin";
|
|
164
|
+
const WECOM_LOGIN_URL = `${WORKBUDDY_ORIGIN}/login/wecom-auth`;
|
|
165
|
+
const AUTH_FLOW_VERSION = "5.8.2";
|
|
166
|
+
const AUTH_STORAGE_KEY = "wecom/cloud-auth";
|
|
167
|
+
const AUTH_MAX_RESPONSE_BYTES = 1024 * 1024;
|
|
168
|
+
const PENDING_TTL_MS = 3e5;
|
|
169
|
+
const FRESH_BUFFER_MS = 6e4;
|
|
170
|
+
const LOGIN_POLL_INTERVAL_MS = 2e3;
|
|
171
|
+
const MAX_WAIT_SECONDS$1 = 300;
|
|
172
|
+
const USER_AGENT = "opencode-plugin-wecom/0.1.0 (local interoperability client)";
|
|
173
|
+
const TOKEN_STATE_PATH_RE = /^\/v2\/plugin\/auth\/token\?state=[A-Za-z0-9_%.-]+$/;
|
|
174
|
+
const EXCHANGE_PATH_RE = /^\/console\/enterprises\/[A-Za-z0-9_%.-]+\/oneid_openapi\/exchange-wecom-token$/;
|
|
175
|
+
const DAYUAN_DISCOVERY_PATH = "/a2a/cards/self";
|
|
176
|
+
const DAYUAN_TICKET_PATH = "/a2a/credentials/wecom-a2a/tickets";
|
|
177
|
+
function record(value) {
|
|
178
|
+
return value && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
196
179
|
}
|
|
197
|
-
function
|
|
198
|
-
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
180
|
+
function dayuanEndpoint(discovery) {
|
|
181
|
+
const data = record(discovery.data);
|
|
182
|
+
const credentials = discovery.credentials ?? data?.credentials;
|
|
183
|
+
const cards = discovery.cards ?? discovery.agents ?? discovery.items ?? discovery.list ?? discovery.result ?? data?.cards ?? data?.agents ?? data?.items ?? data?.list ?? data?.result;
|
|
184
|
+
if (!Array.isArray(credentials) || !Array.isArray(cards)) throw new WecomError("DAYUAN_NOT_AVAILABLE", true);
|
|
185
|
+
const matches = /* @__PURE__ */ new Set();
|
|
186
|
+
for (const item of cards) {
|
|
187
|
+
const entry = record(item);
|
|
188
|
+
const card = record(entry?.card ?? entry?.agentCard ?? entry?.agent_card) ?? entry;
|
|
189
|
+
const interfaces = card?.supportedInterfaces;
|
|
190
|
+
const advertised = Array.isArray(interfaces) && interfaces.length ? interfaces.map(record).filter((i) => !i?.protocolBinding || i.protocolBinding === "HTTP+JSON").map((i) => i?.url) : [card?.url ?? entry?.url];
|
|
191
|
+
for (const url of advertised) {
|
|
192
|
+
if (typeof url !== "string") continue;
|
|
193
|
+
const base = url.replace(/\/+$/, "");
|
|
194
|
+
if (!/^https:\/\/qyapi\.weixin\.qq\.com\/cgi-bin\/[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)*$/.test(base)) continue;
|
|
195
|
+
if (credentials.some((item$1) => {
|
|
196
|
+
const cred = record(item$1);
|
|
197
|
+
const endpoint$1 = cred?.endpoint;
|
|
198
|
+
if (cred?.id !== "wecom-a2a" || typeof endpoint$1 !== "string") return false;
|
|
199
|
+
const prefix = endpoint$1.replace(/\/+$/, "");
|
|
200
|
+
return base === prefix || prefix.startsWith("https://qyapi.weixin.qq.com/cgi-bin/") && base.startsWith(`${prefix}/`);
|
|
201
|
+
})) matches.add(base);
|
|
202
|
+
}
|
|
210
203
|
}
|
|
204
|
+
const endpoint = matches.values().next().value;
|
|
205
|
+
if (!endpoint || matches.size !== 1) throw new WecomError("DAYUAN_NOT_AVAILABLE", true);
|
|
206
|
+
return endpoint;
|
|
211
207
|
}
|
|
212
|
-
function
|
|
213
|
-
return
|
|
208
|
+
function wecomAuthorizationError(err) {
|
|
209
|
+
return err instanceof WecomError && /^(HTTP_40[13](?:_CODE_\d+)?|(?:HTTP_\d+_CODE|CLOUD_CODE)_1011[01])$/.test(err.code);
|
|
214
210
|
}
|
|
215
|
-
function
|
|
216
|
-
|
|
211
|
+
function formatLoginUrl(rawUrl) {
|
|
212
|
+
const parsed = new URL(rawUrl);
|
|
213
|
+
parsed.searchParams.set("version", AUTH_FLOW_VERSION);
|
|
214
|
+
parsed.searchParams.set("force_login_type", "wecom");
|
|
215
|
+
parsed.hash = "";
|
|
216
|
+
return parsed.toString();
|
|
217
217
|
}
|
|
218
|
-
function
|
|
219
|
-
if (
|
|
218
|
+
function assertSecret(value) {
|
|
219
|
+
if (typeof value !== "string" || !value || hasControlOrSpaceChar(value)) throw new WecomError("INVALID_CREDENTIAL", true);
|
|
220
220
|
return value;
|
|
221
221
|
}
|
|
222
|
-
function
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
const rec = asRecord(container);
|
|
226
|
-
if (!rec) return;
|
|
227
|
-
if (Array.isArray(rec.parts)) for (const item of rec.parts) {
|
|
228
|
-
const part = asRecord(item);
|
|
229
|
-
if (part) parts.push(part);
|
|
230
|
-
}
|
|
231
|
-
};
|
|
232
|
-
if (Array.isArray(payload.artifacts)) for (const artifact of payload.artifacts) pushFrom(artifact);
|
|
233
|
-
const status = asRecord(payload.status);
|
|
234
|
-
if (status) pushFrom(status.message);
|
|
235
|
-
pushFrom(payload.message);
|
|
236
|
-
return parts;
|
|
237
|
-
}
|
|
238
|
-
function hasApprovalMarker(value, depth = 0) {
|
|
239
|
-
if (depth > 5 || !value || typeof value !== "object") return false;
|
|
240
|
-
if (Array.isArray(value)) return value.some((item) => hasApprovalMarker(item, depth + 1));
|
|
241
|
-
const rec = value;
|
|
242
|
-
if (rec.wecom_part_type === "approval" || rec.part_type === "approval") return true;
|
|
243
|
-
if (Array.isArray(rec.token_id_list) && rec.token_id_list.length > 0) return true;
|
|
244
|
-
if (typeof rec.approval_id === "string" && rec.approval_id.length > 0) return true;
|
|
245
|
-
for (const child of Object.values(rec)) if (child && typeof child === "object" && hasApprovalMarker(child, depth + 1)) return true;
|
|
246
|
-
return false;
|
|
247
|
-
}
|
|
248
|
-
function extractSummaryText(parts) {
|
|
249
|
-
const lines = [];
|
|
250
|
-
for (const part of parts) if (typeof part.text === "string" && part.text.trim()) lines.push(part.text.trim());
|
|
251
|
-
else if (part.data && typeof part.data === "object") {
|
|
252
|
-
const data = part.data;
|
|
253
|
-
if (typeof data.text === "string" && data.text.trim()) lines.push(data.text.trim());
|
|
254
|
-
else if (typeof data.title === "string" && data.title.trim()) lines.push(data.title.trim());
|
|
255
|
-
}
|
|
256
|
-
return lines.join("\n\n").trim();
|
|
222
|
+
function parseDeadline(value) {
|
|
223
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
|
|
224
|
+
return 0;
|
|
257
225
|
}
|
|
258
|
-
function
|
|
259
|
-
if (
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
}
|
|
269
|
-
};
|
|
270
|
-
}
|
|
271
|
-
if (input.action === "read_chat") {
|
|
272
|
-
const chatName$1 = cleanText(input.chat_name, "chat_name", 300);
|
|
273
|
-
const question = cleanText(input.question, "question", 1500);
|
|
274
|
-
const timeRange$1 = cleanOptionalText(input.time_range, "time_range", 200);
|
|
275
|
-
return {
|
|
276
|
-
prompt: `只读查询:请阅读企业微信群聊「${chatName$1}」${timeRange$1 ? `(时间范围:${timeRange$1})` : ""},回答以下问题并给出要点摘要:${question}。不要发送任何消息或执行写操作。`,
|
|
277
|
-
canonical: {
|
|
278
|
-
action: input.action,
|
|
279
|
-
chat_name: chatName$1,
|
|
280
|
-
question,
|
|
281
|
-
time_range: timeRange$1 ?? null
|
|
282
|
-
}
|
|
283
|
-
};
|
|
284
|
-
}
|
|
285
|
-
const query = cleanText(input.query, "query", 1e3);
|
|
286
|
-
const chatName = cleanOptionalText(input.chat_name, "chat_name", 300);
|
|
287
|
-
const timeRange = cleanOptionalText(input.time_range, "time_range", 200);
|
|
288
|
-
const scope = [chatName ? `限定群聊「${chatName}」` : null, timeRange ? `时间范围:${timeRange}` : null].filter(Boolean).join(",");
|
|
226
|
+
function normalizeAuth(value, nowMs) {
|
|
227
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new WecomError("INVALID_AUTH_RESPONSE");
|
|
228
|
+
const raw = { ...value };
|
|
229
|
+
const accessToken = assertSecret(raw.accessToken);
|
|
230
|
+
let refreshToken;
|
|
231
|
+
if (raw.refreshToken !== void 0 && raw.refreshToken !== null && raw.refreshToken !== "") refreshToken = assertSecret(raw.refreshToken);
|
|
232
|
+
const expiresIn = parseDeadline(raw.expiresIn);
|
|
233
|
+
const expiresAt = parseDeadline(raw.expiresAt) || (expiresIn ? nowMs + expiresIn * 1e3 : 0);
|
|
234
|
+
const refreshExpiresIn = parseDeadline(raw.refreshExpiresIn);
|
|
235
|
+
const refreshExpiresAt = parseDeadline(raw.refreshExpiresAt) || (refreshExpiresIn ? nowMs + refreshExpiresIn * 1e3 : 0);
|
|
289
236
|
return {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
time_range: timeRange ?? null
|
|
296
|
-
}
|
|
237
|
+
...raw,
|
|
238
|
+
accessToken,
|
|
239
|
+
...refreshToken ? { refreshToken } : {},
|
|
240
|
+
expiresAt,
|
|
241
|
+
refreshExpiresAt
|
|
297
242
|
};
|
|
298
243
|
}
|
|
299
|
-
function
|
|
300
|
-
|
|
244
|
+
function accountIdentity(account) {
|
|
245
|
+
if (!account || typeof account !== "object" || Array.isArray(account)) throw new WecomError("INVALID_ACCOUNT_RESPONSE");
|
|
246
|
+
const record$1 = account;
|
|
247
|
+
if (typeof record$1.uid !== "string" || !record$1.uid) throw new WecomError("INVALID_ACCOUNT_RESPONSE");
|
|
248
|
+
const enterpriseId = typeof record$1.enterpriseId === "string" ? record$1.enterpriseId : void 0;
|
|
249
|
+
return [record$1.uid, enterpriseId];
|
|
301
250
|
}
|
|
302
|
-
function
|
|
303
|
-
|
|
304
|
-
const safeId = assertSafeId(route.taskId, "task_id");
|
|
305
|
-
return `${DAYUAN_A2A_ORIGIN}${DAYUAN_A2A_BASE_PATH}/tasks/${encodeURIComponent(safeId)}?historyLength=0`;
|
|
251
|
+
function isFresh(expiryMs, nowMs) {
|
|
252
|
+
return parseDeadline(expiryMs) > nowMs + FRESH_BUFFER_MS;
|
|
306
253
|
}
|
|
307
|
-
|
|
308
|
-
|
|
254
|
+
function dayuanIdentity(enterprise, uid, wecomIdentity) {
|
|
255
|
+
return createHash("sha256").update(JSON.stringify([
|
|
256
|
+
enterprise,
|
|
257
|
+
uid,
|
|
258
|
+
wecomIdentity
|
|
259
|
+
])).digest("hex");
|
|
260
|
+
}
|
|
261
|
+
function isAllowedEndpoint(method, path) {
|
|
262
|
+
if (method === "POST" && (path === `${WORKBUDDY_PREFIX}/auth/state?platform=workbuddy` || path === `${WORKBUDDY_PREFIX}/auth/token/refresh`)) return true;
|
|
263
|
+
if (method === "GET" && (path === `${WORKBUDDY_PREFIX}/account` || TOKEN_STATE_PATH_RE.test(path))) return true;
|
|
264
|
+
if (method === "POST" && EXCHANGE_PATH_RE.test(path)) return true;
|
|
265
|
+
return false;
|
|
266
|
+
}
|
|
267
|
+
var WorkBuddyAuth = class {
|
|
309
268
|
storage;
|
|
310
269
|
transport;
|
|
311
270
|
clock;
|
|
271
|
+
onAuthChange;
|
|
312
272
|
lock = new AsyncKeyLock();
|
|
273
|
+
dayuan;
|
|
313
274
|
constructor(options) {
|
|
314
|
-
this.auth = options.auth;
|
|
315
275
|
this.storage = options.storage;
|
|
316
276
|
this.transport = options.transport ?? createFetchTransport();
|
|
317
277
|
this.clock = options.clock ?? systemClock;
|
|
278
|
+
this.onAuthChange = options.onAuthChange;
|
|
318
279
|
}
|
|
319
|
-
|
|
320
|
-
|
|
280
|
+
async load() {
|
|
281
|
+
const stored = await this.storage.get(AUTH_STORAGE_KEY);
|
|
282
|
+
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return { phase: "logged_out" };
|
|
283
|
+
const doc = stored;
|
|
284
|
+
return {
|
|
285
|
+
...doc,
|
|
286
|
+
phase: doc.phase ?? "logged_out"
|
|
287
|
+
};
|
|
321
288
|
}
|
|
322
|
-
|
|
323
|
-
|
|
289
|
+
async save(doc) {
|
|
290
|
+
await this.storage.set(AUTH_STORAGE_KEY, doc);
|
|
291
|
+
if (this.onAuthChange) await Promise.resolve(this.onAuthChange(this.toStatus(doc))).catch(() => {});
|
|
324
292
|
}
|
|
325
|
-
|
|
326
|
-
const
|
|
327
|
-
const
|
|
328
|
-
|
|
329
|
-
const taskId = assertSafeId(rawId, "task_id");
|
|
330
|
-
const contextId = typeof taskObj.contextId === "string" && taskObj.contextId ? taskObj.contextId : void 0;
|
|
331
|
-
const state = normalizeState(asRecord(taskObj.status)?.state ?? taskObj.state);
|
|
332
|
-
const parts = collectParts(taskObj);
|
|
333
|
-
const summary = extractSummaryText(parts);
|
|
334
|
-
let interactionKind = "none";
|
|
335
|
-
let canReplyInText = false;
|
|
336
|
-
let humanActionRequired = false;
|
|
337
|
-
let guidance;
|
|
338
|
-
if (state === "input_required") if (hasApprovalMarker(parts) || hasApprovalMarker(taskObj)) {
|
|
339
|
-
interactionKind = "approval_required";
|
|
340
|
-
canReplyInText = false;
|
|
341
|
-
humanActionRequired = true;
|
|
342
|
-
guidance = "检测到企业微信敏感审批卡片(approval),插件已禁止自动代批。请在手机企业微信中手动确认审批后再重新查询。";
|
|
343
|
-
} else if (summary.length > 0) {
|
|
344
|
-
interactionKind = "text_clarification";
|
|
345
|
-
canReplyInText = true;
|
|
346
|
-
guidance = "大圆需要进一步澄清问题,请调用 wecom_read_reply 回复澄清文本。";
|
|
347
|
-
} else {
|
|
348
|
-
interactionKind = "unsupported";
|
|
349
|
-
canReplyInText = false;
|
|
350
|
-
humanActionRequired = true;
|
|
351
|
-
guidance = "任务处于 input_required 状态但未包含可回复的文本澄清内容,请在企业微信客户端查看。";
|
|
352
|
-
}
|
|
293
|
+
toStatus(doc) {
|
|
294
|
+
const auth = doc.auth;
|
|
295
|
+
const now = this.clock.now();
|
|
296
|
+
const ticketReady = Boolean(this.dayuan && doc.phase === "ready" && doc.account?.enterpriseId && doc.wecom && this.dayuan.identity === dayuanIdentity(doc.account.enterpriseId, doc.account.uid, doc.wecom.identity) && isFresh(this.dayuan.expires_at_ms, now));
|
|
353
297
|
return {
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
human_action_required: humanActionRequired,
|
|
365
|
-
...guidance ? { guidance } : {},
|
|
366
|
-
from_cache: meta.from_cache,
|
|
367
|
-
updated_at_ms: this.clock.now()
|
|
298
|
+
phase: doc.phase,
|
|
299
|
+
desktop_required: false,
|
|
300
|
+
cloud_dependency: WORKBUDDY_ORIGIN,
|
|
301
|
+
account_expires_at_ms: auth?.expiresAt || null,
|
|
302
|
+
refresh_expires_at_ms: auth?.refreshExpiresAt || null,
|
|
303
|
+
refresh_credential_present: Boolean(auth?.refreshToken),
|
|
304
|
+
wecom_expires_at_ms: doc.wecom?.expires_at_ms || null,
|
|
305
|
+
wecom_configured: Boolean(doc.wecom?.access_token && doc.wecom.expires_at_ms > now),
|
|
306
|
+
...this.dayuan ? { dayuan_ticket_ready: ticketReady } : {},
|
|
307
|
+
authorization_verified: ticketReady
|
|
368
308
|
};
|
|
369
309
|
}
|
|
370
|
-
async
|
|
371
|
-
const
|
|
372
|
-
|
|
373
|
-
const
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
if (options.method === "POST") {
|
|
380
|
-
headers["Content-Type"] = "application/json";
|
|
381
|
-
serialized = JSON.stringify(options.body ?? {});
|
|
382
|
-
}
|
|
383
|
-
const response = await this.transport({
|
|
384
|
-
method: options.method,
|
|
385
|
-
url,
|
|
386
|
-
headers,
|
|
387
|
-
body: serialized,
|
|
388
|
-
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
389
|
-
maxBytes: A2A_MAX_RESPONSE_BYTES,
|
|
390
|
-
signal: options.signal
|
|
391
|
-
});
|
|
392
|
-
let parsed = {};
|
|
393
|
-
if (response.body.trim()) try {
|
|
394
|
-
const decoded = JSON.parse(response.body);
|
|
395
|
-
if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new WecomError("INVALID_A2A_JSON");
|
|
396
|
-
parsed = decoded;
|
|
397
|
-
} catch (err) {
|
|
398
|
-
if (err instanceof WecomError) throw err;
|
|
399
|
-
throw new WecomError("INVALID_A2A_JSON");
|
|
400
|
-
}
|
|
401
|
-
const errcode = typeof parsed.errcode === "number" ? parsed.errcode : 0;
|
|
402
|
-
const isAuthFailure = response.status === 401 || TOKEN_EXPIRED_ERRCODES.has(errcode);
|
|
403
|
-
return {
|
|
404
|
-
status: response.status,
|
|
405
|
-
errcode,
|
|
406
|
-
parsed,
|
|
407
|
-
isAuthFailure
|
|
408
|
-
};
|
|
310
|
+
async requestCloud(options) {
|
|
311
|
+
const { method, path, auth, refreshToken, beforeSend, deadlineMonoMs, signal } = options;
|
|
312
|
+
if (!isAllowedEndpoint(method, path)) throw new WecomError("ENDPOINT_NOT_ALLOWED", true);
|
|
313
|
+
const headers = {
|
|
314
|
+
Accept: "application/json",
|
|
315
|
+
"Content-Type": "application/json",
|
|
316
|
+
"X-Domain": "www.workbuddy.cn",
|
|
317
|
+
"X-Product": "SaaS",
|
|
318
|
+
"User-Agent": USER_AGENT
|
|
409
319
|
};
|
|
410
|
-
|
|
411
|
-
if (
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
signal: options.signal
|
|
415
|
-
});
|
|
416
|
-
attempt = await executeOnce(credential.access_token);
|
|
320
|
+
if (auth) headers.Authorization = `Bearer ${assertSecret(auth.accessToken)}`;
|
|
321
|
+
if (refreshToken) {
|
|
322
|
+
headers["X-Refresh-Token"] = assertSecret(refreshToken);
|
|
323
|
+
headers["X-Auth-Refresh-Source"] = "plugin";
|
|
417
324
|
}
|
|
418
|
-
|
|
419
|
-
if (
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
325
|
+
let timeoutMs = 25e3;
|
|
326
|
+
if (deadlineMonoMs !== void 0) {
|
|
327
|
+
const remaining = deadlineMonoMs - this.clock.monotonic();
|
|
328
|
+
if (remaining <= 0) throw new WecomError("WAIT_TIMEOUT");
|
|
329
|
+
timeoutMs = Math.min(timeoutMs, remaining);
|
|
330
|
+
}
|
|
331
|
+
if (beforeSend) await beforeSend();
|
|
332
|
+
const response = await this.transport({
|
|
333
|
+
method,
|
|
334
|
+
url: `${WORKBUDDY_ORIGIN}${path}`,
|
|
335
|
+
headers,
|
|
336
|
+
body: method === "POST" ? "{}" : void 0,
|
|
337
|
+
timeoutMs,
|
|
338
|
+
maxBytes: AUTH_MAX_RESPONSE_BYTES,
|
|
339
|
+
signal
|
|
340
|
+
});
|
|
341
|
+
if (response.status >= 300 && response.status < 400) throw new WecomError("REDIRECT_REJECTED", true);
|
|
342
|
+
let parsed;
|
|
343
|
+
try {
|
|
344
|
+
parsed = JSON.parse(response.body);
|
|
345
|
+
} catch {
|
|
346
|
+
if (response.status >= 400) throw new WecomError(`HTTP_${response.status}`, response.status < 500);
|
|
347
|
+
throw new WecomError("INVALID_RESPONSE");
|
|
348
|
+
}
|
|
349
|
+
const bodyRecord = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
350
|
+
if (response.status >= 400) {
|
|
351
|
+
const code$1 = bodyRecord?.code;
|
|
352
|
+
if (code$1 === 11217 || code$1 === 12151) throw new WecomError(`PENDING_${code$1}`);
|
|
353
|
+
const suffix = typeof code$1 === "number" && Number.isInteger(code$1) ? `_CODE_${code$1}` : "";
|
|
354
|
+
throw new WecomError(`HTTP_${response.status}${suffix}`, response.status < 500);
|
|
355
|
+
}
|
|
356
|
+
if (!bodyRecord) throw new WecomError("INVALID_RESPONSE");
|
|
357
|
+
const code = bodyRecord.code;
|
|
358
|
+
if (code === 11217 || code === 12151) throw new WecomError(`PENDING_${code}`);
|
|
359
|
+
if (code !== 0) throw new WecomError(typeof code === "number" && Number.isInteger(code) ? `CLOUD_CODE_${code}` : "INVALID_RESPONSE");
|
|
360
|
+
const data = bodyRecord.data;
|
|
361
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) throw new WecomError("INVALID_RESPONSE");
|
|
362
|
+
return data;
|
|
426
363
|
}
|
|
427
|
-
async
|
|
428
|
-
|
|
364
|
+
async status() {
|
|
365
|
+
return this.toStatus(await this.load());
|
|
429
366
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
367
|
+
wecomLoginInfo() {
|
|
368
|
+
return {
|
|
369
|
+
authorization_url: WECOM_LOGIN_URL,
|
|
370
|
+
instruction: "在完成账号登录的同一浏览器中,授权同一企业微信账号,完成后执行 wecom_renew。"
|
|
371
|
+
};
|
|
434
372
|
}
|
|
435
|
-
async
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
method: "GET",
|
|
452
|
-
route: {
|
|
453
|
-
kind: "task",
|
|
454
|
-
taskId: current.task_id
|
|
455
|
-
},
|
|
373
|
+
async start(options) {
|
|
374
|
+
return this.lock.run("auth", async () => {
|
|
375
|
+
const doc = await this.load();
|
|
376
|
+
if (doc.phase === "ready") throw new WecomError("ALREADY_LOGGED_IN_USE_RENEW", true);
|
|
377
|
+
if (doc.phase === "pending_token" && doc.pending && this.clock.now() - doc.pending.created_at_ms < PENDING_TTL_MS) {
|
|
378
|
+
const refreshedUrl = formatLoginUrl(doc.pending.url);
|
|
379
|
+
doc.pending.url = refreshedUrl;
|
|
380
|
+
await this.save(doc);
|
|
381
|
+
return {
|
|
382
|
+
phase: "pending_token",
|
|
383
|
+
authorization_url: refreshedUrl
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
const data = await this.requestCloud({
|
|
387
|
+
method: "POST",
|
|
388
|
+
path: `${WORKBUDDY_PREFIX}/auth/state?platform=workbuddy`,
|
|
456
389
|
signal: options?.signal
|
|
457
390
|
});
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
identity,
|
|
467
|
-
action: current.action,
|
|
468
|
-
request_id: current.request_id,
|
|
469
|
-
result: current
|
|
470
|
-
});
|
|
471
|
-
}
|
|
472
|
-
return current;
|
|
473
|
-
}
|
|
474
|
-
async start(input, options) {
|
|
475
|
-
const { prompt, canonical } = buildReadOnlyPrompt(input);
|
|
476
|
-
const requestId = input.request_id ? assertSafeId(input.request_id, "request_id") : randomUUID();
|
|
477
|
-
const waitSeconds = normalizeWaitSeconds(input.wait_seconds);
|
|
478
|
-
const fingerprint = fingerprintOf(canonical);
|
|
479
|
-
const credential = await this.auth.ensureWecom({ signal: options?.signal });
|
|
480
|
-
const receiptKey = this.receiptKey(credential.identity, requestId);
|
|
481
|
-
return this.lock.run(`receipt:${receiptKey}`, async () => {
|
|
482
|
-
const existing = asRecord(await this.storage.get(receiptKey));
|
|
483
|
-
if (existing) {
|
|
484
|
-
if (existing.fingerprint !== fingerprint) throw new WecomError("REQUEST_ID_CONFLICT", true);
|
|
485
|
-
if (existing.status === "submit_unknown") throw new WecomError("SUBMIT_OUTCOME_UNKNOWN", true);
|
|
486
|
-
if (existing.result && isSettledForWait(existing.result.state)) return {
|
|
487
|
-
...existing.result,
|
|
488
|
-
from_cache: true
|
|
489
|
-
};
|
|
490
|
-
if (existing.task_id) {
|
|
491
|
-
const polled = await this.getResult({
|
|
492
|
-
task_id: existing.task_id,
|
|
493
|
-
wait_seconds: waitSeconds
|
|
494
|
-
}, options);
|
|
495
|
-
existing.status = polled.state;
|
|
496
|
-
existing.result = polled;
|
|
497
|
-
existing.updated_at_ms = this.clock.now();
|
|
498
|
-
await this.storage.set(receiptKey, existing);
|
|
499
|
-
return polled;
|
|
500
|
-
}
|
|
391
|
+
const state = data.state;
|
|
392
|
+
const authUrl = data.authUrl;
|
|
393
|
+
let parsed;
|
|
394
|
+
try {
|
|
395
|
+
if (typeof authUrl !== "string") throw new Error("not string");
|
|
396
|
+
parsed = new URL(authUrl);
|
|
397
|
+
} catch {
|
|
398
|
+
throw new WecomError("UNEXPECTED_LOGIN_URL");
|
|
501
399
|
}
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
400
|
+
if (parsed.origin !== WORKBUDDY_ORIGIN || parsed.pathname !== "/login" || parsed.hash) throw new WecomError("UNEXPECTED_LOGIN_URL");
|
|
401
|
+
if (typeof state !== "string" || !state || parsed.searchParams.get("state") !== state) throw new WecomError("INVALID_LOGIN_STATE");
|
|
402
|
+
const url = formatLoginUrl(authUrl);
|
|
403
|
+
const next = {
|
|
404
|
+
...doc,
|
|
405
|
+
phase: "pending_token",
|
|
406
|
+
pending: {
|
|
407
|
+
state,
|
|
408
|
+
url,
|
|
409
|
+
created_at_ms: this.clock.now()
|
|
410
|
+
}
|
|
511
411
|
};
|
|
512
|
-
await this.
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
412
|
+
await this.save(next);
|
|
413
|
+
return {
|
|
414
|
+
phase: "pending_token",
|
|
415
|
+
authorization_url: url
|
|
416
|
+
};
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
async fetchAccount(doc, deadlineMonoMs, signal) {
|
|
420
|
+
if (!doc.auth) throw new WecomError("LOGIN_REQUIRED", true);
|
|
421
|
+
const account = await this.requestCloud({
|
|
422
|
+
method: "GET",
|
|
423
|
+
path: `${WORKBUDDY_PREFIX}/account`,
|
|
424
|
+
auth: doc.auth,
|
|
425
|
+
deadlineMonoMs,
|
|
426
|
+
signal
|
|
427
|
+
});
|
|
428
|
+
const nextId = accountIdentity(account);
|
|
429
|
+
if (doc.account) {
|
|
430
|
+
const prevId = accountIdentity(doc.account);
|
|
431
|
+
if (prevId[0] !== nextId[0] || prevId[1] !== nextId[1]) {
|
|
432
|
+
doc.phase = "account_changed";
|
|
433
|
+
await this.save(doc);
|
|
434
|
+
throw new WecomError("ACCOUNT_CHANGED_USE_SEPARATE_STATE", true);
|
|
534
435
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
436
|
+
}
|
|
437
|
+
doc.account = account;
|
|
438
|
+
doc.phase = "ready";
|
|
439
|
+
delete doc.pending;
|
|
440
|
+
await this.save(doc);
|
|
441
|
+
}
|
|
442
|
+
async finish(options) {
|
|
443
|
+
return this.lock.run("auth", async () => {
|
|
444
|
+
const doc = await this.load();
|
|
445
|
+
if (doc.phase === "pending_token") {
|
|
446
|
+
if (!doc.pending?.state) throw new WecomError("LOGIN_REQUIRED", true);
|
|
447
|
+
try {
|
|
448
|
+
doc.auth = normalizeAuth(await this.requestCloud({
|
|
449
|
+
method: "GET",
|
|
450
|
+
path: `${WORKBUDDY_PREFIX}/auth/token?state=${encodeURIComponent(doc.pending.state)}`,
|
|
451
|
+
deadlineMonoMs: options?.deadlineMonoMs,
|
|
452
|
+
signal: options?.signal
|
|
453
|
+
}), this.clock.now());
|
|
454
|
+
doc.phase = "pending_account";
|
|
455
|
+
await this.save(doc);
|
|
456
|
+
} catch (err) {
|
|
457
|
+
if (err instanceof WecomError && err.code.startsWith("PENDING_")) return { phase: "pending_token" };
|
|
458
|
+
throw err;
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
if (doc.phase === "pending_account") try {
|
|
462
|
+
await this.fetchAccount(doc, options?.deadlineMonoMs, options?.signal);
|
|
463
|
+
} catch (err) {
|
|
464
|
+
if (err instanceof WecomError && err.code.startsWith("PENDING_")) return { phase: "pending_account" };
|
|
465
|
+
throw err;
|
|
466
|
+
}
|
|
467
|
+
if (doc.phase !== "ready") throw new WecomError("LOGIN_REQUIRED", true);
|
|
468
|
+
return {
|
|
469
|
+
phase: "ready",
|
|
470
|
+
desktop_required: false,
|
|
471
|
+
cloud_dependency: WORKBUDDY_ORIGIN
|
|
557
472
|
};
|
|
558
|
-
await this.storage.set(receiptKey, finalized);
|
|
559
|
-
return result;
|
|
560
473
|
});
|
|
561
474
|
}
|
|
562
|
-
async
|
|
563
|
-
const
|
|
564
|
-
const
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
from_cache: true
|
|
569
|
-
};
|
|
570
|
-
const { payload, identity } = await this.requestA2A({
|
|
571
|
-
method: "GET",
|
|
572
|
-
route: {
|
|
573
|
-
kind: "task",
|
|
574
|
-
taskId
|
|
575
|
-
},
|
|
576
|
-
signal: options?.signal
|
|
577
|
-
});
|
|
578
|
-
let result = this.parseTaskPayload(payload, {
|
|
579
|
-
request_id: existing?.request_id,
|
|
580
|
-
action: existing?.action,
|
|
581
|
-
from_cache: false
|
|
475
|
+
async waitForLogin(options) {
|
|
476
|
+
const boundedSeconds = Math.min(Math.max(Math.floor(options.waitSeconds), 0), MAX_WAIT_SECONDS$1);
|
|
477
|
+
const deadlineMonoMs = this.clock.monotonic() + boundedSeconds * 1e3;
|
|
478
|
+
let result = await this.finish({
|
|
479
|
+
signal: options.signal,
|
|
480
|
+
deadlineMonoMs
|
|
582
481
|
});
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
482
|
+
while (result.phase !== "ready" && this.clock.monotonic() < deadlineMonoMs) {
|
|
483
|
+
const remaining = deadlineMonoMs - this.clock.monotonic();
|
|
484
|
+
await this.clock.sleep(Math.min(LOGIN_POLL_INTERVAL_MS, remaining), options.signal);
|
|
485
|
+
if (this.clock.monotonic() >= deadlineMonoMs) break;
|
|
486
|
+
result = await this.finish({
|
|
487
|
+
signal: options.signal,
|
|
488
|
+
deadlineMonoMs
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
if (result.phase === "ready" && options.exchangeWecom !== false) await this.ensureWecom({
|
|
492
|
+
signal: options.signal,
|
|
493
|
+
deadlineMonoMs
|
|
590
494
|
});
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
495
|
+
return this.status();
|
|
496
|
+
}
|
|
497
|
+
async refreshAccount(doc, deadlineMonoMs, signal) {
|
|
498
|
+
const refreshToken = doc.auth?.refreshToken;
|
|
499
|
+
if (!refreshToken) {
|
|
500
|
+
doc.phase = "login_required";
|
|
501
|
+
await this.save(doc);
|
|
502
|
+
throw new WecomError("LOGIN_REQUIRED_NO_REFRESH_TOKEN", true);
|
|
503
|
+
}
|
|
504
|
+
const refreshExp = parseDeadline(doc.auth?.refreshExpiresAt);
|
|
505
|
+
if (refreshExp && refreshExp <= this.clock.now()) {
|
|
506
|
+
doc.phase = "login_required";
|
|
507
|
+
await this.save(doc);
|
|
508
|
+
throw new WecomError("LOGIN_REQUIRED_REFRESH_EXPIRED", true);
|
|
509
|
+
}
|
|
510
|
+
const previousPhase = doc.phase;
|
|
511
|
+
let refreshed;
|
|
512
|
+
try {
|
|
513
|
+
refreshed = await this.requestCloud({
|
|
514
|
+
method: "POST",
|
|
515
|
+
path: `${WORKBUDDY_PREFIX}/auth/token/refresh`,
|
|
516
|
+
auth: doc.auth,
|
|
517
|
+
refreshToken,
|
|
518
|
+
deadlineMonoMs,
|
|
519
|
+
signal,
|
|
520
|
+
beforeSend: async () => {
|
|
521
|
+
doc.phase = "refresh_unknown";
|
|
522
|
+
await this.save(doc);
|
|
523
|
+
}
|
|
524
|
+
});
|
|
525
|
+
} catch (err) {
|
|
526
|
+
if (err instanceof WecomError) {
|
|
527
|
+
if (err.code.startsWith("HTTP_401") || err.code.startsWith("HTTP_403")) {
|
|
528
|
+
doc.phase = "login_required";
|
|
529
|
+
await this.save(doc);
|
|
530
|
+
} else if (err.code === "TRANSPORT_NOT_SENT" && doc.phase === "refresh_unknown") {
|
|
531
|
+
doc.phase = previousPhase;
|
|
532
|
+
await this.save(doc);
|
|
533
|
+
}
|
|
600
534
|
}
|
|
535
|
+
throw err;
|
|
601
536
|
}
|
|
602
|
-
|
|
537
|
+
doc.auth = normalizeAuth(refreshed, this.clock.now());
|
|
538
|
+
doc.phase = "pending_account";
|
|
539
|
+
await this.save(doc);
|
|
540
|
+
await this.fetchAccount(doc, deadlineMonoMs, signal);
|
|
603
541
|
}
|
|
604
|
-
|
|
605
|
-
const
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
542
|
+
cachedWecom(doc) {
|
|
543
|
+
const nowMs = this.clock.now();
|
|
544
|
+
if (doc.phase === "ready" && isFresh(doc.auth?.expiresAt, nowMs) && doc.wecom && isFresh(doc.wecom.expires_at_ms, nowMs)) return doc.wecom;
|
|
545
|
+
return null;
|
|
546
|
+
}
|
|
547
|
+
async ensureWecom(options) {
|
|
548
|
+
const force = options?.force ?? false;
|
|
549
|
+
const forceRefreshAccount = options?.refreshAccount ?? false;
|
|
550
|
+
if (!force && !forceRefreshAccount) {
|
|
551
|
+
const cached = this.cachedWecom(await this.load());
|
|
552
|
+
if (cached) return cached;
|
|
553
|
+
}
|
|
554
|
+
return this.lock.run("auth", async () => {
|
|
555
|
+
const doc = await this.load();
|
|
556
|
+
if (doc.phase === "refresh_unknown") throw new WecomError("REFRESH_OUTCOME_UNKNOWN_LOGIN_REQUIRED", true);
|
|
557
|
+
if (doc.phase === "pending_account") await this.fetchAccount(doc, options?.deadlineMonoMs, options?.signal);
|
|
558
|
+
if (doc.phase !== "ready" || !doc.auth) throw new WecomError("LOGIN_REQUIRED", true);
|
|
559
|
+
if (forceRefreshAccount || !isFresh(doc.auth.expiresAt, this.clock.now())) await this.refreshAccount(doc, options?.deadlineMonoMs, options?.signal);
|
|
560
|
+
if (!force && !forceRefreshAccount) {
|
|
561
|
+
const cachedAfterLock = this.cachedWecom(doc);
|
|
562
|
+
if (cachedAfterLock) return cachedAfterLock;
|
|
617
563
|
}
|
|
618
|
-
|
|
619
|
-
if (
|
|
620
|
-
|
|
621
|
-
const
|
|
564
|
+
const enterpriseId = doc.account?.enterpriseId;
|
|
565
|
+
if (typeof enterpriseId !== "string" || !enterpriseId) throw new WecomError("ENTERPRISE_ACCOUNT_REQUIRED", true);
|
|
566
|
+
const route = `/console/enterprises/${encodeURIComponent(enterpriseId)}/oneid_openapi/exchange-wecom-token`;
|
|
567
|
+
const exchange = () => this.requestCloud({
|
|
622
568
|
method: "POST",
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
role: "user",
|
|
627
|
-
taskId,
|
|
628
|
-
...record.context_id ? { contextId: record.context_id } : {},
|
|
629
|
-
parts: [{
|
|
630
|
-
kind: "text",
|
|
631
|
-
text
|
|
632
|
-
}]
|
|
633
|
-
} },
|
|
569
|
+
path: route,
|
|
570
|
+
auth: doc.auth,
|
|
571
|
+
deadlineMonoMs: options?.deadlineMonoMs,
|
|
634
572
|
signal: options?.signal
|
|
635
573
|
});
|
|
636
|
-
let
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
if (rRaw) {
|
|
654
|
-
rRaw.status = result.state;
|
|
655
|
-
rRaw.result = result;
|
|
656
|
-
rRaw.updated_at_ms = this.clock.now();
|
|
657
|
-
await this.storage.set(rKey, rRaw);
|
|
574
|
+
let exchanged;
|
|
575
|
+
try {
|
|
576
|
+
exchanged = await exchange().catch((err) => {
|
|
577
|
+
if (err instanceof WecomError && /^(?:HTTP_\d+_CODE|CLOUD_CODE)_10113$/.test(err.code)) return exchange();
|
|
578
|
+
throw err;
|
|
579
|
+
});
|
|
580
|
+
} catch (err) {
|
|
581
|
+
if (wecomAuthorizationError(err)) {
|
|
582
|
+
this.dayuan = void 0;
|
|
583
|
+
if (doc.wecom) {
|
|
584
|
+
doc.wecom = {
|
|
585
|
+
...doc.wecom,
|
|
586
|
+
expires_at_ms: 0
|
|
587
|
+
};
|
|
588
|
+
await this.save(doc);
|
|
589
|
+
}
|
|
590
|
+
throw new WecomError("WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN", true);
|
|
658
591
|
}
|
|
592
|
+
throw err;
|
|
659
593
|
}
|
|
660
|
-
|
|
594
|
+
const accessToken = assertSecret(exchanged.access_token);
|
|
595
|
+
const user = exchanged.alias_id;
|
|
596
|
+
const corp = exchanged.src_tid;
|
|
597
|
+
if (typeof user !== "string" || !user || typeof corp !== "string" || !corp) throw new WecomError("WECOM_STABLE_IDENTITY_MISSING");
|
|
598
|
+
const identity = createHash("sha256").update(JSON.stringify([corp, user])).digest("hex");
|
|
599
|
+
if (doc.wecom && doc.wecom.identity !== identity) throw new WecomError("WECOM_IDENTITY_CHANGED", true);
|
|
600
|
+
const expiresIn = parseDeadline(exchanged.expires_in);
|
|
601
|
+
if (!expiresIn) throw new WecomError("WECOM_EXPIRY_MISSING");
|
|
602
|
+
const credential = {
|
|
603
|
+
access_token: accessToken,
|
|
604
|
+
identity,
|
|
605
|
+
expires_at_ms: this.clock.now() + expiresIn * 1e3,
|
|
606
|
+
source: "workbuddy_cloud"
|
|
607
|
+
};
|
|
608
|
+
doc.wecom = credential;
|
|
609
|
+
await this.save(doc);
|
|
610
|
+
return credential;
|
|
661
611
|
});
|
|
662
612
|
}
|
|
663
|
-
async
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
const
|
|
683
|
-
return
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
613
|
+
async verifyWecom(signal) {
|
|
614
|
+
await this.ensureWecom({
|
|
615
|
+
force: true,
|
|
616
|
+
signal
|
|
617
|
+
});
|
|
618
|
+
await this.ensureDayuan({
|
|
619
|
+
force: true,
|
|
620
|
+
signal
|
|
621
|
+
});
|
|
622
|
+
return this.status();
|
|
623
|
+
}
|
|
624
|
+
async ensureDayuan(options) {
|
|
625
|
+
const user = await this.ensureWecom({ signal: options?.signal });
|
|
626
|
+
return this.lock.run("auth", async () => {
|
|
627
|
+
options?.signal?.throwIfAborted();
|
|
628
|
+
const doc = await this.load();
|
|
629
|
+
const enterprise = doc.account?.enterpriseId;
|
|
630
|
+
const uid = doc.account?.uid;
|
|
631
|
+
if (doc.phase !== "ready" || !doc.auth || !enterprise || !uid || doc.wecom?.identity !== user.identity || doc.wecom.access_token !== user.access_token) throw new WecomError("LOGIN_REQUIRED", true);
|
|
632
|
+
const identity = dayuanIdentity(enterprise, uid, user.identity);
|
|
633
|
+
if (!options?.force && this.dayuan?.identity === identity && isFresh(this.dayuan.expires_at_ms, this.clock.now())) return this.dayuan;
|
|
634
|
+
this.dayuan = void 0;
|
|
635
|
+
const headers = {
|
|
636
|
+
"X-User-Id": assertSecret(uid),
|
|
637
|
+
"X-Enterprise-Id": assertSecret(enterprise),
|
|
638
|
+
"X-Tenant-Id": assertSecret(enterprise)
|
|
639
|
+
};
|
|
640
|
+
if (typeof doc.auth.domain === "string" && doc.auth.domain) headers["X-Domain"] = assertSecret(doc.auth.domain);
|
|
641
|
+
const cloud = async (method, path) => {
|
|
642
|
+
let response;
|
|
643
|
+
try {
|
|
644
|
+
response = await this.transport({
|
|
645
|
+
method,
|
|
646
|
+
url: `${WORKBUDDY_ORIGIN}${path}`,
|
|
647
|
+
headers: {
|
|
648
|
+
...headers,
|
|
649
|
+
Accept: "application/json",
|
|
650
|
+
Authorization: `Bearer ${assertSecret(doc.auth?.accessToken)}`
|
|
651
|
+
},
|
|
652
|
+
maxBytes: AUTH_MAX_RESPONSE_BYTES,
|
|
653
|
+
timeoutMs: 15e3,
|
|
654
|
+
signal: options?.signal
|
|
655
|
+
});
|
|
656
|
+
} catch {
|
|
657
|
+
options?.signal?.throwIfAborted();
|
|
658
|
+
throw new WecomError("DAYUAN_AUTH_UNAVAILABLE", true);
|
|
659
|
+
}
|
|
660
|
+
const stage = method === "GET" ? "DAYUAN_DISCOVERY" : "DAYUAN_TICKET";
|
|
661
|
+
let payload$1;
|
|
662
|
+
try {
|
|
663
|
+
payload$1 = record(JSON.parse(response.body));
|
|
664
|
+
} catch {}
|
|
665
|
+
const code = payload$1?.code ?? record(payload$1?.error)?.code;
|
|
666
|
+
if (code === 10110 || code === 10111 || response.status === 401) throw new WecomError("WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN", true);
|
|
667
|
+
if (code === 10113 && method === "POST") return void 0;
|
|
668
|
+
if (response.status < 200 || response.status >= 300 || typeof code === "number" && code !== 0) throw new WecomError(`${stage}_HTTP_${response.status}${Number.isInteger(code) ? `_CODE_${code}` : ""}`, true);
|
|
669
|
+
if (!payload$1) throw new WecomError(`${stage}_INVALID_RESPONSE`, true);
|
|
670
|
+
return payload$1;
|
|
671
|
+
};
|
|
672
|
+
const endpoint = dayuanEndpoint(await cloud("GET", DAYUAN_DISCOVERY_PATH) ?? {});
|
|
673
|
+
const payload = await cloud("POST", options?.force ? `${DAYUAN_TICKET_PATH}?force_refresh=true` : DAYUAN_TICKET_PATH) ?? await cloud("POST", `${DAYUAN_TICKET_PATH}?force_refresh=true`);
|
|
674
|
+
if (!payload) throw new WecomError("DAYUAN_TICKET_CODE_10113", true);
|
|
675
|
+
const ticket = record(payload.data) ?? payload;
|
|
676
|
+
const raw = ticket?.ticket ?? ticket?.access_token ?? ticket?.accessToken ?? ticket?.token ?? ticket?.credential ?? ticket?.agent_ticket ?? ticket?.agentTicket;
|
|
677
|
+
const ttl = parseDeadline(ticket?.expires_in ?? ticket?.expiresIn ?? ticket?.ttl);
|
|
678
|
+
const absolute = parseDeadline(ticket?.expires_at ?? ticket?.expiresAt);
|
|
679
|
+
const now = this.clock.now();
|
|
680
|
+
const expires = ttl ? now + ttl * 1e3 : absolute < 0xe8d4a51000 ? absolute * 1e3 : absolute;
|
|
681
|
+
if (expires <= now) throw new WecomError("DAYUAN_TICKET_EXPIRY_MISSING", true);
|
|
682
|
+
this.dayuan = {
|
|
683
|
+
endpoint,
|
|
684
|
+
headers,
|
|
685
|
+
identity,
|
|
686
|
+
access_token: assertSecret(raw),
|
|
687
|
+
expires_at_ms: expires
|
|
690
688
|
};
|
|
689
|
+
return this.dayuan;
|
|
690
|
+
});
|
|
691
|
+
}
|
|
692
|
+
async logout() {
|
|
693
|
+
return this.lock.run("auth", async () => {
|
|
694
|
+
this.dayuan = void 0;
|
|
695
|
+
await this.storage.remove(AUTH_STORAGE_KEY);
|
|
696
|
+
const status = await this.status();
|
|
697
|
+
if (this.onAuthChange) await Promise.resolve(this.onAuthChange(status)).catch(() => {});
|
|
698
|
+
return status;
|
|
691
699
|
});
|
|
692
700
|
}
|
|
693
|
-
};
|
|
694
|
-
|
|
695
|
-
//#endregion
|
|
696
|
-
//#region src/
|
|
697
|
-
const
|
|
698
|
-
const
|
|
699
|
-
const
|
|
700
|
-
const
|
|
701
|
-
const
|
|
702
|
-
const
|
|
703
|
-
const
|
|
704
|
-
const
|
|
705
|
-
const
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
function
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
701
|
+
};
|
|
702
|
+
|
|
703
|
+
//#endregion
|
|
704
|
+
//#region src/a2a/client.ts
|
|
705
|
+
const A2A_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
|
|
706
|
+
const RECEIPT_PREFIX = "wecom/a2a/receipt/";
|
|
707
|
+
const TASK_PREFIX = "wecom/a2a/task/";
|
|
708
|
+
const POLL_INTERVAL_MS = 2e3;
|
|
709
|
+
const REQUEST_TIMEOUT_MS = 3e4;
|
|
710
|
+
const MAX_WAIT_SECONDS = 120;
|
|
711
|
+
const DEFAULT_WAIT_SECONDS = 20;
|
|
712
|
+
const SAFE_ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;
|
|
713
|
+
const TOKEN_EXPIRED_ERRCODES = new Set([
|
|
714
|
+
40001,
|
|
715
|
+
40014,
|
|
716
|
+
42001
|
|
717
|
+
]);
|
|
718
|
+
function cleanText(value, field, maxLength = 2e3) {
|
|
719
|
+
if (typeof value !== "string") throw new WecomError(`INVALID_${field.toUpperCase()}`, true);
|
|
720
|
+
const trimmed = value.trim();
|
|
721
|
+
if (!trimmed || trimmed.length > maxLength || hasControlChar(trimmed, { allowWhitespace: true })) throw new WecomError(`INVALID_${field.toUpperCase()}`, true);
|
|
722
|
+
return trimmed;
|
|
723
|
+
}
|
|
724
|
+
function cleanOptionalText(value, field, maxLength = 500) {
|
|
725
|
+
if (value === void 0 || value === null || value === "") return void 0;
|
|
726
|
+
return cleanText(value, field, maxLength);
|
|
727
|
+
}
|
|
728
|
+
function assertSafeId(value, field) {
|
|
729
|
+
const trimmed = value.trim();
|
|
730
|
+
if (!SAFE_ID_RE.test(trimmed)) throw new WecomError(`INVALID_${field.toUpperCase()}`, true);
|
|
731
|
+
return trimmed;
|
|
732
|
+
}
|
|
733
|
+
function normalizeWaitSeconds(value) {
|
|
734
|
+
if (value === void 0) return DEFAULT_WAIT_SECONDS;
|
|
735
|
+
if (!Number.isFinite(value) || value < 0) return 0;
|
|
736
|
+
return Math.min(Math.floor(value), MAX_WAIT_SECONDS);
|
|
737
|
+
}
|
|
738
|
+
function normalizeState(raw) {
|
|
739
|
+
if (typeof raw === "number") return [
|
|
740
|
+
"unknown",
|
|
741
|
+
"submitted",
|
|
742
|
+
"working",
|
|
743
|
+
"completed",
|
|
744
|
+
"failed",
|
|
745
|
+
"canceled",
|
|
746
|
+
"input_required",
|
|
747
|
+
"rejected",
|
|
748
|
+
"auth_required"
|
|
749
|
+
][raw] ?? "unknown";
|
|
750
|
+
if (typeof raw !== "string") return "unknown";
|
|
751
|
+
const normalized = raw.trim().toLowerCase().replace(/-/g, "_").replace(/^task_state_/, "");
|
|
752
|
+
switch (normalized) {
|
|
753
|
+
case "submitted":
|
|
754
|
+
case "working":
|
|
755
|
+
case "input_required":
|
|
756
|
+
case "auth_required":
|
|
757
|
+
case "completed":
|
|
758
|
+
case "failed":
|
|
759
|
+
case "canceled":
|
|
760
|
+
case "rejected": return normalized;
|
|
761
|
+
case "cancelled": return "canceled";
|
|
762
|
+
default: return "unknown";
|
|
763
|
+
}
|
|
716
764
|
}
|
|
717
|
-
function
|
|
718
|
-
|
|
765
|
+
function isTerminalState(state) {
|
|
766
|
+
return state === "completed" || state === "failed" || state === "canceled" || state === "rejected";
|
|
767
|
+
}
|
|
768
|
+
function isSettledForWait(state) {
|
|
769
|
+
return isTerminalState(state) || state === "input_required" || state === "auth_required";
|
|
770
|
+
}
|
|
771
|
+
function asRecord(value) {
|
|
772
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
719
773
|
return value;
|
|
720
774
|
}
|
|
721
|
-
function
|
|
722
|
-
|
|
723
|
-
|
|
775
|
+
function collectParts(payload) {
|
|
776
|
+
const parts = [];
|
|
777
|
+
const pushFrom = (container) => {
|
|
778
|
+
const rec = asRecord(container);
|
|
779
|
+
if (!rec) return;
|
|
780
|
+
if (Array.isArray(rec.parts)) for (const item of rec.parts) {
|
|
781
|
+
const part = asRecord(item);
|
|
782
|
+
if (part) parts.push(part);
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
if (Array.isArray(payload.artifacts)) for (const artifact of payload.artifacts) pushFrom(artifact);
|
|
786
|
+
const status = asRecord(payload.status);
|
|
787
|
+
if (status) pushFrom(status.message);
|
|
788
|
+
pushFrom(payload.message);
|
|
789
|
+
return parts;
|
|
724
790
|
}
|
|
725
|
-
function
|
|
726
|
-
if (!value || typeof value !== "object"
|
|
727
|
-
|
|
728
|
-
const
|
|
729
|
-
|
|
730
|
-
if (
|
|
731
|
-
|
|
732
|
-
const
|
|
733
|
-
|
|
734
|
-
|
|
791
|
+
function hasApprovalMarker(value, depth = 0) {
|
|
792
|
+
if (depth > 5 || !value || typeof value !== "object") return false;
|
|
793
|
+
if (Array.isArray(value)) return value.some((item) => hasApprovalMarker(item, depth + 1));
|
|
794
|
+
const rec = value;
|
|
795
|
+
if (rec.wecom_part_type === "approval" || rec.part_type === "approval") return true;
|
|
796
|
+
if (Array.isArray(rec.token_id_list) && rec.token_id_list.length > 0) return true;
|
|
797
|
+
if (typeof rec.approval_id === "string" && rec.approval_id.length > 0) return true;
|
|
798
|
+
for (const child of Object.values(rec)) if (child && typeof child === "object" && hasApprovalMarker(child, depth + 1)) return true;
|
|
799
|
+
return false;
|
|
800
|
+
}
|
|
801
|
+
function extractSummaryText(parts) {
|
|
802
|
+
const lines = [];
|
|
803
|
+
for (const part of parts) if (typeof part.text === "string" && part.text.trim()) lines.push(part.text.trim());
|
|
804
|
+
else if (part.data && typeof part.data === "object") {
|
|
805
|
+
const data = part.data;
|
|
806
|
+
if (typeof data.text === "string" && data.text.trim()) lines.push(data.text.trim());
|
|
807
|
+
else if (typeof data.title === "string" && data.title.trim()) lines.push(data.title.trim());
|
|
808
|
+
}
|
|
809
|
+
return lines.join("\n\n").trim();
|
|
810
|
+
}
|
|
811
|
+
function buildReadOnlyPrompt(input) {
|
|
812
|
+
if (input.action === "search_groups") {
|
|
813
|
+
const query$1 = cleanText(input.query, "query", 300);
|
|
814
|
+
const limit = input.limit !== void 0 && Number.isFinite(input.limit) ? Math.max(1, Math.min(20, Math.floor(input.limit))) : 10;
|
|
815
|
+
return {
|
|
816
|
+
prompt: `只读查询:请在企业微信中查找名称或主题与「${query$1}」相关的群聊,最多列出 ${limit} 个候选群名及简短说明。不要发送任何消息或执行写操作。`,
|
|
817
|
+
canonical: {
|
|
818
|
+
action: input.action,
|
|
819
|
+
query: query$1,
|
|
820
|
+
limit
|
|
821
|
+
}
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
if (input.action === "read_chat") {
|
|
825
|
+
const chatName$1 = cleanText(input.chat_name, "chat_name", 300);
|
|
826
|
+
const question = cleanText(input.question, "question", 1500);
|
|
827
|
+
const timeRange$1 = cleanOptionalText(input.time_range, "time_range", 200);
|
|
828
|
+
return {
|
|
829
|
+
prompt: `只读查询:请阅读企业微信群聊「${chatName$1}」${timeRange$1 ? `(时间范围:${timeRange$1})` : ""},回答以下问题并给出要点摘要:${question}。不要发送任何消息或执行写操作。`,
|
|
830
|
+
canonical: {
|
|
831
|
+
action: input.action,
|
|
832
|
+
chat_name: chatName$1,
|
|
833
|
+
question,
|
|
834
|
+
time_range: timeRange$1 ?? null
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
}
|
|
838
|
+
const query = cleanText(input.query, "query", 1e3);
|
|
839
|
+
const chatName = cleanOptionalText(input.chat_name, "chat_name", 300);
|
|
840
|
+
const timeRange = cleanOptionalText(input.time_range, "time_range", 200);
|
|
841
|
+
const scope = [chatName ? `限定群聊「${chatName}」` : null, timeRange ? `时间范围:${timeRange}` : null].filter(Boolean).join(",");
|
|
735
842
|
return {
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
843
|
+
prompt: `只读查询:请在企业微信消息中检索与「${query}」相关的内容${scope ? `(${scope})` : ""},汇总相关讨论结论与来源群名。不要发送任何消息或执行写操作。`,
|
|
844
|
+
canonical: {
|
|
845
|
+
action: input.action,
|
|
846
|
+
query,
|
|
847
|
+
chat_name: chatName ?? null,
|
|
848
|
+
time_range: timeRange ?? null
|
|
849
|
+
}
|
|
741
850
|
};
|
|
742
851
|
}
|
|
743
|
-
function
|
|
744
|
-
|
|
745
|
-
const record = account;
|
|
746
|
-
if (typeof record.uid !== "string" || !record.uid) throw new WecomError("INVALID_ACCOUNT_RESPONSE");
|
|
747
|
-
const enterpriseId = typeof record.enterpriseId === "string" ? record.enterpriseId : void 0;
|
|
748
|
-
return [record.uid, enterpriseId];
|
|
749
|
-
}
|
|
750
|
-
function isFresh(expiryMs, nowMs) {
|
|
751
|
-
return parseDeadline(expiryMs) > nowMs + FRESH_BUFFER_MS;
|
|
852
|
+
function fingerprintOf(canonical) {
|
|
853
|
+
return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
752
854
|
}
|
|
753
|
-
function
|
|
754
|
-
if (
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
return false;
|
|
855
|
+
function buildWhitelistedUrl(endpoint, route) {
|
|
856
|
+
if (route.kind === "send") return `${endpoint}/message:send`;
|
|
857
|
+
const safeId = assertSafeId(route.taskId, "task_id");
|
|
858
|
+
return `${endpoint}/tasks/${encodeURIComponent(safeId)}?historyLength=0`;
|
|
758
859
|
}
|
|
759
|
-
var
|
|
860
|
+
var DayuanA2AClient = class {
|
|
861
|
+
auth;
|
|
760
862
|
storage;
|
|
761
863
|
transport;
|
|
762
864
|
clock;
|
|
763
|
-
onAuthChange;
|
|
764
865
|
lock = new AsyncKeyLock();
|
|
765
866
|
constructor(options) {
|
|
867
|
+
this.auth = options.auth;
|
|
766
868
|
this.storage = options.storage;
|
|
767
869
|
this.transport = options.transport ?? createFetchTransport();
|
|
768
870
|
this.clock = options.clock ?? systemClock;
|
|
769
|
-
this.onAuthChange = options.onAuthChange;
|
|
770
|
-
}
|
|
771
|
-
async load() {
|
|
772
|
-
const stored = await this.storage.get(AUTH_STORAGE_KEY);
|
|
773
|
-
if (!stored || typeof stored !== "object" || Array.isArray(stored)) return { phase: "logged_out" };
|
|
774
|
-
const doc = stored;
|
|
775
|
-
return {
|
|
776
|
-
...doc,
|
|
777
|
-
phase: doc.phase ?? "logged_out"
|
|
778
|
-
};
|
|
779
|
-
}
|
|
780
|
-
async save(doc) {
|
|
781
|
-
await this.storage.set(AUTH_STORAGE_KEY, doc);
|
|
782
|
-
if (this.onAuthChange) await Promise.resolve(this.onAuthChange(this.toStatus(doc))).catch(() => {});
|
|
783
|
-
}
|
|
784
|
-
toStatus(doc) {
|
|
785
|
-
const auth = doc.auth;
|
|
786
|
-
return {
|
|
787
|
-
phase: doc.phase,
|
|
788
|
-
desktop_required: false,
|
|
789
|
-
cloud_dependency: WORKBUDDY_ORIGIN,
|
|
790
|
-
account_expires_at_ms: auth?.expiresAt || null,
|
|
791
|
-
refresh_expires_at_ms: auth?.refreshExpiresAt || null,
|
|
792
|
-
refresh_credential_present: Boolean(auth?.refreshToken),
|
|
793
|
-
wecom_expires_at_ms: doc.wecom?.expires_at_ms ?? null,
|
|
794
|
-
wecom_configured: Boolean(doc.wecom?.access_token),
|
|
795
|
-
authorization_verified: false
|
|
796
|
-
};
|
|
797
|
-
}
|
|
798
|
-
async requestCloud(options) {
|
|
799
|
-
const { method, path, auth, refreshToken, beforeSend, deadlineMonoMs, signal } = options;
|
|
800
|
-
if (!isAllowedEndpoint(method, path)) throw new WecomError("ENDPOINT_NOT_ALLOWED", true);
|
|
801
|
-
const headers = {
|
|
802
|
-
Accept: "application/json",
|
|
803
|
-
"Content-Type": "application/json",
|
|
804
|
-
"X-Domain": "www.workbuddy.cn",
|
|
805
|
-
"X-Product": "SaaS",
|
|
806
|
-
"User-Agent": USER_AGENT
|
|
807
|
-
};
|
|
808
|
-
if (auth) headers.Authorization = `Bearer ${assertSecret(auth.accessToken)}`;
|
|
809
|
-
if (refreshToken) {
|
|
810
|
-
headers["X-Refresh-Token"] = assertSecret(refreshToken);
|
|
811
|
-
headers["X-Auth-Refresh-Source"] = "plugin";
|
|
812
|
-
}
|
|
813
|
-
let timeoutMs = 25e3;
|
|
814
|
-
if (deadlineMonoMs !== void 0) {
|
|
815
|
-
const remaining = deadlineMonoMs - this.clock.monotonic();
|
|
816
|
-
if (remaining <= 0) throw new WecomError("WAIT_TIMEOUT");
|
|
817
|
-
timeoutMs = Math.min(timeoutMs, remaining);
|
|
818
|
-
}
|
|
819
|
-
if (beforeSend) await beforeSend();
|
|
820
|
-
const response = await this.transport({
|
|
821
|
-
method,
|
|
822
|
-
url: `${WORKBUDDY_ORIGIN}${path}`,
|
|
823
|
-
headers,
|
|
824
|
-
body: method === "POST" ? "{}" : void 0,
|
|
825
|
-
timeoutMs,
|
|
826
|
-
maxBytes: AUTH_MAX_RESPONSE_BYTES,
|
|
827
|
-
signal
|
|
828
|
-
});
|
|
829
|
-
if (response.status >= 300 && response.status < 400) throw new WecomError("REDIRECT_REJECTED", true);
|
|
830
|
-
let parsed;
|
|
831
|
-
try {
|
|
832
|
-
parsed = JSON.parse(response.body);
|
|
833
|
-
} catch {
|
|
834
|
-
if (response.status >= 400) throw new WecomError(`HTTP_${response.status}`, response.status < 500);
|
|
835
|
-
throw new WecomError("INVALID_RESPONSE");
|
|
836
|
-
}
|
|
837
|
-
const bodyRecord = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
|
|
838
|
-
if (response.status >= 400) {
|
|
839
|
-
const code$1 = bodyRecord?.code;
|
|
840
|
-
if (code$1 === 11217 || code$1 === 12151) throw new WecomError(`PENDING_${code$1}`);
|
|
841
|
-
const suffix = typeof code$1 === "number" && Number.isInteger(code$1) ? `_CODE_${code$1}` : "";
|
|
842
|
-
throw new WecomError(`HTTP_${response.status}${suffix}`, response.status < 500);
|
|
843
|
-
}
|
|
844
|
-
if (!bodyRecord) throw new WecomError("INVALID_RESPONSE");
|
|
845
|
-
const code = bodyRecord.code;
|
|
846
|
-
if (code === 11217 || code === 12151) throw new WecomError(`PENDING_${code}`);
|
|
847
|
-
if (code !== 0) throw new WecomError(typeof code === "number" && Number.isInteger(code) ? `CLOUD_CODE_${code}` : "INVALID_RESPONSE");
|
|
848
|
-
const data = bodyRecord.data;
|
|
849
|
-
if (!data || typeof data !== "object" || Array.isArray(data)) throw new WecomError("INVALID_RESPONSE");
|
|
850
|
-
return data;
|
|
851
871
|
}
|
|
852
|
-
|
|
853
|
-
return
|
|
872
|
+
receiptKey(identity, requestId) {
|
|
873
|
+
return `${RECEIPT_PREFIX}${identity}/${requestId}`;
|
|
854
874
|
}
|
|
855
|
-
|
|
875
|
+
taskKey(taskId) {
|
|
876
|
+
return `${TASK_PREFIX}${taskId}`;
|
|
877
|
+
}
|
|
878
|
+
parseTaskPayload(raw, meta) {
|
|
879
|
+
const taskObj = asRecord(raw.result) ?? asRecord(raw.task) ?? raw;
|
|
880
|
+
const rawId = taskObj.id ?? taskObj.taskId ?? raw.id;
|
|
881
|
+
if (typeof rawId !== "string" || !rawId.trim()) throw new WecomError("A2A_TASK_ID_MISSING");
|
|
882
|
+
const taskId = assertSafeId(rawId, "task_id");
|
|
883
|
+
const contextId = typeof taskObj.contextId === "string" && taskObj.contextId ? taskObj.contextId : void 0;
|
|
884
|
+
const state = normalizeState(asRecord(taskObj.status)?.state ?? taskObj.state);
|
|
885
|
+
const parts = collectParts(taskObj);
|
|
886
|
+
const approval = (state === "input_required" || state === "auth_required") && hasApprovalMarker(taskObj);
|
|
887
|
+
const summary = state === "auth_required" || approval ? "" : extractSummaryText(parts);
|
|
888
|
+
let interactionKind = "none";
|
|
889
|
+
let canReplyInText = false;
|
|
890
|
+
let humanActionRequired = false;
|
|
891
|
+
let guidance;
|
|
892
|
+
if (approval) {
|
|
893
|
+
interactionKind = "approval_required";
|
|
894
|
+
humanActionRequired = true;
|
|
895
|
+
guidance = "请本人在企业微信官方界面处理原审批卡,完成后查询原任务状态。";
|
|
896
|
+
} else if (state === "auth_required") {
|
|
897
|
+
interactionKind = "authorization_required";
|
|
898
|
+
humanActionRequired = true;
|
|
899
|
+
guidance = "大圆要求追加授权。请用同一企业账号在官方授权页确认,完成后查询原任务状态。若原任务仍待授权,请在 WorkBuddy 或企业微信官方界面查看该任务。";
|
|
900
|
+
} else if (state === "input_required") if (summary.length > 0) {
|
|
901
|
+
interactionKind = "text_clarification";
|
|
902
|
+
canReplyInText = true;
|
|
903
|
+
guidance = "大圆需要进一步澄清问题,请调用 wecom_read_reply 回复澄清文本。";
|
|
904
|
+
} else {
|
|
905
|
+
interactionKind = "unsupported";
|
|
906
|
+
canReplyInText = false;
|
|
907
|
+
humanActionRequired = true;
|
|
908
|
+
guidance = "任务处于 input_required 状态但未包含可回复的文本澄清内容,请在企业微信客户端查看。";
|
|
909
|
+
}
|
|
856
910
|
return {
|
|
857
|
-
|
|
858
|
-
|
|
911
|
+
task_id: taskId,
|
|
912
|
+
...contextId ? { context_id: contextId } : {},
|
|
913
|
+
...meta.request_id ? { request_id: meta.request_id } : {},
|
|
914
|
+
...meta.action ? { action: meta.action } : {},
|
|
915
|
+
state,
|
|
916
|
+
completed: isTerminalState(state),
|
|
917
|
+
is_summary: true,
|
|
918
|
+
summary,
|
|
919
|
+
interaction_kind: interactionKind,
|
|
920
|
+
can_reply_in_text: canReplyInText,
|
|
921
|
+
human_action_required: humanActionRequired,
|
|
922
|
+
...interactionKind === "authorization_required" ? { authorization_url: WECOM_LOGIN_URL } : {},
|
|
923
|
+
...guidance ? { guidance } : {},
|
|
924
|
+
from_cache: meta.from_cache,
|
|
925
|
+
updated_at_ms: this.clock.now()
|
|
859
926
|
};
|
|
860
927
|
}
|
|
861
|
-
async
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
}
|
|
874
|
-
const
|
|
875
|
-
method:
|
|
876
|
-
|
|
877
|
-
|
|
928
|
+
async requestA2A(options) {
|
|
929
|
+
let credential = await this.auth.ensureDayuan({ signal: options.signal });
|
|
930
|
+
if (options.expectedIdentity && credential.identity !== options.expectedIdentity) throw new WecomError("DAYUAN_IDENTITY_CHANGED", true);
|
|
931
|
+
const url = buildWhitelistedUrl(credential.endpoint, options.route);
|
|
932
|
+
const executeOnce = async (ticket) => {
|
|
933
|
+
const headers = {
|
|
934
|
+
...ticket.headers,
|
|
935
|
+
Accept: "application/a2a+json, application/json",
|
|
936
|
+
"Content-Type": "application/json",
|
|
937
|
+
Authorization: `Bearer ${ticket.access_token}`
|
|
938
|
+
};
|
|
939
|
+
let serialized;
|
|
940
|
+
if (options.method === "POST") serialized = JSON.stringify(options.body ?? {});
|
|
941
|
+
const response = await this.transport({
|
|
942
|
+
method: options.method,
|
|
943
|
+
url,
|
|
944
|
+
headers,
|
|
945
|
+
body: serialized,
|
|
946
|
+
timeoutMs: REQUEST_TIMEOUT_MS,
|
|
947
|
+
maxBytes: A2A_MAX_RESPONSE_BYTES,
|
|
948
|
+
signal: options.signal
|
|
878
949
|
});
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
950
|
+
let parsed = {};
|
|
951
|
+
if (response.body.trim()) try {
|
|
952
|
+
const decoded = JSON.parse(response.body);
|
|
953
|
+
if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) throw new WecomError("INVALID_A2A_JSON");
|
|
954
|
+
parsed = decoded;
|
|
955
|
+
} catch (err) {
|
|
956
|
+
if (response.status === 401) return {
|
|
957
|
+
status: 401,
|
|
958
|
+
errcode: 0,
|
|
959
|
+
agentCode: void 0,
|
|
960
|
+
parsed,
|
|
961
|
+
isAuthFailure: true
|
|
962
|
+
};
|
|
963
|
+
if (err instanceof WecomError) throw err;
|
|
964
|
+
throw new WecomError("INVALID_A2A_JSON");
|
|
887
965
|
}
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
const
|
|
891
|
-
const next = {
|
|
892
|
-
...doc,
|
|
893
|
-
phase: "pending_token",
|
|
894
|
-
pending: {
|
|
895
|
-
state,
|
|
896
|
-
url,
|
|
897
|
-
created_at_ms: this.clock.now()
|
|
898
|
-
}
|
|
899
|
-
};
|
|
900
|
-
await this.save(next);
|
|
966
|
+
const errcode = typeof parsed.errcode === "number" ? parsed.errcode : 0;
|
|
967
|
+
const agentCode = asRecord(parsed.error)?.code;
|
|
968
|
+
const isAuthFailure = response.status === 401 || errcode === 896004 || agentCode === 896004 || TOKEN_EXPIRED_ERRCODES.has(errcode);
|
|
901
969
|
return {
|
|
902
|
-
|
|
903
|
-
|
|
970
|
+
status: response.status,
|
|
971
|
+
errcode,
|
|
972
|
+
agentCode,
|
|
973
|
+
parsed,
|
|
974
|
+
isAuthFailure
|
|
904
975
|
};
|
|
905
|
-
}
|
|
976
|
+
};
|
|
977
|
+
let attempt = await executeOnce(credential);
|
|
978
|
+
if (attempt.isAuthFailure && (options.allowAuthRetry ?? true)) {
|
|
979
|
+
const renewed = await this.auth.ensureDayuan({
|
|
980
|
+
force: true,
|
|
981
|
+
signal: options.signal
|
|
982
|
+
});
|
|
983
|
+
if (renewed.identity !== credential.identity || renewed.endpoint !== credential.endpoint) throw new WecomError("DAYUAN_IDENTITY_OR_ENDPOINT_CHANGED", true);
|
|
984
|
+
credential = renewed;
|
|
985
|
+
attempt = await executeOnce(credential);
|
|
986
|
+
}
|
|
987
|
+
if (attempt.isAuthFailure) throw new WecomError("WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN", true);
|
|
988
|
+
if (attempt.status === 403) throw new WecomError("A2A_FORBIDDEN", true);
|
|
989
|
+
if (attempt.status < 200 || attempt.status >= 300) {
|
|
990
|
+
const code = Number.isInteger(attempt.agentCode) ? attempt.agentCode : attempt.errcode || void 0;
|
|
991
|
+
throw new WecomError(`A2A_HTTP_${attempt.status}${code === void 0 ? "" : `_CODE_${code}`}`);
|
|
992
|
+
}
|
|
993
|
+
if (attempt.errcode !== 0) throw new WecomError(`A2A_ERRCODE_${attempt.errcode}`);
|
|
994
|
+
return {
|
|
995
|
+
payload: attempt.parsed,
|
|
996
|
+
identity: credential.identity
|
|
997
|
+
};
|
|
906
998
|
}
|
|
907
|
-
async
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
if (
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
999
|
+
async saveTaskRecord(record$1) {
|
|
1000
|
+
await this.storage.set(this.taskKey(record$1.task_id), record$1);
|
|
1001
|
+
}
|
|
1002
|
+
async loadTaskRecord(taskId) {
|
|
1003
|
+
const raw = await this.storage.get(this.taskKey(taskId));
|
|
1004
|
+
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
|
|
1005
|
+
return raw;
|
|
1006
|
+
}
|
|
1007
|
+
async pollTask(initial, identity, waitSeconds, options) {
|
|
1008
|
+
let current = initial;
|
|
1009
|
+
if (isSettledForWait(current.state) || waitSeconds <= 0) return current;
|
|
1010
|
+
const deadlineMono = this.clock.monotonic() + waitSeconds * 1e3;
|
|
1011
|
+
let pollCount = 0;
|
|
1012
|
+
while (!isSettledForWait(current.state)) {
|
|
1013
|
+
const remaining = deadlineMono - this.clock.monotonic();
|
|
1014
|
+
if (remaining <= 0) break;
|
|
1015
|
+
pollCount += 1;
|
|
1016
|
+
if (options?.onProgress) await Promise.resolve(options.onProgress({
|
|
1017
|
+
task_id: current.task_id,
|
|
1018
|
+
state: current.state,
|
|
1019
|
+
poll_count: pollCount
|
|
1020
|
+
}));
|
|
1021
|
+
await this.clock.sleep(Math.min(POLL_INTERVAL_MS, remaining), options?.signal);
|
|
1022
|
+
const { payload } = await this.requestA2A({
|
|
1023
|
+
method: "GET",
|
|
1024
|
+
expectedIdentity: identity,
|
|
1025
|
+
route: {
|
|
1026
|
+
kind: "task",
|
|
1027
|
+
taskId: current.task_id
|
|
1028
|
+
},
|
|
1029
|
+
signal: options?.signal
|
|
1030
|
+
}).catch((err) => {
|
|
1031
|
+
if (!(err instanceof WecomError) || err.code !== "WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN") throw err;
|
|
1032
|
+
return { payload: {
|
|
1033
|
+
id: current.task_id,
|
|
1034
|
+
contextId: current.context_id,
|
|
1035
|
+
status: { state: "auth_required" }
|
|
1036
|
+
} };
|
|
1037
|
+
});
|
|
1038
|
+
current = this.parseTaskPayload(payload, {
|
|
1039
|
+
request_id: current.request_id,
|
|
1040
|
+
action: current.action,
|
|
1041
|
+
from_cache: false
|
|
1042
|
+
});
|
|
1043
|
+
await this.saveTaskRecord({
|
|
1044
|
+
task_id: current.task_id,
|
|
1045
|
+
context_id: current.context_id,
|
|
1046
|
+
identity,
|
|
1047
|
+
action: current.action,
|
|
1048
|
+
request_id: current.request_id,
|
|
1049
|
+
result: current
|
|
1050
|
+
});
|
|
924
1051
|
}
|
|
925
|
-
|
|
926
|
-
doc.phase = "ready";
|
|
927
|
-
delete doc.pending;
|
|
928
|
-
await this.save(doc);
|
|
1052
|
+
return current;
|
|
929
1053
|
}
|
|
930
|
-
async
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
1054
|
+
async start(input, options) {
|
|
1055
|
+
const { prompt, canonical } = buildReadOnlyPrompt(input);
|
|
1056
|
+
const requestId = input.request_id ? assertSafeId(input.request_id, "request_id") : randomUUID();
|
|
1057
|
+
const waitSeconds = normalizeWaitSeconds(input.wait_seconds);
|
|
1058
|
+
const fingerprint = fingerprintOf(canonical);
|
|
1059
|
+
const credential = await this.auth.ensureDayuan({ signal: options?.signal });
|
|
1060
|
+
const receiptKey = this.receiptKey(credential.identity, requestId);
|
|
1061
|
+
return this.lock.run(`receipt:${receiptKey}`, async () => {
|
|
1062
|
+
const existing = asRecord(await this.storage.get(receiptKey));
|
|
1063
|
+
if (existing) {
|
|
1064
|
+
if (existing.fingerprint !== fingerprint) throw new WecomError("REQUEST_ID_CONFLICT", true);
|
|
1065
|
+
if (existing.status === "submit_unknown") throw new WecomError("SUBMIT_OUTCOME_UNKNOWN", true);
|
|
1066
|
+
if (existing.result && existing.result.state !== "auth_required" && isSettledForWait(existing.result.state)) return {
|
|
1067
|
+
...existing.result,
|
|
1068
|
+
from_cache: true
|
|
1069
|
+
};
|
|
1070
|
+
if (existing.task_id) {
|
|
1071
|
+
const polled = await this.getResult({
|
|
1072
|
+
task_id: existing.task_id,
|
|
1073
|
+
wait_seconds: waitSeconds
|
|
1074
|
+
}, options);
|
|
1075
|
+
existing.status = polled.state;
|
|
1076
|
+
existing.result = polled;
|
|
1077
|
+
existing.updated_at_ms = this.clock.now();
|
|
1078
|
+
await this.storage.set(receiptKey, existing);
|
|
1079
|
+
return polled;
|
|
947
1080
|
}
|
|
948
1081
|
}
|
|
949
|
-
|
|
950
|
-
|
|
1082
|
+
const now = this.clock.now();
|
|
1083
|
+
const pendingReceipt = {
|
|
1084
|
+
request_id: requestId,
|
|
1085
|
+
identity: credential.identity,
|
|
1086
|
+
action: input.action,
|
|
1087
|
+
fingerprint,
|
|
1088
|
+
status: "submit_unknown",
|
|
1089
|
+
created_at_ms: now,
|
|
1090
|
+
updated_at_ms: now
|
|
1091
|
+
};
|
|
1092
|
+
await this.storage.set(receiptKey, pendingReceipt);
|
|
1093
|
+
let payload;
|
|
1094
|
+
let identity;
|
|
1095
|
+
try {
|
|
1096
|
+
const res = await this.requestA2A({
|
|
1097
|
+
method: "POST",
|
|
1098
|
+
expectedIdentity: credential.identity,
|
|
1099
|
+
route: { kind: "send" },
|
|
1100
|
+
body: { message: {
|
|
1101
|
+
messageId: requestId,
|
|
1102
|
+
role: "ROLE_USER",
|
|
1103
|
+
parts: [{ text: prompt }]
|
|
1104
|
+
} },
|
|
1105
|
+
signal: options?.signal
|
|
1106
|
+
});
|
|
1107
|
+
payload = res.payload;
|
|
1108
|
+
identity = res.identity;
|
|
951
1109
|
} catch (err) {
|
|
952
|
-
if (err instanceof WecomError && err.code
|
|
1110
|
+
if (err instanceof WecomError && (err.code === "TRANSPORT_NOT_SENT" || err.definitive)) await this.storage.remove(receiptKey);
|
|
953
1111
|
throw err;
|
|
954
1112
|
}
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
1113
|
+
let result = this.parseTaskPayload(payload, {
|
|
1114
|
+
request_id: requestId,
|
|
1115
|
+
action: input.action,
|
|
1116
|
+
from_cache: false
|
|
1117
|
+
});
|
|
1118
|
+
await this.saveTaskRecord({
|
|
1119
|
+
task_id: result.task_id,
|
|
1120
|
+
context_id: result.context_id,
|
|
1121
|
+
identity,
|
|
1122
|
+
action: input.action,
|
|
1123
|
+
request_id: requestId,
|
|
1124
|
+
result
|
|
1125
|
+
});
|
|
1126
|
+
result = await this.pollTask(result, identity, waitSeconds, options);
|
|
1127
|
+
const finalized = {
|
|
1128
|
+
...pendingReceipt,
|
|
1129
|
+
identity,
|
|
1130
|
+
status: result.state,
|
|
1131
|
+
task_id: result.task_id,
|
|
1132
|
+
context_id: result.context_id,
|
|
1133
|
+
result,
|
|
1134
|
+
updated_at_ms: this.clock.now()
|
|
960
1135
|
};
|
|
1136
|
+
await this.storage.set(receiptKey, finalized);
|
|
1137
|
+
return result;
|
|
961
1138
|
});
|
|
962
1139
|
}
|
|
963
|
-
async
|
|
964
|
-
const
|
|
965
|
-
const
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
result = await this.finish({
|
|
975
|
-
signal: options.signal,
|
|
976
|
-
deadlineMonoMs
|
|
977
|
-
});
|
|
1140
|
+
async getResult(input, options) {
|
|
1141
|
+
const taskId = assertSafeId(input.task_id, "task_id");
|
|
1142
|
+
const waitSeconds = normalizeWaitSeconds(input.wait_seconds);
|
|
1143
|
+
const existing = await this.loadTaskRecord(taskId);
|
|
1144
|
+
if (existing && isTerminalState(existing.result.state)) {
|
|
1145
|
+
const credential = await this.auth.ensureDayuan({ signal: options?.signal });
|
|
1146
|
+
if (existing.identity !== credential.identity) throw new WecomError("DAYUAN_IDENTITY_CHANGED", true);
|
|
1147
|
+
return {
|
|
1148
|
+
...existing.result,
|
|
1149
|
+
from_cache: true
|
|
1150
|
+
};
|
|
978
1151
|
}
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
1152
|
+
const { payload, identity } = await this.requestA2A({
|
|
1153
|
+
method: "GET",
|
|
1154
|
+
expectedIdentity: existing?.identity,
|
|
1155
|
+
route: {
|
|
1156
|
+
kind: "task",
|
|
1157
|
+
taskId
|
|
1158
|
+
},
|
|
1159
|
+
signal: options?.signal
|
|
982
1160
|
});
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
1161
|
+
let result = this.parseTaskPayload(payload, {
|
|
1162
|
+
request_id: existing?.request_id,
|
|
1163
|
+
action: existing?.action,
|
|
1164
|
+
from_cache: false
|
|
1165
|
+
});
|
|
1166
|
+
await this.saveTaskRecord({
|
|
1167
|
+
task_id: result.task_id,
|
|
1168
|
+
context_id: result.context_id ?? existing?.context_id,
|
|
1169
|
+
identity,
|
|
1170
|
+
action: existing?.action,
|
|
1171
|
+
request_id: existing?.request_id,
|
|
1172
|
+
result
|
|
1173
|
+
});
|
|
1174
|
+
result = await this.pollTask(result, identity, waitSeconds, options);
|
|
1175
|
+
if (existing?.request_id) {
|
|
1176
|
+
const rKey = this.receiptKey(identity, existing.request_id);
|
|
1177
|
+
const rRaw = asRecord(await this.storage.get(rKey));
|
|
1178
|
+
if (rRaw) {
|
|
1179
|
+
rRaw.status = result.state;
|
|
1180
|
+
rRaw.result = result;
|
|
1181
|
+
rRaw.updated_at_ms = this.clock.now();
|
|
1182
|
+
await this.storage.set(rKey, rRaw);
|
|
1183
|
+
}
|
|
997
1184
|
}
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1185
|
+
return result;
|
|
1186
|
+
}
|
|
1187
|
+
async reply(input, options) {
|
|
1188
|
+
const taskId = assertSafeId(input.task_id, "task_id");
|
|
1189
|
+
const text = cleanText(input.text, "text", 1500);
|
|
1190
|
+
const waitSeconds = normalizeWaitSeconds(input.wait_seconds);
|
|
1191
|
+
const replyMessageId = input.request_id ? assertSafeId(input.request_id, "request_id") : randomUUID();
|
|
1192
|
+
return this.lock.run(`task:${taskId}`, async () => {
|
|
1193
|
+
let record$1 = await this.loadTaskRecord(taskId);
|
|
1194
|
+
if (!record$1) {
|
|
1195
|
+
const fetched = await this.getResult({
|
|
1196
|
+
task_id: taskId,
|
|
1197
|
+
wait_seconds: 0
|
|
1198
|
+
}, options);
|
|
1199
|
+
record$1 = await this.loadTaskRecord(fetched.task_id);
|
|
1200
|
+
}
|
|
1201
|
+
if (record$1?.result.state !== "input_required") throw new WecomError("TASK_NOT_WAITING_FOR_INPUT", true);
|
|
1202
|
+
if (record$1.result.interaction_kind === "approval_required") throw new WecomError("APPROVAL_INTERACTION_BLOCKED", true);
|
|
1203
|
+
if (!record$1.result.can_reply_in_text) throw new WecomError("UNSUPPORTED_INTERACTION_BLOCKED", true);
|
|
1204
|
+
const { payload, identity } = await this.requestA2A({
|
|
1002
1205
|
method: "POST",
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
}
|
|
1206
|
+
expectedIdentity: record$1.identity,
|
|
1207
|
+
route: { kind: "send" },
|
|
1208
|
+
body: { message: {
|
|
1209
|
+
messageId: replyMessageId,
|
|
1210
|
+
role: "ROLE_USER",
|
|
1211
|
+
taskId,
|
|
1212
|
+
...record$1.context_id ? { contextId: record$1.context_id } : {},
|
|
1213
|
+
parts: [{ text }]
|
|
1214
|
+
} },
|
|
1215
|
+
signal: options?.signal
|
|
1012
1216
|
});
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1217
|
+
let result = this.parseTaskPayload(payload, {
|
|
1218
|
+
request_id: record$1.request_id,
|
|
1219
|
+
action: record$1.action,
|
|
1220
|
+
from_cache: false
|
|
1221
|
+
});
|
|
1222
|
+
await this.saveTaskRecord({
|
|
1223
|
+
task_id: result.task_id,
|
|
1224
|
+
context_id: result.context_id ?? record$1.context_id,
|
|
1225
|
+
identity,
|
|
1226
|
+
action: record$1.action,
|
|
1227
|
+
request_id: record$1.request_id,
|
|
1228
|
+
result
|
|
1229
|
+
});
|
|
1230
|
+
result = await this.pollTask(result, identity, waitSeconds, options);
|
|
1231
|
+
if (record$1.request_id) {
|
|
1232
|
+
const rKey = this.receiptKey(identity, record$1.request_id);
|
|
1233
|
+
const rRaw = asRecord(await this.storage.get(rKey));
|
|
1234
|
+
if (rRaw) {
|
|
1235
|
+
rRaw.status = result.state;
|
|
1236
|
+
rRaw.result = result;
|
|
1237
|
+
rRaw.updated_at_ms = this.clock.now();
|
|
1238
|
+
await this.storage.set(rKey, rRaw);
|
|
1021
1239
|
}
|
|
1022
1240
|
}
|
|
1023
|
-
|
|
1024
|
-
}
|
|
1025
|
-
doc.auth = normalizeAuth(refreshed, this.clock.now());
|
|
1026
|
-
doc.phase = "pending_account";
|
|
1027
|
-
await this.save(doc);
|
|
1028
|
-
await this.fetchAccount(doc, deadlineMonoMs, signal);
|
|
1029
|
-
}
|
|
1030
|
-
cachedWecom(doc) {
|
|
1031
|
-
const nowMs = this.clock.now();
|
|
1032
|
-
if (doc.phase === "ready" && isFresh(doc.auth?.expiresAt, nowMs) && doc.wecom && isFresh(doc.wecom.expires_at_ms, nowMs)) return doc.wecom;
|
|
1033
|
-
return null;
|
|
1241
|
+
return result;
|
|
1242
|
+
});
|
|
1034
1243
|
}
|
|
1035
|
-
async
|
|
1036
|
-
const
|
|
1037
|
-
const
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
if (!force && !forceRefreshAccount) {
|
|
1049
|
-
const cachedAfterLock = this.cachedWecom(doc);
|
|
1050
|
-
if (cachedAfterLock) return cachedAfterLock;
|
|
1051
|
-
}
|
|
1052
|
-
const enterpriseId = doc.account?.enterpriseId;
|
|
1053
|
-
if (typeof enterpriseId !== "string" || !enterpriseId) throw new WecomError("ENTERPRISE_ACCOUNT_REQUIRED", true);
|
|
1054
|
-
const route = `/console/enterprises/${encodeURIComponent(enterpriseId)}/oneid_openapi/exchange-wecom-token`;
|
|
1055
|
-
let exchanged;
|
|
1056
|
-
try {
|
|
1057
|
-
exchanged = await this.requestCloud({
|
|
1058
|
-
method: "POST",
|
|
1059
|
-
path: route,
|
|
1060
|
-
auth: doc.auth,
|
|
1061
|
-
deadlineMonoMs: options?.deadlineMonoMs,
|
|
1062
|
-
signal: options?.signal
|
|
1063
|
-
});
|
|
1064
|
-
} catch (err) {
|
|
1065
|
-
if (err instanceof WecomError && err.code.startsWith("HTTP_403")) throw new WecomError("WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN", true);
|
|
1066
|
-
throw err;
|
|
1244
|
+
async listReceipts(limit = 20) {
|
|
1245
|
+
const max = Math.max(1, Math.min(100, Math.floor(limit)));
|
|
1246
|
+
const items = [];
|
|
1247
|
+
let after;
|
|
1248
|
+
while (items.length < 200) {
|
|
1249
|
+
const page = await this.storage.scan({
|
|
1250
|
+
prefix: RECEIPT_PREFIX,
|
|
1251
|
+
after,
|
|
1252
|
+
limit: 50
|
|
1253
|
+
});
|
|
1254
|
+
for (const entry of page.entries) {
|
|
1255
|
+
const rec = asRecord(entry.value);
|
|
1256
|
+
if (rec && typeof rec.request_id === "string") items.push(rec);
|
|
1067
1257
|
}
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1258
|
+
if (!page.next) break;
|
|
1259
|
+
after = page.next;
|
|
1260
|
+
}
|
|
1261
|
+
items.sort((a, b) => (b.updated_at_ms ?? 0) - (a.updated_at_ms ?? 0));
|
|
1262
|
+
return items.slice(0, max).map((rec) => {
|
|
1263
|
+
const preview = rec.result?.summary ? rec.result.summary.slice(0, 140) : void 0;
|
|
1264
|
+
return {
|
|
1265
|
+
request_id: rec.request_id,
|
|
1266
|
+
action: rec.action,
|
|
1267
|
+
status: rec.status,
|
|
1268
|
+
...rec.task_id ? { task_id: rec.task_id } : {},
|
|
1269
|
+
...preview ? { summary_preview: preview } : {},
|
|
1270
|
+
updated_at_ms: rec.updated_at_ms
|
|
1081
1271
|
};
|
|
1082
|
-
doc.wecom = credential;
|
|
1083
|
-
await this.save(doc);
|
|
1084
|
-
return credential;
|
|
1085
|
-
});
|
|
1086
|
-
}
|
|
1087
|
-
async logout() {
|
|
1088
|
-
return this.lock.run("auth", async () => {
|
|
1089
|
-
await this.storage.remove(AUTH_STORAGE_KEY);
|
|
1090
|
-
const status = await this.status();
|
|
1091
|
-
if (this.onAuthChange) await Promise.resolve(this.onAuthChange(status)).catch(() => {});
|
|
1092
|
-
return status;
|
|
1093
1272
|
});
|
|
1094
1273
|
}
|
|
1095
1274
|
};
|
|
@@ -1151,14 +1330,14 @@ function defaultProcessRunner(binary, args, options) {
|
|
|
1151
1330
|
});
|
|
1152
1331
|
return;
|
|
1153
1332
|
}
|
|
1154
|
-
const record = err;
|
|
1155
|
-
if (record.code === "ENOENT") {
|
|
1156
|
-
reject(record);
|
|
1333
|
+
const record$1 = err;
|
|
1334
|
+
if (record$1.code === "ENOENT") {
|
|
1335
|
+
reject(record$1);
|
|
1157
1336
|
return;
|
|
1158
1337
|
}
|
|
1159
|
-
if (typeof record.code === "number") {
|
|
1338
|
+
if (typeof record$1.code === "number") {
|
|
1160
1339
|
resolve({
|
|
1161
|
-
exitCode: record.code,
|
|
1340
|
+
exitCode: record$1.code,
|
|
1162
1341
|
stdout: stdout ?? "",
|
|
1163
1342
|
stderr: stderr ?? ""
|
|
1164
1343
|
});
|
|
@@ -1259,23 +1438,20 @@ var WecomCliBridge = class {
|
|
|
1259
1438
|
//#region src/index.ts
|
|
1260
1439
|
const EMBEDDED_SKILL_CONTENT = `---
|
|
1261
1440
|
name: wecom-dayuan
|
|
1262
|
-
description:
|
|
1441
|
+
description: 通过大圆只读查询企业微信内部单聊、群聊、消息和近期工作进展;处理首次登录、任务追加授权和查询恢复。文档、日程等办公域按需走可选的企业微信 CLI。
|
|
1263
1442
|
---
|
|
1264
1443
|
|
|
1265
1444
|
# 企业微信(WeCom / 大圆)使用规范
|
|
1266
1445
|
|
|
1267
|
-
## 1.
|
|
1268
|
-
-
|
|
1269
|
-
-
|
|
1270
|
-
-
|
|
1271
|
-
- 若遇到 \`WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN\`,说明企业微信应用尚未在云端授权,请引导用户打开 \`${WECOM_LOGIN_URL}\` 完成授权。
|
|
1446
|
+
## 1. 查询
|
|
1447
|
+
- 已登录时直接调用 \`wecom_read_start\`,无需每次扫码。按群名找群用 \`search_groups\`;有明确会话和问题用 \`read_chat\`(\`chat_name\`、\`question\`);查近期工作或跨会话找消息用 \`search_messages\`(\`query\`、可选 \`time_range\`)。
|
|
1448
|
+
- 例如「我最近在做什么」:查最近 7 天我发出的消息和提到我的消息,汇总项目、进展和待办,请大圆注明会话和日期。拿到 \`task_id\` 后用 \`wecom_read_result\` 查同一任务,直到完成、失败或需要用户处理。仅 \`text_clarification\` 可用 \`wecom_read_reply\` 回复。
|
|
1449
|
+
- 回复时标明内容是大圆摘要,不是聊天原文。没有匹配就如实说明。为原查询保留稳定的 \`request_id\`;遇到 \`SUBMIT_OUTCOME_UNKNOWN\` 不要换 ID 重发。
|
|
1272
1450
|
|
|
1273
|
-
## 2.
|
|
1274
|
-
-
|
|
1275
|
-
-
|
|
1276
|
-
-
|
|
1277
|
-
- 当任务返回 \`interaction_kind === "text_clarification"\` 时,可用 \`wecom_read_reply\` 补充澄清。
|
|
1278
|
-
- 当任务返回 \`interaction_kind === "approval_required"\` 时,**必须停下并告知用户在手机企业微信手动审批**,严禁尝试自动通过。
|
|
1451
|
+
## 2. 登录、追加授权与恢复
|
|
1452
|
+
- 未登录或 WorkBuddy 会话失效:调用 \`wecom_login({ mode: "start" })\`,**在面向用户的正文中贴出返回的 \`authorization_url\`**。请用户用同一企业账号在官方页面完成登录,确认后调用 \`wecom_login({ mode: "wait", wait_seconds: 60 })\`,再查询。不需要安装 WorkBuddy 或企业微信桌面端。
|
|
1453
|
+
- 若结果为 \`authorization_required\`,或报 \`WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN\`,先停下。**每个受阻事项的正文都要附上该结果的授权地址**;优先原样使用 \`authorization_url\`,缺失时调用 \`wecom_login({ mode: "wecom_auth" })\` 获取。请用户确认后调用 \`wecom_login({ mode: "verify_wecom" })\` 验证。已有 \`task_id\` 就继续查询原任务;仅在明确未提交时,才用原参数和原 \`request_id\` 重试。验证仍不通过就说明原因,不循环要求扫码。
|
|
1454
|
+
- \`approval_required\` 是当前任务的审批卡,不是登录或应用追加授权。请用户在企业微信官方界面处理原审批卡;不要拿应用授权链接代替,也不要拼接或转发带审批票据的 deep link、用文本代批或切换通道绕过。
|
|
1279
1455
|
|
|
1280
1456
|
## 3. 结构化办公域(可选)
|
|
1281
1457
|
- 若用户需要查文档、智能表格、日程、会议、邮件、微盘或通讯录,且已安装 \`@wecom/cli\`,可调用 \`wecom_cli\`(默认仅允许只读子命令)。
|
|
@@ -1294,7 +1470,8 @@ function formatErrorHint(err) {
|
|
|
1294
1470
|
case "LOGIN_REQUIRED":
|
|
1295
1471
|
case "WECOM_TOKEN_REJECTED_LOGIN_REQUIRED": return `${code}: 当前未登录或凭据已失效,请运行 /wecom-login 或调用 wecom_login({ mode: "start" }) 扫码登录。`;
|
|
1296
1472
|
case "REFRESH_OUTCOME_UNKNOWN_LOGIN_REQUIRED": return `${code}: 上一次续期请求网络状态不确定,为避免重放一次性 refresh_token 已中止自动续期,请重新扫码登录。`;
|
|
1297
|
-
case "WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN": return `${code}:
|
|
1473
|
+
case "WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN": return `${code}: 企业微信授权未完成或已失效。请用同一企业账号在官方页面 ${WECOM_LOGIN_URL} 确认,再运行 wecom_login({ mode: "verify_wecom" }) 检查。`;
|
|
1474
|
+
case "DAYUAN_NOT_AVAILABLE": return `${code}: 当前账号的 WorkBuddy 服务未提供可用的大圆接口;请确认企业开通及账号权限。`;
|
|
1298
1475
|
case "ENTERPRISE_ACCOUNT_REQUIRED": return `${code}: 当前账号缺少企业 ID,请使用企业微信企业账号登录。`;
|
|
1299
1476
|
case "APPROVAL_INTERACTION_BLOCKED": return `${code}: 该任务触发了企业微信敏感审批卡片,插件严禁代批,请用户在手机企业微信手动处理。`;
|
|
1300
1477
|
case "WECOM_CLI_NOT_INSTALLED": return `${code}: 未检测到 @wecom/cli。如需使用文档/日程/会议等办公域能力,请先执行 npm install -g @wecom/cli。`;
|
|
@@ -1306,8 +1483,22 @@ function formatTaskSummaryText(result) {
|
|
|
1306
1483
|
const lines = [`状态: ${result.state} | 任务 ID: ${result.task_id}${result.from_cache ? " (缓存)" : ""}`, "说明: 以下内容由大圆 A2A 生成,属于只读摘要而非逐字原始记录。"];
|
|
1307
1484
|
if (result.summary) lines.push("", result.summary);
|
|
1308
1485
|
if (result.guidance) lines.push("", `提示: ${result.guidance}`);
|
|
1486
|
+
if (result.authorization_url) lines.push("", `授权地址: ${result.authorization_url}`);
|
|
1309
1487
|
return lines.join("\n");
|
|
1310
1488
|
}
|
|
1489
|
+
function dayuanAuthorizationResult(err, taskId) {
|
|
1490
|
+
if (!(err instanceof WecomError) || err.code !== "WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN") throw new Error(formatErrorHint(err));
|
|
1491
|
+
return {
|
|
1492
|
+
output: {
|
|
1493
|
+
...taskId ? { task_id: taskId } : {},
|
|
1494
|
+
state: "auth_required",
|
|
1495
|
+
interaction_kind: "authorization_required",
|
|
1496
|
+
human_action_required: true,
|
|
1497
|
+
authorization_url: WECOM_LOGIN_URL
|
|
1498
|
+
},
|
|
1499
|
+
content: formatErrorHint(err)
|
|
1500
|
+
};
|
|
1501
|
+
}
|
|
1311
1502
|
function formatStatusText(status, cliAvailable, receiptCount) {
|
|
1312
1503
|
const lines = [
|
|
1313
1504
|
`WeCom 登录状态: ${status.phase}`,
|
|
@@ -1328,6 +1519,8 @@ const DAYUAN_TASK_RESULT_OUTPUT_SCHEMA = {
|
|
|
1328
1519
|
summary: { type: "string" },
|
|
1329
1520
|
interaction_kind: { type: "string" },
|
|
1330
1521
|
guidance: { type: "string" },
|
|
1522
|
+
authorization_url: { type: "string" },
|
|
1523
|
+
human_action_required: { type: "boolean" },
|
|
1331
1524
|
raw_parts_count: { type: "number" },
|
|
1332
1525
|
from_cache: { type: "boolean" }
|
|
1333
1526
|
},
|
|
@@ -1378,6 +1571,13 @@ function createWecomPlugin(deps) {
|
|
|
1378
1571
|
async startLogin(_input, callCtx) {
|
|
1379
1572
|
return auth.start({ signal: callCtx.signal });
|
|
1380
1573
|
},
|
|
1574
|
+
async verifyWecom(_input, callCtx) {
|
|
1575
|
+
try {
|
|
1576
|
+
return { auth: await auth.verifyWecom(callCtx.signal) };
|
|
1577
|
+
} catch (err) {
|
|
1578
|
+
throw new Error(formatErrorHint(err));
|
|
1579
|
+
}
|
|
1580
|
+
},
|
|
1381
1581
|
async finishLogin(input, callCtx) {
|
|
1382
1582
|
const raw = input;
|
|
1383
1583
|
const waitSeconds = typeof raw?.wait_seconds === "number" ? raw.wait_seconds : 0;
|
|
@@ -1477,9 +1677,10 @@ function createWecomPlugin(deps) {
|
|
|
1477
1677
|
"finish",
|
|
1478
1678
|
"wait",
|
|
1479
1679
|
"wecom_auth",
|
|
1680
|
+
"verify_wecom",
|
|
1480
1681
|
"logout"
|
|
1481
1682
|
],
|
|
1482
|
-
description: "start: create/reuse QR login URL; finish: single poll check; wait: poll until scan completes and exchange WeCom token; wecom_auth: return
|
|
1683
|
+
description: "start: create/reuse QR login URL; finish: single poll check; wait: poll until scan completes and exchange WeCom token; wecom_auth: return official authorization URL; verify_wecom: recheck user authorization and Dayuan ticket after user confirmation; logout: clear stored credentials."
|
|
1483
1684
|
},
|
|
1484
1685
|
wait_seconds: {
|
|
1485
1686
|
type: "number",
|
|
@@ -1522,6 +1723,10 @@ function createWecomPlugin(deps) {
|
|
|
1522
1723
|
content: `请在浏览器打开以下企业微信应用授权链接并确认:\n${info.authorization_url}`
|
|
1523
1724
|
};
|
|
1524
1725
|
}
|
|
1726
|
+
if (mode === "verify_wecom") return {
|
|
1727
|
+
output: { auth: await auth.verifyWecom(toolCtx.signal) },
|
|
1728
|
+
content: "企业微信授权和大圆专用票据已验证,尚未发起聊天查询。"
|
|
1729
|
+
};
|
|
1525
1730
|
if (mode === "logout") return {
|
|
1526
1731
|
output: { auth: await auth.logout() },
|
|
1527
1732
|
content: "已清除本机保存的 WorkBuddy / 企业微信登录凭据。"
|
|
@@ -1661,7 +1866,7 @@ function createWecomPlugin(deps) {
|
|
|
1661
1866
|
content: formatTaskSummaryText(result)
|
|
1662
1867
|
};
|
|
1663
1868
|
} catch (err) {
|
|
1664
|
-
|
|
1869
|
+
return dayuanAuthorizationResult(err);
|
|
1665
1870
|
}
|
|
1666
1871
|
}
|
|
1667
1872
|
});
|
|
@@ -1709,7 +1914,7 @@ function createWecomPlugin(deps) {
|
|
|
1709
1914
|
content: formatTaskSummaryText(result)
|
|
1710
1915
|
};
|
|
1711
1916
|
} catch (err) {
|
|
1712
|
-
|
|
1917
|
+
return dayuanAuthorizationResult(err, input.task_id);
|
|
1713
1918
|
}
|
|
1714
1919
|
}
|
|
1715
1920
|
});
|
|
@@ -1762,7 +1967,7 @@ function createWecomPlugin(deps) {
|
|
|
1762
1967
|
content: formatTaskSummaryText(result)
|
|
1763
1968
|
};
|
|
1764
1969
|
} catch (err) {
|
|
1765
|
-
|
|
1970
|
+
return dayuanAuthorizationResult(err, input.task_id);
|
|
1766
1971
|
}
|
|
1767
1972
|
}
|
|
1768
1973
|
});
|