opencode-plugin-wecom 0.1.0 → 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 +1135 -856
- 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
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
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");
|
|
399
|
+
}
|
|
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
|
+
}
|
|
411
|
+
};
|
|
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);
|
|
435
|
+
}
|
|
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
|
|
472
|
+
};
|
|
473
|
+
});
|
|
474
|
+
}
|
|
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
|
|
481
|
+
});
|
|
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
|
|
470
489
|
});
|
|
471
490
|
}
|
|
472
|
-
|
|
491
|
+
if (result.phase === "ready" && options.exchangeWecom !== false) await this.ensureWecom({
|
|
492
|
+
signal: options.signal,
|
|
493
|
+
deadlineMonoMs
|
|
494
|
+
});
|
|
495
|
+
return this.status();
|
|
473
496
|
}
|
|
474
|
-
async
|
|
475
|
-
const
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
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);
|
|
500
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
|
+
}
|
|
534
|
+
}
|
|
535
|
+
throw err;
|
|
536
|
+
}
|
|
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);
|
|
541
|
+
}
|
|
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;
|
|
501
563
|
}
|
|
502
|
-
const
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
};
|
|
512
|
-
|
|
513
|
-
let payload;
|
|
514
|
-
let identity;
|
|
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({
|
|
568
|
+
method: "POST",
|
|
569
|
+
path: route,
|
|
570
|
+
auth: doc.auth,
|
|
571
|
+
deadlineMonoMs: options?.deadlineMonoMs,
|
|
572
|
+
signal: options?.signal
|
|
573
|
+
});
|
|
574
|
+
let exchanged;
|
|
515
575
|
try {
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
body: { message: {
|
|
520
|
-
messageId: requestId,
|
|
521
|
-
role: "user",
|
|
522
|
-
parts: [{
|
|
523
|
-
kind: "text",
|
|
524
|
-
text: prompt
|
|
525
|
-
}]
|
|
526
|
-
} },
|
|
527
|
-
signal: options?.signal
|
|
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;
|
|
528
579
|
});
|
|
529
|
-
payload = res.payload;
|
|
530
|
-
identity = res.identity;
|
|
531
580
|
} catch (err) {
|
|
532
|
-
if (
|
|
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);
|
|
591
|
+
}
|
|
533
592
|
throw err;
|
|
534
593
|
}
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
request_id: requestId,
|
|
546
|
-
result
|
|
547
|
-
});
|
|
548
|
-
result = await this.pollTask(result, identity, waitSeconds, options);
|
|
549
|
-
const finalized = {
|
|
550
|
-
...pendingReceipt,
|
|
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,
|
|
551
604
|
identity,
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
context_id: result.context_id,
|
|
555
|
-
result,
|
|
556
|
-
updated_at_ms: this.clock.now()
|
|
605
|
+
expires_at_ms: this.clock.now() + expiresIn * 1e3,
|
|
606
|
+
source: "workbuddy_cloud"
|
|
557
607
|
};
|
|
558
|
-
|
|
559
|
-
|
|
608
|
+
doc.wecom = credential;
|
|
609
|
+
await this.save(doc);
|
|
610
|
+
return credential;
|
|
560
611
|
});
|
|
561
612
|
}
|
|
562
|
-
async
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
if (existing && isTerminalState(existing.result.state)) return {
|
|
567
|
-
...existing.result,
|
|
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
|
|
613
|
+
async verifyWecom(signal) {
|
|
614
|
+
await this.ensureWecom({
|
|
615
|
+
force: true,
|
|
616
|
+
signal
|
|
582
617
|
});
|
|
583
|
-
await this.
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
identity,
|
|
587
|
-
action: existing?.action,
|
|
588
|
-
request_id: existing?.request_id,
|
|
589
|
-
result
|
|
618
|
+
await this.ensureDayuan({
|
|
619
|
+
force: true,
|
|
620
|
+
signal
|
|
590
621
|
});
|
|
591
|
-
|
|
592
|
-
if (existing?.request_id) {
|
|
593
|
-
const rKey = this.receiptKey(identity, existing.request_id);
|
|
594
|
-
const rRaw = asRecord(await this.storage.get(rKey));
|
|
595
|
-
if (rRaw) {
|
|
596
|
-
rRaw.status = result.state;
|
|
597
|
-
rRaw.result = result;
|
|
598
|
-
rRaw.updated_at_ms = this.clock.now();
|
|
599
|
-
await this.storage.set(rKey, rRaw);
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
return result;
|
|
622
|
+
return this.status();
|
|
603
623
|
}
|
|
604
|
-
async
|
|
605
|
-
const
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
if (!
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
if (
|
|
621
|
-
const
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
from_cache: false
|
|
640
|
-
});
|
|
641
|
-
await this.saveTaskRecord({
|
|
642
|
-
task_id: result.task_id,
|
|
643
|
-
context_id: result.context_id ?? record.context_id,
|
|
644
|
-
identity,
|
|
645
|
-
action: record.action,
|
|
646
|
-
request_id: record.request_id,
|
|
647
|
-
result
|
|
648
|
-
});
|
|
649
|
-
result = await this.pollTask(result, identity, waitSeconds, options);
|
|
650
|
-
if (record.request_id) {
|
|
651
|
-
const rKey = this.receiptKey(identity, record.request_id);
|
|
652
|
-
const rRaw = asRecord(await this.storage.get(rKey));
|
|
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);
|
|
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);
|
|
658
659
|
}
|
|
659
|
-
|
|
660
|
-
|
|
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
|
|
688
|
+
};
|
|
689
|
+
return this.dayuan;
|
|
661
690
|
});
|
|
662
691
|
}
|
|
663
|
-
async
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
after,
|
|
671
|
-
limit: 50
|
|
672
|
-
});
|
|
673
|
-
for (const entry of page.entries) {
|
|
674
|
-
const rec = asRecord(entry.value);
|
|
675
|
-
if (rec && typeof rec.request_id === "string") items.push(rec);
|
|
676
|
-
}
|
|
677
|
-
if (!page.next) break;
|
|
678
|
-
after = page.next;
|
|
679
|
-
}
|
|
680
|
-
items.sort((a, b) => (b.updated_at_ms ?? 0) - (a.updated_at_ms ?? 0));
|
|
681
|
-
return items.slice(0, max).map((rec) => {
|
|
682
|
-
const preview = rec.result?.summary ? rec.result.summary.slice(0, 140) : void 0;
|
|
683
|
-
return {
|
|
684
|
-
request_id: rec.request_id,
|
|
685
|
-
action: rec.action,
|
|
686
|
-
status: rec.status,
|
|
687
|
-
...rec.task_id ? { task_id: rec.task_id } : {},
|
|
688
|
-
...preview ? { summary_preview: preview } : {},
|
|
689
|
-
updated_at_ms: rec.updated_at_ms
|
|
690
|
-
};
|
|
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
871
|
}
|
|
798
|
-
|
|
799
|
-
|
|
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;
|
|
872
|
+
receiptKey(identity, requestId) {
|
|
873
|
+
return `${RECEIPT_PREFIX}${identity}/${requestId}`;
|
|
851
874
|
}
|
|
852
|
-
|
|
853
|
-
return
|
|
875
|
+
taskKey(taskId) {
|
|
876
|
+
return `${TASK_PREFIX}${taskId}`;
|
|
854
877
|
}
|
|
855
|
-
|
|
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
|
-
authorization_url: refreshedUrl
|
|
872
|
-
};
|
|
873
|
-
}
|
|
874
|
-
const data = await this.requestCloud({
|
|
875
|
-
method: "POST",
|
|
876
|
-
path: `${WORKBUDDY_PREFIX}/auth/state?platform=workbuddy`,
|
|
877
|
-
signal: options?.signal
|
|
878
|
-
});
|
|
879
|
-
const state = data.state;
|
|
880
|
-
const authUrl = data.authUrl;
|
|
881
|
-
let parsed;
|
|
882
|
-
try {
|
|
883
|
-
if (typeof authUrl !== "string") throw new Error("not string");
|
|
884
|
-
parsed = new URL(authUrl);
|
|
885
|
-
} catch {
|
|
886
|
-
throw new WecomError("UNEXPECTED_LOGIN_URL");
|
|
887
|
-
}
|
|
888
|
-
if (parsed.origin !== WORKBUDDY_ORIGIN || parsed.pathname !== "/login" || parsed.hash) throw new WecomError("UNEXPECTED_LOGIN_URL");
|
|
889
|
-
if (typeof state !== "string" || !state || parsed.searchParams.get("state") !== state) throw new WecomError("INVALID_LOGIN_STATE");
|
|
890
|
-
const url = formatLoginUrl(authUrl);
|
|
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);
|
|
901
|
-
return {
|
|
902
|
-
phase: "pending_token",
|
|
903
|
-
authorization_url: url
|
|
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}`
|
|
904
938
|
};
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
await this.save(doc);
|
|
922
|
-
throw new WecomError("ACCOUNT_CHANGED_USE_SEPARATE_STATE", true);
|
|
923
|
-
}
|
|
924
|
-
}
|
|
925
|
-
doc.account = account;
|
|
926
|
-
doc.phase = "ready";
|
|
927
|
-
delete doc.pending;
|
|
928
|
-
await this.save(doc);
|
|
929
|
-
}
|
|
930
|
-
async finish(options) {
|
|
931
|
-
return this.lock.run("auth", async () => {
|
|
932
|
-
const doc = await this.load();
|
|
933
|
-
if (doc.phase === "pending_token") {
|
|
934
|
-
if (!doc.pending?.state) throw new WecomError("LOGIN_REQUIRED", true);
|
|
935
|
-
try {
|
|
936
|
-
doc.auth = normalizeAuth(await this.requestCloud({
|
|
937
|
-
method: "GET",
|
|
938
|
-
path: `${WORKBUDDY_PREFIX}/auth/token?state=${encodeURIComponent(doc.pending.state)}`,
|
|
939
|
-
deadlineMonoMs: options?.deadlineMonoMs,
|
|
940
|
-
signal: options?.signal
|
|
941
|
-
}), this.clock.now());
|
|
942
|
-
doc.phase = "pending_account";
|
|
943
|
-
await this.save(doc);
|
|
944
|
-
} catch (err) {
|
|
945
|
-
if (err instanceof WecomError && err.code.startsWith("PENDING_")) return { phase: "pending_token" };
|
|
946
|
-
throw err;
|
|
947
|
-
}
|
|
948
|
-
}
|
|
949
|
-
if (doc.phase === "pending_account") try {
|
|
950
|
-
await this.fetchAccount(doc, options?.deadlineMonoMs, options?.signal);
|
|
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
|
|
949
|
+
});
|
|
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;
|
|
951
955
|
} catch (err) {
|
|
952
|
-
if (
|
|
953
|
-
|
|
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");
|
|
954
965
|
}
|
|
955
|
-
|
|
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);
|
|
956
969
|
return {
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
970
|
+
status: response.status,
|
|
971
|
+
errcode,
|
|
972
|
+
agentCode,
|
|
973
|
+
parsed,
|
|
974
|
+
isAuthFailure
|
|
960
975
|
};
|
|
961
|
-
}
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
signal: options.signal,
|
|
968
|
-
deadlineMonoMs
|
|
969
|
-
});
|
|
970
|
-
while (result.phase !== "ready" && this.clock.monotonic() < deadlineMonoMs) {
|
|
971
|
-
const remaining = deadlineMonoMs - this.clock.monotonic();
|
|
972
|
-
await this.clock.sleep(Math.min(LOGIN_POLL_INTERVAL_MS, remaining), options.signal);
|
|
973
|
-
if (this.clock.monotonic() >= deadlineMonoMs) break;
|
|
974
|
-
result = await this.finish({
|
|
975
|
-
signal: options.signal,
|
|
976
|
-
deadlineMonoMs
|
|
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
|
|
977
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);
|
|
978
986
|
}
|
|
979
|
-
if (
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
}
|
|
985
|
-
async refreshAccount(doc, deadlineMonoMs, signal) {
|
|
986
|
-
const refreshToken = doc.auth?.refreshToken;
|
|
987
|
-
if (!refreshToken) {
|
|
988
|
-
doc.phase = "login_required";
|
|
989
|
-
await this.save(doc);
|
|
990
|
-
throw new WecomError("LOGIN_REQUIRED_NO_REFRESH_TOKEN", true);
|
|
991
|
-
}
|
|
992
|
-
const refreshExp = parseDeadline(doc.auth?.refreshExpiresAt);
|
|
993
|
-
if (refreshExp && refreshExp <= this.clock.now()) {
|
|
994
|
-
doc.phase = "login_required";
|
|
995
|
-
await this.save(doc);
|
|
996
|
-
throw new WecomError("LOGIN_REQUIRED_REFRESH_EXPIRED", true);
|
|
997
|
-
}
|
|
998
|
-
const previousPhase = doc.phase;
|
|
999
|
-
let refreshed;
|
|
1000
|
-
try {
|
|
1001
|
-
refreshed = await this.requestCloud({
|
|
1002
|
-
method: "POST",
|
|
1003
|
-
path: `${WORKBUDDY_PREFIX}/auth/token/refresh`,
|
|
1004
|
-
auth: doc.auth,
|
|
1005
|
-
refreshToken,
|
|
1006
|
-
deadlineMonoMs,
|
|
1007
|
-
signal,
|
|
1008
|
-
beforeSend: async () => {
|
|
1009
|
-
doc.phase = "refresh_unknown";
|
|
1010
|
-
await this.save(doc);
|
|
1011
|
-
}
|
|
1012
|
-
});
|
|
1013
|
-
} catch (err) {
|
|
1014
|
-
if (err instanceof WecomError) {
|
|
1015
|
-
if (err.code.startsWith("HTTP_401") || err.code.startsWith("HTTP_403")) {
|
|
1016
|
-
doc.phase = "login_required";
|
|
1017
|
-
await this.save(doc);
|
|
1018
|
-
} else if (err.code === "TRANSPORT_NOT_SENT" && doc.phase === "refresh_unknown") {
|
|
1019
|
-
doc.phase = previousPhase;
|
|
1020
|
-
await this.save(doc);
|
|
1021
|
-
}
|
|
1022
|
-
}
|
|
1023
|
-
throw err;
|
|
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}`}`);
|
|
1024
992
|
}
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
993
|
+
if (attempt.errcode !== 0) throw new WecomError(`A2A_ERRCODE_${attempt.errcode}`);
|
|
994
|
+
return {
|
|
995
|
+
payload: attempt.parsed,
|
|
996
|
+
identity: credential.identity
|
|
997
|
+
};
|
|
1029
998
|
}
|
|
1030
|
-
|
|
1031
|
-
|
|
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;
|
|
999
|
+
async saveTaskRecord(record$1) {
|
|
1000
|
+
await this.storage.set(this.taskKey(record$1.task_id), record$1);
|
|
1034
1001
|
}
|
|
1035
|
-
async
|
|
1036
|
-
const
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
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
|
+
});
|
|
1041
1051
|
}
|
|
1042
|
-
return
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1052
|
+
return current;
|
|
1053
|
+
}
|
|
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;
|
|
1080
|
+
}
|
|
1051
1081
|
}
|
|
1052
|
-
const
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
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;
|
|
1056
1095
|
try {
|
|
1057
|
-
|
|
1096
|
+
const res = await this.requestA2A({
|
|
1058
1097
|
method: "POST",
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1098
|
+
expectedIdentity: credential.identity,
|
|
1099
|
+
route: { kind: "send" },
|
|
1100
|
+
body: { message: {
|
|
1101
|
+
messageId: requestId,
|
|
1102
|
+
role: "ROLE_USER",
|
|
1103
|
+
parts: [{ text: prompt }]
|
|
1104
|
+
} },
|
|
1062
1105
|
signal: options?.signal
|
|
1063
1106
|
});
|
|
1107
|
+
payload = res.payload;
|
|
1108
|
+
identity = res.identity;
|
|
1064
1109
|
} catch (err) {
|
|
1065
|
-
if (err instanceof WecomError && err.code
|
|
1110
|
+
if (err instanceof WecomError && (err.code === "TRANSPORT_NOT_SENT" || err.definitive)) await this.storage.remove(receiptKey);
|
|
1066
1111
|
throw err;
|
|
1067
1112
|
}
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
const credential = {
|
|
1077
|
-
access_token: accessToken,
|
|
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,
|
|
1078
1121
|
identity,
|
|
1079
|
-
|
|
1080
|
-
|
|
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()
|
|
1081
1135
|
};
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
return credential;
|
|
1136
|
+
await this.storage.set(receiptKey, finalized);
|
|
1137
|
+
return result;
|
|
1085
1138
|
});
|
|
1086
1139
|
}
|
|
1087
|
-
async
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
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
|
+
};
|
|
1151
|
+
}
|
|
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
|
|
1160
|
+
});
|
|
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
|
+
}
|
|
1184
|
+
}
|
|
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({
|
|
1205
|
+
method: "POST",
|
|
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
|
|
1216
|
+
});
|
|
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);
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
return result;
|
|
1242
|
+
});
|
|
1243
|
+
}
|
|
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);
|
|
1257
|
+
}
|
|
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
|
|
1271
|
+
};
|
|
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}`,
|
|
@@ -1319,6 +1510,22 @@ function formatStatusText(status, cliAvailable, receiptCount) {
|
|
|
1319
1510
|
if (status.phase !== "ready") lines.push("提示: 运行 /wecom-login 获取手机企微扫码链接。");
|
|
1320
1511
|
return lines.join("\n");
|
|
1321
1512
|
}
|
|
1513
|
+
const DAYUAN_TASK_RESULT_OUTPUT_SCHEMA = {
|
|
1514
|
+
type: "object",
|
|
1515
|
+
properties: {
|
|
1516
|
+
task_id: { type: "string" },
|
|
1517
|
+
state: { type: "string" },
|
|
1518
|
+
is_summary: { type: "boolean" },
|
|
1519
|
+
summary: { type: "string" },
|
|
1520
|
+
interaction_kind: { type: "string" },
|
|
1521
|
+
guidance: { type: "string" },
|
|
1522
|
+
authorization_url: { type: "string" },
|
|
1523
|
+
human_action_required: { type: "boolean" },
|
|
1524
|
+
raw_parts_count: { type: "number" },
|
|
1525
|
+
from_cache: { type: "boolean" }
|
|
1526
|
+
},
|
|
1527
|
+
additionalProperties: true
|
|
1528
|
+
};
|
|
1322
1529
|
function createWecomPlugin(deps) {
|
|
1323
1530
|
return Plugin.define({
|
|
1324
1531
|
id: PLUGIN_ID,
|
|
@@ -1364,6 +1571,13 @@ function createWecomPlugin(deps) {
|
|
|
1364
1571
|
async startLogin(_input, callCtx) {
|
|
1365
1572
|
return auth.start({ signal: callCtx.signal });
|
|
1366
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
|
+
},
|
|
1367
1581
|
async finishLogin(input, callCtx) {
|
|
1368
1582
|
const raw = input;
|
|
1369
1583
|
const waitSeconds = typeof raw?.wait_seconds === "number" ? raw.wait_seconds : 0;
|
|
@@ -1406,6 +1620,28 @@ function createWecomPlugin(deps) {
|
|
|
1406
1620
|
} },
|
|
1407
1621
|
additionalProperties: false
|
|
1408
1622
|
},
|
|
1623
|
+
output: {
|
|
1624
|
+
type: "object",
|
|
1625
|
+
properties: {
|
|
1626
|
+
auth: {
|
|
1627
|
+
type: "object",
|
|
1628
|
+
additionalProperties: true
|
|
1629
|
+
},
|
|
1630
|
+
wecom_auth_url: { type: "string" },
|
|
1631
|
+
cli: {
|
|
1632
|
+
type: "object",
|
|
1633
|
+
additionalProperties: true
|
|
1634
|
+
},
|
|
1635
|
+
recent_receipts: {
|
|
1636
|
+
type: "array",
|
|
1637
|
+
items: {
|
|
1638
|
+
type: "object",
|
|
1639
|
+
additionalProperties: true
|
|
1640
|
+
}
|
|
1641
|
+
}
|
|
1642
|
+
},
|
|
1643
|
+
additionalProperties: true
|
|
1644
|
+
},
|
|
1409
1645
|
options: {
|
|
1410
1646
|
namespace: "wecom",
|
|
1411
1647
|
codemode: true
|
|
@@ -1441,9 +1677,10 @@ function createWecomPlugin(deps) {
|
|
|
1441
1677
|
"finish",
|
|
1442
1678
|
"wait",
|
|
1443
1679
|
"wecom_auth",
|
|
1680
|
+
"verify_wecom",
|
|
1444
1681
|
"logout"
|
|
1445
1682
|
],
|
|
1446
|
-
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."
|
|
1447
1684
|
},
|
|
1448
1685
|
wait_seconds: {
|
|
1449
1686
|
type: "number",
|
|
@@ -1452,6 +1689,25 @@ function createWecomPlugin(deps) {
|
|
|
1452
1689
|
},
|
|
1453
1690
|
additionalProperties: false
|
|
1454
1691
|
},
|
|
1692
|
+
output: {
|
|
1693
|
+
type: "object",
|
|
1694
|
+
properties: {
|
|
1695
|
+
authorization_url: { type: "string" },
|
|
1696
|
+
state: { type: "string" },
|
|
1697
|
+
expires_in_seconds: { type: "number" },
|
|
1698
|
+
desktop_required: { type: "boolean" },
|
|
1699
|
+
reused: { type: "boolean" },
|
|
1700
|
+
auth: {
|
|
1701
|
+
type: "object",
|
|
1702
|
+
additionalProperties: true
|
|
1703
|
+
},
|
|
1704
|
+
result: {
|
|
1705
|
+
type: "object",
|
|
1706
|
+
additionalProperties: true
|
|
1707
|
+
}
|
|
1708
|
+
},
|
|
1709
|
+
additionalProperties: true
|
|
1710
|
+
},
|
|
1455
1711
|
options: {
|
|
1456
1712
|
namespace: "wecom",
|
|
1457
1713
|
codemode: true
|
|
@@ -1467,6 +1723,10 @@ function createWecomPlugin(deps) {
|
|
|
1467
1723
|
content: `请在浏览器打开以下企业微信应用授权链接并确认:\n${info.authorization_url}`
|
|
1468
1724
|
};
|
|
1469
1725
|
}
|
|
1726
|
+
if (mode === "verify_wecom") return {
|
|
1727
|
+
output: { auth: await auth.verifyWecom(toolCtx.signal) },
|
|
1728
|
+
content: "企业微信授权和大圆专用票据已验证,尚未发起聊天查询。"
|
|
1729
|
+
};
|
|
1470
1730
|
if (mode === "logout") return {
|
|
1471
1731
|
output: { auth: await auth.logout() },
|
|
1472
1732
|
content: "已清除本机保存的 WorkBuddy / 企业微信登录凭据。"
|
|
@@ -1557,6 +1817,7 @@ function createWecomPlugin(deps) {
|
|
|
1557
1817
|
required: ["action"],
|
|
1558
1818
|
additionalProperties: false
|
|
1559
1819
|
},
|
|
1820
|
+
output: DAYUAN_TASK_RESULT_OUTPUT_SCHEMA,
|
|
1560
1821
|
options: {
|
|
1561
1822
|
namespace: "wecom",
|
|
1562
1823
|
codemode: true
|
|
@@ -1605,7 +1866,7 @@ function createWecomPlugin(deps) {
|
|
|
1605
1866
|
content: formatTaskSummaryText(result)
|
|
1606
1867
|
};
|
|
1607
1868
|
} catch (err) {
|
|
1608
|
-
|
|
1869
|
+
return dayuanAuthorizationResult(err);
|
|
1609
1870
|
}
|
|
1610
1871
|
}
|
|
1611
1872
|
});
|
|
@@ -1627,6 +1888,7 @@ function createWecomPlugin(deps) {
|
|
|
1627
1888
|
required: ["task_id"],
|
|
1628
1889
|
additionalProperties: false
|
|
1629
1890
|
},
|
|
1891
|
+
output: DAYUAN_TASK_RESULT_OUTPUT_SCHEMA,
|
|
1630
1892
|
options: {
|
|
1631
1893
|
namespace: "wecom",
|
|
1632
1894
|
codemode: true
|
|
@@ -1652,7 +1914,7 @@ function createWecomPlugin(deps) {
|
|
|
1652
1914
|
content: formatTaskSummaryText(result)
|
|
1653
1915
|
};
|
|
1654
1916
|
} catch (err) {
|
|
1655
|
-
|
|
1917
|
+
return dayuanAuthorizationResult(err, input.task_id);
|
|
1656
1918
|
}
|
|
1657
1919
|
}
|
|
1658
1920
|
});
|
|
@@ -1682,6 +1944,7 @@ function createWecomPlugin(deps) {
|
|
|
1682
1944
|
required: ["task_id", "text"],
|
|
1683
1945
|
additionalProperties: false
|
|
1684
1946
|
},
|
|
1947
|
+
output: DAYUAN_TASK_RESULT_OUTPUT_SCHEMA,
|
|
1685
1948
|
options: {
|
|
1686
1949
|
namespace: "wecom",
|
|
1687
1950
|
codemode: true
|
|
@@ -1704,7 +1967,7 @@ function createWecomPlugin(deps) {
|
|
|
1704
1967
|
content: formatTaskSummaryText(result)
|
|
1705
1968
|
};
|
|
1706
1969
|
} catch (err) {
|
|
1707
|
-
|
|
1970
|
+
return dayuanAuthorizationResult(err, input.task_id);
|
|
1708
1971
|
}
|
|
1709
1972
|
}
|
|
1710
1973
|
});
|
|
@@ -1732,6 +1995,22 @@ function createWecomPlugin(deps) {
|
|
|
1732
1995
|
required: ["domain", "args"],
|
|
1733
1996
|
additionalProperties: false
|
|
1734
1997
|
},
|
|
1998
|
+
output: {
|
|
1999
|
+
type: "object",
|
|
2000
|
+
properties: {
|
|
2001
|
+
ok: { type: "boolean" },
|
|
2002
|
+
domain: { type: "string" },
|
|
2003
|
+
args: {
|
|
2004
|
+
type: "array",
|
|
2005
|
+
items: { type: "string" }
|
|
2006
|
+
},
|
|
2007
|
+
exit_code: { type: "number" },
|
|
2008
|
+
stdout: { type: "string" },
|
|
2009
|
+
stderr: { type: "string" },
|
|
2010
|
+
data: {}
|
|
2011
|
+
},
|
|
2012
|
+
additionalProperties: true
|
|
2013
|
+
},
|
|
1735
2014
|
options: {
|
|
1736
2015
|
namespace: "wecom",
|
|
1737
2016
|
codemode: true
|