opencode-plugin-wecom 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1901 @@
1
+ import { n as WecomRpc, t as PLUGIN_ID } from "./rpc-CDRXKJwO.js";
2
+ import { Plugin } from "@opencode/plugin";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { execFile } from "node:child_process";
5
+
6
+ //#region src/types.ts
7
+ var WecomError = class extends Error {
8
+ code;
9
+ definitive;
10
+ constructor(code, definitive = false) {
11
+ super(code);
12
+ this.name = "WecomError";
13
+ this.code = code;
14
+ this.definitive = definitive;
15
+ }
16
+ };
17
+ const systemClock = {
18
+ now: () => Date.now(),
19
+ monotonic: () => performance.now(),
20
+ sleep: (ms, signal) => new Promise((resolve, reject) => {
21
+ if (signal?.aborted) {
22
+ reject(new WecomError("ABORTED"));
23
+ return;
24
+ }
25
+ const timer = setTimeout(() => {
26
+ signal?.removeEventListener("abort", onAbort);
27
+ resolve();
28
+ }, Math.max(0, ms));
29
+ const onAbort = () => {
30
+ clearTimeout(timer);
31
+ reject(new WecomError("ABORTED"));
32
+ };
33
+ signal?.addEventListener("abort", onAbort, { once: true });
34
+ })
35
+ };
36
+ function hasControlOrSpaceChar(value) {
37
+ for (let i = 0; i < value.length; i += 1) {
38
+ const code = value.charCodeAt(i);
39
+ if (code <= 32 || code === 127) return true;
40
+ }
41
+ return false;
42
+ }
43
+ function hasControlChar(value, options) {
44
+ const allowWhitespace = options?.allowWhitespace ?? false;
45
+ for (let i = 0; i < value.length; i += 1) {
46
+ const code = value.charCodeAt(i);
47
+ if (code === 127) return true;
48
+ if (code < 32) {
49
+ if (allowWhitespace && (code === 9 || code === 10 || code === 13)) continue;
50
+ return true;
51
+ }
52
+ }
53
+ return false;
54
+ }
55
+ /**
56
+ * Simple in-process async mutex keyed by string to prevent concurrent renewals or duplicate submits.
57
+ */
58
+ var AsyncKeyLock = class {
59
+ queues = /* @__PURE__ */ new Map();
60
+ async run(key, fn) {
61
+ const previous = this.queues.get(key) ?? Promise.resolve();
62
+ let release;
63
+ const current = new Promise((resolve) => {
64
+ release = resolve;
65
+ });
66
+ const next = previous.then(() => current);
67
+ this.queues.set(key, next);
68
+ await previous;
69
+ try {
70
+ return await fn();
71
+ } finally {
72
+ release();
73
+ if (this.queues.get(key) === next) this.queues.delete(key);
74
+ }
75
+ }
76
+ };
77
+
78
+ //#endregion
79
+ //#region src/http.ts
80
+ const PRE_SEND_ERRNO = new Set([
81
+ "ENOTFOUND",
82
+ "EAI_AGAIN",
83
+ "ECONNREFUSED",
84
+ "EHOSTUNREACH"
85
+ ]);
86
+ function isPreSendError(err) {
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);
91
+ return false;
92
+ }
93
+ async function readBoundedText(response, maxBytes) {
94
+ if (!response.body) {
95
+ const text = await response.text();
96
+ if (Buffer.byteLength(text, "utf8") > maxBytes) throw new WecomError("RESPONSE_TOO_LARGE");
97
+ return text;
98
+ }
99
+ const reader = response.body.getReader();
100
+ const chunks = [];
101
+ let total = 0;
102
+ try {
103
+ while (true) {
104
+ const { done, value } = await reader.read();
105
+ if (done) break;
106
+ if (!value) continue;
107
+ total += value.byteLength;
108
+ if (total > maxBytes) {
109
+ await reader.cancel().catch(() => {});
110
+ throw new WecomError("RESPONSE_TOO_LARGE");
111
+ }
112
+ chunks.push(value);
113
+ }
114
+ } finally {
115
+ reader.releaseLock();
116
+ }
117
+ return Buffer.concat(chunks, total).toString("utf8");
118
+ }
119
+ function createFetchTransport(fetchImpl = fetch) {
120
+ return async (request) => {
121
+ const controller = new AbortController();
122
+ const timer = setTimeout(() => controller.abort(new WecomError("WAIT_TIMEOUT")), request.timeoutMs);
123
+ const onExternalAbort = () => controller.abort(new WecomError("ABORTED"));
124
+ request.signal?.addEventListener("abort", onExternalAbort, { once: true });
125
+ let response;
126
+ try {
127
+ response = await fetchImpl(request.url, {
128
+ method: request.method,
129
+ headers: request.headers,
130
+ body: request.body,
131
+ redirect: "manual",
132
+ signal: controller.signal
133
+ });
134
+ } catch (err) {
135
+ clearTimeout(timer);
136
+ request.signal?.removeEventListener("abort", onExternalAbort);
137
+ if (err instanceof WecomError) throw err;
138
+ if (request.signal?.aborted) throw new WecomError("ABORTED");
139
+ if (isPreSendError(err)) throw new WecomError("TRANSPORT_NOT_SENT");
140
+ throw new WecomError("TRANSPORT_UNCERTAIN");
141
+ }
142
+ try {
143
+ if (response.status >= 300 && response.status < 400) throw new WecomError("REDIRECT_REJECTED", true);
144
+ const body = await readBoundedText(response, request.maxBytes);
145
+ return {
146
+ status: response.status,
147
+ body
148
+ };
149
+ } catch (err) {
150
+ if (err instanceof WecomError) throw err;
151
+ if (request.signal?.aborted) throw new WecomError("ABORTED");
152
+ throw new WecomError("TRANSPORT_UNCERTAIN");
153
+ } finally {
154
+ clearTimeout(timer);
155
+ request.signal?.removeEventListener("abort", onExternalAbort);
156
+ }
157
+ };
158
+ }
159
+
160
+ //#endregion
161
+ //#region src/a2a/client.ts
162
+ const DAYUAN_A2A_ORIGIN = "https://qyapi.weixin.qq.com";
163
+ const DAYUAN_A2A_BASE_PATH = "/cgi-bin/a2a/api";
164
+ const A2A_MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
165
+ const RECEIPT_PREFIX = "wecom/a2a/receipt/";
166
+ const TASK_PREFIX = "wecom/a2a/task/";
167
+ const POLL_INTERVAL_MS = 2e3;
168
+ const REQUEST_TIMEOUT_MS = 3e4;
169
+ const MAX_WAIT_SECONDS$1 = 120;
170
+ const DEFAULT_WAIT_SECONDS = 20;
171
+ const SAFE_ID_RE = /^[A-Za-z0-9_.:-]{1,128}$/;
172
+ const TOKEN_EXPIRED_ERRCODES = new Set([
173
+ 40001,
174
+ 40014,
175
+ 42001
176
+ ]);
177
+ function cleanText(value, field, maxLength = 2e3) {
178
+ if (typeof value !== "string") throw new WecomError(`INVALID_${field.toUpperCase()}`, true);
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);
196
+ }
197
+ function normalizeState(raw) {
198
+ if (typeof raw !== "string") return "unknown";
199
+ const normalized = raw.trim().toLowerCase().replace(/-/g, "_");
200
+ switch (normalized) {
201
+ case "submitted":
202
+ case "working":
203
+ case "input_required":
204
+ case "completed":
205
+ case "failed":
206
+ case "canceled":
207
+ case "rejected": return normalized;
208
+ case "cancelled": return "canceled";
209
+ default: return "unknown";
210
+ }
211
+ }
212
+ function isTerminalState(state) {
213
+ return state === "completed" || state === "failed" || state === "canceled" || state === "rejected";
214
+ }
215
+ function isSettledForWait(state) {
216
+ return isTerminalState(state) || state === "input_required";
217
+ }
218
+ function asRecord(value) {
219
+ if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
220
+ return value;
221
+ }
222
+ function collectParts(payload) {
223
+ const parts = [];
224
+ const pushFrom = (container) => {
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();
257
+ }
258
+ function buildReadOnlyPrompt(input) {
259
+ if (input.action === "search_groups") {
260
+ const query$1 = cleanText(input.query, "query", 300);
261
+ const limit = input.limit !== void 0 && Number.isFinite(input.limit) ? Math.max(1, Math.min(20, Math.floor(input.limit))) : 10;
262
+ return {
263
+ prompt: `只读查询:请在企业微信中查找名称或主题与「${query$1}」相关的群聊,最多列出 ${limit} 个候选群名及简短说明。不要发送任何消息或执行写操作。`,
264
+ canonical: {
265
+ action: input.action,
266
+ query: query$1,
267
+ limit
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(",");
289
+ return {
290
+ prompt: `只读查询:请在企业微信消息中检索与「${query}」相关的内容${scope ? `(${scope})` : ""},汇总相关讨论结论与来源群名。不要发送任何消息或执行写操作。`,
291
+ canonical: {
292
+ action: input.action,
293
+ query,
294
+ chat_name: chatName ?? null,
295
+ time_range: timeRange ?? null
296
+ }
297
+ };
298
+ }
299
+ function fingerprintOf(canonical) {
300
+ return createHash("sha256").update(JSON.stringify(canonical)).digest("hex");
301
+ }
302
+ function buildWhitelistedUrl(route) {
303
+ if (route.kind === "send") return `${DAYUAN_A2A_ORIGIN}${DAYUAN_A2A_BASE_PATH}/message:send`;
304
+ const safeId = assertSafeId(route.taskId, "task_id");
305
+ return `${DAYUAN_A2A_ORIGIN}${DAYUAN_A2A_BASE_PATH}/tasks/${encodeURIComponent(safeId)}?historyLength=0`;
306
+ }
307
+ var DayuanA2AClient = class {
308
+ auth;
309
+ storage;
310
+ transport;
311
+ clock;
312
+ lock = new AsyncKeyLock();
313
+ constructor(options) {
314
+ this.auth = options.auth;
315
+ this.storage = options.storage;
316
+ this.transport = options.transport ?? createFetchTransport();
317
+ this.clock = options.clock ?? systemClock;
318
+ }
319
+ receiptKey(identity, requestId) {
320
+ return `${RECEIPT_PREFIX}${identity}/${requestId}`;
321
+ }
322
+ taskKey(taskId) {
323
+ return `${TASK_PREFIX}${taskId}`;
324
+ }
325
+ parseTaskPayload(raw, meta) {
326
+ const taskObj = asRecord(raw.result) ?? asRecord(raw.task) ?? raw;
327
+ const rawId = taskObj.id ?? taskObj.taskId ?? raw.id;
328
+ if (typeof rawId !== "string" || !rawId.trim()) throw new WecomError("A2A_TASK_ID_MISSING");
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
+ }
353
+ return {
354
+ task_id: taskId,
355
+ ...contextId ? { context_id: contextId } : {},
356
+ ...meta.request_id ? { request_id: meta.request_id } : {},
357
+ ...meta.action ? { action: meta.action } : {},
358
+ state,
359
+ completed: isTerminalState(state),
360
+ is_summary: true,
361
+ summary,
362
+ interaction_kind: interactionKind,
363
+ can_reply_in_text: canReplyInText,
364
+ human_action_required: humanActionRequired,
365
+ ...guidance ? { guidance } : {},
366
+ from_cache: meta.from_cache,
367
+ updated_at_ms: this.clock.now()
368
+ };
369
+ }
370
+ async requestA2A(options) {
371
+ const url = buildWhitelistedUrl(options.route);
372
+ let credential = await this.auth.ensureWecom({ signal: options.signal });
373
+ const executeOnce = async (token) => {
374
+ const headers = {
375
+ Accept: "application/json",
376
+ Authorization: `Bearer ${token}`
377
+ };
378
+ let serialized;
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
+ };
409
+ };
410
+ let attempt = await executeOnce(credential.access_token);
411
+ if (attempt.isAuthFailure && (options.allowAuthRetry ?? true)) {
412
+ credential = await this.auth.ensureWecom({
413
+ force: true,
414
+ signal: options.signal
415
+ });
416
+ attempt = await executeOnce(credential.access_token);
417
+ }
418
+ if (attempt.isAuthFailure) throw new WecomError("WECOM_TOKEN_REJECTED_LOGIN_REQUIRED", true);
419
+ if (attempt.status === 403) throw new WecomError("A2A_FORBIDDEN", true);
420
+ if (attempt.status < 200 || attempt.status >= 300) throw new WecomError(`A2A_HTTP_${attempt.status}`);
421
+ if (attempt.errcode !== 0) throw new WecomError(`A2A_ERRCODE_${attempt.errcode}`);
422
+ return {
423
+ payload: attempt.parsed,
424
+ identity: credential.identity
425
+ };
426
+ }
427
+ async saveTaskRecord(record) {
428
+ await this.storage.set(this.taskKey(record.task_id), record);
429
+ }
430
+ async loadTaskRecord(taskId) {
431
+ const raw = await this.storage.get(this.taskKey(taskId));
432
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return void 0;
433
+ return raw;
434
+ }
435
+ async pollTask(initial, identity, waitSeconds, options) {
436
+ let current = initial;
437
+ if (isSettledForWait(current.state) || waitSeconds <= 0) return current;
438
+ const deadlineMono = this.clock.monotonic() + waitSeconds * 1e3;
439
+ let pollCount = 0;
440
+ while (!isSettledForWait(current.state)) {
441
+ const remaining = deadlineMono - this.clock.monotonic();
442
+ if (remaining <= 0) break;
443
+ pollCount += 1;
444
+ if (options?.onProgress) await Promise.resolve(options.onProgress({
445
+ task_id: current.task_id,
446
+ state: current.state,
447
+ poll_count: pollCount
448
+ }));
449
+ await this.clock.sleep(Math.min(POLL_INTERVAL_MS, remaining), options?.signal);
450
+ const { payload } = await this.requestA2A({
451
+ method: "GET",
452
+ route: {
453
+ kind: "task",
454
+ taskId: current.task_id
455
+ },
456
+ signal: options?.signal
457
+ });
458
+ current = this.parseTaskPayload(payload, {
459
+ request_id: current.request_id,
460
+ action: current.action,
461
+ from_cache: false
462
+ });
463
+ await this.saveTaskRecord({
464
+ task_id: current.task_id,
465
+ context_id: current.context_id,
466
+ identity,
467
+ action: current.action,
468
+ request_id: current.request_id,
469
+ result: current
470
+ });
471
+ }
472
+ return current;
473
+ }
474
+ async start(input, options) {
475
+ const { prompt, canonical } = buildReadOnlyPrompt(input);
476
+ const requestId = input.request_id ? assertSafeId(input.request_id, "request_id") : randomUUID();
477
+ const waitSeconds = normalizeWaitSeconds(input.wait_seconds);
478
+ const fingerprint = fingerprintOf(canonical);
479
+ const credential = await this.auth.ensureWecom({ signal: options?.signal });
480
+ const receiptKey = this.receiptKey(credential.identity, requestId);
481
+ return this.lock.run(`receipt:${receiptKey}`, async () => {
482
+ const existing = asRecord(await this.storage.get(receiptKey));
483
+ if (existing) {
484
+ if (existing.fingerprint !== fingerprint) throw new WecomError("REQUEST_ID_CONFLICT", true);
485
+ if (existing.status === "submit_unknown") throw new WecomError("SUBMIT_OUTCOME_UNKNOWN", true);
486
+ if (existing.result && isSettledForWait(existing.result.state)) return {
487
+ ...existing.result,
488
+ from_cache: true
489
+ };
490
+ if (existing.task_id) {
491
+ const polled = await this.getResult({
492
+ task_id: existing.task_id,
493
+ wait_seconds: waitSeconds
494
+ }, options);
495
+ existing.status = polled.state;
496
+ existing.result = polled;
497
+ existing.updated_at_ms = this.clock.now();
498
+ await this.storage.set(receiptKey, existing);
499
+ return polled;
500
+ }
501
+ }
502
+ const now = this.clock.now();
503
+ const pendingReceipt = {
504
+ request_id: requestId,
505
+ identity: credential.identity,
506
+ action: input.action,
507
+ fingerprint,
508
+ status: "submit_unknown",
509
+ created_at_ms: now,
510
+ updated_at_ms: now
511
+ };
512
+ await this.storage.set(receiptKey, pendingReceipt);
513
+ let payload;
514
+ let identity;
515
+ try {
516
+ const res = await this.requestA2A({
517
+ method: "POST",
518
+ route: { kind: "send" },
519
+ body: { message: {
520
+ messageId: requestId,
521
+ role: "user",
522
+ parts: [{
523
+ kind: "text",
524
+ text: prompt
525
+ }]
526
+ } },
527
+ signal: options?.signal
528
+ });
529
+ payload = res.payload;
530
+ identity = res.identity;
531
+ } catch (err) {
532
+ if (err instanceof WecomError && (err.code === "TRANSPORT_NOT_SENT" || err.definitive)) await this.storage.remove(receiptKey);
533
+ throw err;
534
+ }
535
+ let result = this.parseTaskPayload(payload, {
536
+ request_id: requestId,
537
+ action: input.action,
538
+ from_cache: false
539
+ });
540
+ await this.saveTaskRecord({
541
+ task_id: result.task_id,
542
+ context_id: result.context_id,
543
+ identity,
544
+ action: input.action,
545
+ request_id: requestId,
546
+ result
547
+ });
548
+ result = await this.pollTask(result, identity, waitSeconds, options);
549
+ const finalized = {
550
+ ...pendingReceipt,
551
+ identity,
552
+ status: result.state,
553
+ task_id: result.task_id,
554
+ context_id: result.context_id,
555
+ result,
556
+ updated_at_ms: this.clock.now()
557
+ };
558
+ await this.storage.set(receiptKey, finalized);
559
+ return result;
560
+ });
561
+ }
562
+ async getResult(input, options) {
563
+ const taskId = assertSafeId(input.task_id, "task_id");
564
+ const waitSeconds = normalizeWaitSeconds(input.wait_seconds);
565
+ const existing = await this.loadTaskRecord(taskId);
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
582
+ });
583
+ await this.saveTaskRecord({
584
+ task_id: result.task_id,
585
+ context_id: result.context_id ?? existing?.context_id,
586
+ identity,
587
+ action: existing?.action,
588
+ request_id: existing?.request_id,
589
+ result
590
+ });
591
+ result = await this.pollTask(result, identity, waitSeconds, options);
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;
603
+ }
604
+ async reply(input, options) {
605
+ const taskId = assertSafeId(input.task_id, "task_id");
606
+ const text = cleanText(input.text, "text", 1500);
607
+ const waitSeconds = normalizeWaitSeconds(input.wait_seconds);
608
+ const replyMessageId = input.request_id ? assertSafeId(input.request_id, "request_id") : randomUUID();
609
+ return this.lock.run(`task:${taskId}`, async () => {
610
+ let record = await this.loadTaskRecord(taskId);
611
+ if (!record) {
612
+ const fetched = await this.getResult({
613
+ task_id: taskId,
614
+ wait_seconds: 0
615
+ }, options);
616
+ record = await this.loadTaskRecord(fetched.task_id);
617
+ }
618
+ if (record?.result.state !== "input_required") throw new WecomError("TASK_NOT_WAITING_FOR_INPUT", true);
619
+ if (record.result.interaction_kind === "approval_required") throw new WecomError("APPROVAL_INTERACTION_BLOCKED", true);
620
+ if (!record.result.can_reply_in_text) throw new WecomError("UNSUPPORTED_INTERACTION_BLOCKED", true);
621
+ const { payload, identity } = await this.requestA2A({
622
+ method: "POST",
623
+ route: { kind: "send" },
624
+ body: { message: {
625
+ messageId: replyMessageId,
626
+ role: "user",
627
+ taskId,
628
+ ...record.context_id ? { contextId: record.context_id } : {},
629
+ parts: [{
630
+ kind: "text",
631
+ text
632
+ }]
633
+ } },
634
+ signal: options?.signal
635
+ });
636
+ let result = this.parseTaskPayload(payload, {
637
+ request_id: record.request_id,
638
+ action: record.action,
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);
658
+ }
659
+ }
660
+ return result;
661
+ });
662
+ }
663
+ async listReceipts(limit = 20) {
664
+ const max = Math.max(1, Math.min(100, Math.floor(limit)));
665
+ const items = [];
666
+ let after;
667
+ while (items.length < 200) {
668
+ const page = await this.storage.scan({
669
+ prefix: RECEIPT_PREFIX,
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
+ };
691
+ });
692
+ }
693
+ };
694
+
695
+ //#endregion
696
+ //#region src/auth/workbuddy.ts
697
+ const WORKBUDDY_ORIGIN = "https://www.workbuddy.cn";
698
+ const WORKBUDDY_PREFIX = "/v2/plugin";
699
+ const WECOM_LOGIN_URL = `${WORKBUDDY_ORIGIN}/login/wecom-auth`;
700
+ const AUTH_FLOW_VERSION = "5.8.2";
701
+ const AUTH_STORAGE_KEY = "wecom/cloud-auth";
702
+ const AUTH_MAX_RESPONSE_BYTES = 1024 * 1024;
703
+ const PENDING_TTL_MS = 3e5;
704
+ const FRESH_BUFFER_MS = 6e4;
705
+ const LOGIN_POLL_INTERVAL_MS = 2e3;
706
+ const MAX_WAIT_SECONDS = 300;
707
+ const USER_AGENT = "opencode-plugin-wecom/0.1.0 (local interoperability client)";
708
+ const TOKEN_STATE_PATH_RE = /^\/v2\/plugin\/auth\/token\?state=[A-Za-z0-9_%.-]+$/;
709
+ const EXCHANGE_PATH_RE = /^\/console\/enterprises\/[A-Za-z0-9_%.-]+\/oneid_openapi\/exchange-wecom-token$/;
710
+ function formatLoginUrl(rawUrl) {
711
+ const parsed = new URL(rawUrl);
712
+ parsed.searchParams.set("version", AUTH_FLOW_VERSION);
713
+ parsed.searchParams.set("force_login_type", "wecom");
714
+ parsed.hash = "";
715
+ return parsed.toString();
716
+ }
717
+ function assertSecret(value) {
718
+ if (typeof value !== "string" || !value || hasControlOrSpaceChar(value)) throw new WecomError("INVALID_CREDENTIAL", true);
719
+ return value;
720
+ }
721
+ function parseDeadline(value) {
722
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) return value;
723
+ return 0;
724
+ }
725
+ function normalizeAuth(value, nowMs) {
726
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new WecomError("INVALID_AUTH_RESPONSE");
727
+ const raw = { ...value };
728
+ const accessToken = assertSecret(raw.accessToken);
729
+ let refreshToken;
730
+ if (raw.refreshToken !== void 0 && raw.refreshToken !== null && raw.refreshToken !== "") refreshToken = assertSecret(raw.refreshToken);
731
+ const expiresIn = parseDeadline(raw.expiresIn);
732
+ const expiresAt = parseDeadline(raw.expiresAt) || (expiresIn ? nowMs + expiresIn * 1e3 : 0);
733
+ const refreshExpiresIn = parseDeadline(raw.refreshExpiresIn);
734
+ const refreshExpiresAt = parseDeadline(raw.refreshExpiresAt) || (refreshExpiresIn ? nowMs + refreshExpiresIn * 1e3 : 0);
735
+ return {
736
+ ...raw,
737
+ accessToken,
738
+ ...refreshToken ? { refreshToken } : {},
739
+ expiresAt,
740
+ refreshExpiresAt
741
+ };
742
+ }
743
+ function accountIdentity(account) {
744
+ if (!account || typeof account !== "object" || Array.isArray(account)) throw new WecomError("INVALID_ACCOUNT_RESPONSE");
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;
752
+ }
753
+ function isAllowedEndpoint(method, path) {
754
+ if (method === "POST" && (path === `${WORKBUDDY_PREFIX}/auth/state?platform=workbuddy` || path === `${WORKBUDDY_PREFIX}/auth/token/refresh`)) return true;
755
+ if (method === "GET" && (path === `${WORKBUDDY_PREFIX}/account` || TOKEN_STATE_PATH_RE.test(path))) return true;
756
+ if (method === "POST" && EXCHANGE_PATH_RE.test(path)) return true;
757
+ return false;
758
+ }
759
+ var WorkBuddyAuth = class {
760
+ storage;
761
+ transport;
762
+ clock;
763
+ onAuthChange;
764
+ lock = new AsyncKeyLock();
765
+ constructor(options) {
766
+ this.storage = options.storage;
767
+ this.transport = options.transport ?? createFetchTransport();
768
+ this.clock = options.clock ?? systemClock;
769
+ this.onAuthChange = options.onAuthChange;
770
+ }
771
+ async load() {
772
+ const stored = await this.storage.get(AUTH_STORAGE_KEY);
773
+ if (!stored || typeof stored !== "object" || Array.isArray(stored)) return { phase: "logged_out" };
774
+ const doc = stored;
775
+ return {
776
+ ...doc,
777
+ phase: doc.phase ?? "logged_out"
778
+ };
779
+ }
780
+ async save(doc) {
781
+ await this.storage.set(AUTH_STORAGE_KEY, doc);
782
+ if (this.onAuthChange) await Promise.resolve(this.onAuthChange(this.toStatus(doc))).catch(() => {});
783
+ }
784
+ toStatus(doc) {
785
+ const auth = doc.auth;
786
+ return {
787
+ phase: doc.phase,
788
+ desktop_required: false,
789
+ cloud_dependency: WORKBUDDY_ORIGIN,
790
+ account_expires_at_ms: auth?.expiresAt || null,
791
+ refresh_expires_at_ms: auth?.refreshExpiresAt || null,
792
+ refresh_credential_present: Boolean(auth?.refreshToken),
793
+ wecom_expires_at_ms: doc.wecom?.expires_at_ms ?? null,
794
+ wecom_configured: Boolean(doc.wecom?.access_token),
795
+ authorization_verified: false
796
+ };
797
+ }
798
+ async requestCloud(options) {
799
+ const { method, path, auth, refreshToken, beforeSend, deadlineMonoMs, signal } = options;
800
+ if (!isAllowedEndpoint(method, path)) throw new WecomError("ENDPOINT_NOT_ALLOWED", true);
801
+ const headers = {
802
+ Accept: "application/json",
803
+ "Content-Type": "application/json",
804
+ "X-Domain": "www.workbuddy.cn",
805
+ "X-Product": "SaaS",
806
+ "User-Agent": USER_AGENT
807
+ };
808
+ if (auth) headers.Authorization = `Bearer ${assertSecret(auth.accessToken)}`;
809
+ if (refreshToken) {
810
+ headers["X-Refresh-Token"] = assertSecret(refreshToken);
811
+ headers["X-Auth-Refresh-Source"] = "plugin";
812
+ }
813
+ let timeoutMs = 25e3;
814
+ if (deadlineMonoMs !== void 0) {
815
+ const remaining = deadlineMonoMs - this.clock.monotonic();
816
+ if (remaining <= 0) throw new WecomError("WAIT_TIMEOUT");
817
+ timeoutMs = Math.min(timeoutMs, remaining);
818
+ }
819
+ if (beforeSend) await beforeSend();
820
+ const response = await this.transport({
821
+ method,
822
+ url: `${WORKBUDDY_ORIGIN}${path}`,
823
+ headers,
824
+ body: method === "POST" ? "{}" : void 0,
825
+ timeoutMs,
826
+ maxBytes: AUTH_MAX_RESPONSE_BYTES,
827
+ signal
828
+ });
829
+ if (response.status >= 300 && response.status < 400) throw new WecomError("REDIRECT_REJECTED", true);
830
+ let parsed;
831
+ try {
832
+ parsed = JSON.parse(response.body);
833
+ } catch {
834
+ if (response.status >= 400) throw new WecomError(`HTTP_${response.status}`, response.status < 500);
835
+ throw new WecomError("INVALID_RESPONSE");
836
+ }
837
+ const bodyRecord = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null;
838
+ if (response.status >= 400) {
839
+ const code$1 = bodyRecord?.code;
840
+ if (code$1 === 11217 || code$1 === 12151) throw new WecomError(`PENDING_${code$1}`);
841
+ const suffix = typeof code$1 === "number" && Number.isInteger(code$1) ? `_CODE_${code$1}` : "";
842
+ throw new WecomError(`HTTP_${response.status}${suffix}`, response.status < 500);
843
+ }
844
+ if (!bodyRecord) throw new WecomError("INVALID_RESPONSE");
845
+ const code = bodyRecord.code;
846
+ if (code === 11217 || code === 12151) throw new WecomError(`PENDING_${code}`);
847
+ if (code !== 0) throw new WecomError(typeof code === "number" && Number.isInteger(code) ? `CLOUD_CODE_${code}` : "INVALID_RESPONSE");
848
+ const data = bodyRecord.data;
849
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new WecomError("INVALID_RESPONSE");
850
+ return data;
851
+ }
852
+ async status() {
853
+ return this.toStatus(await this.load());
854
+ }
855
+ wecomLoginInfo() {
856
+ return {
857
+ authorization_url: WECOM_LOGIN_URL,
858
+ instruction: "在完成账号登录的同一浏览器中,授权同一企业微信账号,完成后执行 wecom_renew。"
859
+ };
860
+ }
861
+ async start(options) {
862
+ return this.lock.run("auth", async () => {
863
+ const doc = await this.load();
864
+ if (doc.phase === "ready") throw new WecomError("ALREADY_LOGGED_IN_USE_RENEW", true);
865
+ if (doc.phase === "pending_token" && doc.pending && this.clock.now() - doc.pending.created_at_ms < PENDING_TTL_MS) {
866
+ const refreshedUrl = formatLoginUrl(doc.pending.url);
867
+ doc.pending.url = refreshedUrl;
868
+ await this.save(doc);
869
+ return {
870
+ phase: "pending_token",
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
904
+ };
905
+ });
906
+ }
907
+ async fetchAccount(doc, deadlineMonoMs, signal) {
908
+ if (!doc.auth) throw new WecomError("LOGIN_REQUIRED", true);
909
+ const account = await this.requestCloud({
910
+ method: "GET",
911
+ path: `${WORKBUDDY_PREFIX}/account`,
912
+ auth: doc.auth,
913
+ deadlineMonoMs,
914
+ signal
915
+ });
916
+ const nextId = accountIdentity(account);
917
+ if (doc.account) {
918
+ const prevId = accountIdentity(doc.account);
919
+ if (prevId[0] !== nextId[0] || prevId[1] !== nextId[1]) {
920
+ doc.phase = "account_changed";
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);
951
+ } catch (err) {
952
+ if (err instanceof WecomError && err.code.startsWith("PENDING_")) return { phase: "pending_account" };
953
+ throw err;
954
+ }
955
+ if (doc.phase !== "ready") throw new WecomError("LOGIN_REQUIRED", true);
956
+ return {
957
+ phase: "ready",
958
+ desktop_required: false,
959
+ cloud_dependency: WORKBUDDY_ORIGIN
960
+ };
961
+ });
962
+ }
963
+ async waitForLogin(options) {
964
+ const boundedSeconds = Math.min(Math.max(Math.floor(options.waitSeconds), 0), MAX_WAIT_SECONDS);
965
+ const deadlineMonoMs = this.clock.monotonic() + boundedSeconds * 1e3;
966
+ let result = await this.finish({
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
977
+ });
978
+ }
979
+ if (result.phase === "ready" && options.exchangeWecom !== false) await this.ensureWecom({
980
+ signal: options.signal,
981
+ deadlineMonoMs
982
+ });
983
+ return this.status();
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;
1024
+ }
1025
+ doc.auth = normalizeAuth(refreshed, this.clock.now());
1026
+ doc.phase = "pending_account";
1027
+ await this.save(doc);
1028
+ await this.fetchAccount(doc, deadlineMonoMs, signal);
1029
+ }
1030
+ cachedWecom(doc) {
1031
+ const nowMs = this.clock.now();
1032
+ if (doc.phase === "ready" && isFresh(doc.auth?.expiresAt, nowMs) && doc.wecom && isFresh(doc.wecom.expires_at_ms, nowMs)) return doc.wecom;
1033
+ return null;
1034
+ }
1035
+ async ensureWecom(options) {
1036
+ const force = options?.force ?? false;
1037
+ const forceRefreshAccount = options?.refreshAccount ?? false;
1038
+ if (!force && !forceRefreshAccount) {
1039
+ const cached = this.cachedWecom(await this.load());
1040
+ if (cached) return cached;
1041
+ }
1042
+ return this.lock.run("auth", async () => {
1043
+ const doc = await this.load();
1044
+ if (doc.phase === "refresh_unknown") throw new WecomError("REFRESH_OUTCOME_UNKNOWN_LOGIN_REQUIRED", true);
1045
+ if (doc.phase === "pending_account") await this.fetchAccount(doc, options?.deadlineMonoMs, options?.signal);
1046
+ if (doc.phase !== "ready" || !doc.auth) throw new WecomError("LOGIN_REQUIRED", true);
1047
+ if (forceRefreshAccount || !isFresh(doc.auth.expiresAt, this.clock.now())) await this.refreshAccount(doc, options?.deadlineMonoMs, options?.signal);
1048
+ if (!force && !forceRefreshAccount) {
1049
+ const cachedAfterLock = this.cachedWecom(doc);
1050
+ if (cachedAfterLock) return cachedAfterLock;
1051
+ }
1052
+ const enterpriseId = doc.account?.enterpriseId;
1053
+ if (typeof enterpriseId !== "string" || !enterpriseId) throw new WecomError("ENTERPRISE_ACCOUNT_REQUIRED", true);
1054
+ const route = `/console/enterprises/${encodeURIComponent(enterpriseId)}/oneid_openapi/exchange-wecom-token`;
1055
+ let exchanged;
1056
+ try {
1057
+ exchanged = await this.requestCloud({
1058
+ method: "POST",
1059
+ path: route,
1060
+ auth: doc.auth,
1061
+ deadlineMonoMs: options?.deadlineMonoMs,
1062
+ signal: options?.signal
1063
+ });
1064
+ } catch (err) {
1065
+ if (err instanceof WecomError && err.code.startsWith("HTTP_403")) throw new WecomError("WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN", true);
1066
+ throw err;
1067
+ }
1068
+ const accessToken = assertSecret(exchanged.access_token);
1069
+ const user = exchanged.alias_id;
1070
+ const corp = exchanged.src_tid;
1071
+ if (typeof user !== "string" || !user || typeof corp !== "string" || !corp) throw new WecomError("WECOM_STABLE_IDENTITY_MISSING");
1072
+ const identity = createHash("sha256").update(JSON.stringify([corp, user])).digest("hex");
1073
+ if (doc.wecom && doc.wecom.identity !== identity) throw new WecomError("WECOM_IDENTITY_CHANGED", true);
1074
+ const expiresIn = parseDeadline(exchanged.expires_in);
1075
+ if (!expiresIn) throw new WecomError("WECOM_EXPIRY_MISSING");
1076
+ const credential = {
1077
+ access_token: accessToken,
1078
+ identity,
1079
+ expires_at_ms: this.clock.now() + expiresIn * 1e3,
1080
+ source: "workbuddy_cloud"
1081
+ };
1082
+ doc.wecom = credential;
1083
+ await this.save(doc);
1084
+ return credential;
1085
+ });
1086
+ }
1087
+ async logout() {
1088
+ return this.lock.run("auth", async () => {
1089
+ await this.storage.remove(AUTH_STORAGE_KEY);
1090
+ const status = await this.status();
1091
+ if (this.onAuthChange) await Promise.resolve(this.onAuthChange(status)).catch(() => {});
1092
+ return status;
1093
+ });
1094
+ }
1095
+ };
1096
+
1097
+ //#endregion
1098
+ //#region src/wecom/cli.ts
1099
+ const ALLOWED_CLI_DOMAINS = [
1100
+ "doc",
1101
+ "smartsheet",
1102
+ "calendar",
1103
+ "meeting",
1104
+ "mail",
1105
+ "wedrive",
1106
+ "contact",
1107
+ "auth"
1108
+ ];
1109
+ const ALLOWED_DOMAIN_SET = new Set(ALLOWED_CLI_DOMAINS);
1110
+ const WRITE_VERBS = new Set([
1111
+ "create",
1112
+ "add",
1113
+ "new",
1114
+ "update",
1115
+ "edit",
1116
+ "patch",
1117
+ "set",
1118
+ "put",
1119
+ "delete",
1120
+ "del",
1121
+ "remove",
1122
+ "rm",
1123
+ "send",
1124
+ "reply",
1125
+ "forward",
1126
+ "upload",
1127
+ "share",
1128
+ "cancel",
1129
+ "revoke",
1130
+ "move",
1131
+ "rename",
1132
+ "copy",
1133
+ "write"
1134
+ ]);
1135
+ const DEFAULT_TIMEOUT_MS = 3e4;
1136
+ const MAX_BUFFER_BYTES = 2 * 1024 * 1024;
1137
+ function defaultProcessRunner(binary, args, options) {
1138
+ return new Promise((resolve, reject) => {
1139
+ execFile(binary, [...args], {
1140
+ shell: false,
1141
+ timeout: options.timeoutMs,
1142
+ maxBuffer: MAX_BUFFER_BYTES,
1143
+ signal: options.signal,
1144
+ encoding: "utf8"
1145
+ }, (err, stdout, stderr) => {
1146
+ if (!err) {
1147
+ resolve({
1148
+ exitCode: 0,
1149
+ stdout: stdout ?? "",
1150
+ stderr: stderr ?? ""
1151
+ });
1152
+ return;
1153
+ }
1154
+ const record = err;
1155
+ if (record.code === "ENOENT") {
1156
+ reject(record);
1157
+ return;
1158
+ }
1159
+ if (typeof record.code === "number") {
1160
+ resolve({
1161
+ exitCode: record.code,
1162
+ stdout: stdout ?? "",
1163
+ stderr: stderr ?? ""
1164
+ });
1165
+ return;
1166
+ }
1167
+ reject(err);
1168
+ });
1169
+ });
1170
+ }
1171
+ function isNotInstalledError(err) {
1172
+ return Boolean(err && typeof err === "object" && err.code === "ENOENT");
1173
+ }
1174
+ function validateArgs(args, allowWrite) {
1175
+ if (!Array.isArray(args) || args.length === 0 || args.length > 32) throw new WecomError("INVALID_CLI_ARGS", true);
1176
+ const clean = [];
1177
+ for (const raw of args) {
1178
+ if (typeof raw !== "string" || raw.length === 0 || raw.length > 1e3 || hasControlChar(raw)) throw new WecomError("INVALID_CLI_ARGS", true);
1179
+ clean.push(raw);
1180
+ }
1181
+ if (!allowWrite) for (const token of clean) {
1182
+ if (token.startsWith("-")) continue;
1183
+ const lower = token.toLowerCase();
1184
+ if (WRITE_VERBS.has(lower)) throw new WecomError("WECOM_CLI_WRITE_BLOCKED", true);
1185
+ break;
1186
+ }
1187
+ return clean;
1188
+ }
1189
+ var WecomCliBridge = class {
1190
+ binary;
1191
+ allowWrite;
1192
+ runner;
1193
+ constructor(options) {
1194
+ this.binary = options?.binary?.trim() || "wecom";
1195
+ this.allowWrite = options?.allowWrite ?? false;
1196
+ this.runner = options?.runner ?? defaultProcessRunner;
1197
+ }
1198
+ async probe(signal) {
1199
+ try {
1200
+ const res = await this.runner(this.binary, ["--version"], {
1201
+ timeoutMs: 5e3,
1202
+ signal
1203
+ });
1204
+ if (res.exitCode === 0) {
1205
+ const version = res.stdout.trim().split(/\r?\n/)[0]?.trim() || "unknown";
1206
+ return {
1207
+ available: true,
1208
+ binary: this.binary,
1209
+ version
1210
+ };
1211
+ }
1212
+ return {
1213
+ available: false,
1214
+ binary: this.binary,
1215
+ install_hint: "npm install -g @wecom/cli"
1216
+ };
1217
+ } catch {
1218
+ return {
1219
+ available: false,
1220
+ binary: this.binary,
1221
+ install_hint: "npm install -g @wecom/cli"
1222
+ };
1223
+ }
1224
+ }
1225
+ async run(input, signal) {
1226
+ if (typeof input.domain !== "string" || !ALLOWED_DOMAIN_SET.has(input.domain)) throw new WecomError("WECOM_CLI_DOMAIN_BLOCKED", true);
1227
+ const cleanArgs = validateArgs(input.args, this.allowWrite);
1228
+ const timeoutMs = input.timeout_ms !== void 0 && Number.isFinite(input.timeout_ms) ? Math.max(1e3, Math.min(12e4, Math.floor(input.timeout_ms))) : DEFAULT_TIMEOUT_MS;
1229
+ let result;
1230
+ try {
1231
+ result = await this.runner(this.binary, [input.domain, ...cleanArgs], {
1232
+ timeoutMs,
1233
+ signal
1234
+ });
1235
+ } catch (err) {
1236
+ if (isNotInstalledError(err)) throw new WecomError("WECOM_CLI_NOT_INSTALLED", true);
1237
+ if (signal?.aborted) throw new WecomError("ABORTED");
1238
+ throw new WecomError("WECOM_CLI_EXECUTION_FAILED");
1239
+ }
1240
+ let data;
1241
+ const trimmed = result.stdout.trim();
1242
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) try {
1243
+ data = JSON.parse(trimmed);
1244
+ } catch {
1245
+ data = void 0;
1246
+ }
1247
+ return {
1248
+ ok: result.exitCode === 0,
1249
+ exit_code: result.exitCode,
1250
+ domain: input.domain,
1251
+ ...data !== void 0 ? { data } : {},
1252
+ stdout: result.stdout,
1253
+ stderr: result.stderr
1254
+ };
1255
+ }
1256
+ };
1257
+
1258
+ //#endregion
1259
+ //#region src/index.ts
1260
+ const EMBEDDED_SKILL_CONTENT = `---
1261
+ name: wecom-dayuan
1262
+ description: 使用 opencode-plugin-wecom 零客户端依赖地连接企业微信(WorkBuddy 扫码换票 + 大圆 A2A 只读群聊摘要 + 可选 @wecom/cli 办公域)。
1263
+ ---
1264
+
1265
+ # 企业微信(WeCom / 大圆)使用规范
1266
+
1267
+ ## 1. 登录与凭据
1268
+ - 本插件**不需要**安装 WorkBuddy 桌面端或企业微信桌面端,只需要用手机企业微信扫码一次。
1269
+ - 调用查询前可先用 \`wecom_status\` 检查状态(零网络请求)。
1270
+ - 若未登录或遇到 \`LOGIN_REQUIRED\` / \`REFRESH_OUTCOME_UNKNOWN_LOGIN_REQUIRED\`,调用 \`wecom_login({ mode: "start" })\` 把 \`authorization_url\` 给用户,引导用户在浏览器打开并用手机企微扫码,随后调用 \`wecom_login({ mode: "wait", wait_seconds: 60 })\` 完成换票。
1271
+ - 若遇到 \`WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN\`,说明企业微信应用尚未在云端授权,请引导用户打开 \`${WECOM_LOGIN_URL}\` 完成授权。
1272
+
1273
+ ## 2. 大圆 A2A 只读边界
1274
+ - \`wecom_read_start\` / \`wecom_read_result\` / \`wecom_read_reply\` 仅支持只读查群、读群聊摘要和搜消息摘要。
1275
+ - **返回值是大圆生成的摘要(\`is_summary: true\`),不是逐字原始聊天记录**,请如实向用户说明。
1276
+ - 建议传稳定的 \`request_id\` 保证幂等;遇到 \`SUBMIT_OUTCOME_UNKNOWN\` 不要盲目重试同一请求。
1277
+ - 当任务返回 \`interaction_kind === "text_clarification"\` 时,可用 \`wecom_read_reply\` 补充澄清。
1278
+ - 当任务返回 \`interaction_kind === "approval_required"\` 时,**必须停下并告知用户在手机企业微信手动审批**,严禁尝试自动通过。
1279
+
1280
+ ## 3. 结构化办公域(可选)
1281
+ - 若用户需要查文档、智能表格、日程、会议、邮件、微盘或通讯录,且已安装 \`@wecom/cli\`,可调用 \`wecom_cli\`(默认仅允许只读子命令)。
1282
+ `;
1283
+ function wrapOpenCodeStorage(storage) {
1284
+ return {
1285
+ get: (key) => storage.get(key),
1286
+ set: (key, value) => storage.set(key, value),
1287
+ remove: (key) => storage.remove(key),
1288
+ scan: (options) => storage.scan(options)
1289
+ };
1290
+ }
1291
+ function formatErrorHint(err) {
1292
+ const code = err instanceof WecomError ? err.code : err instanceof Error ? err.message : String(err);
1293
+ switch (code) {
1294
+ case "LOGIN_REQUIRED":
1295
+ case "WECOM_TOKEN_REJECTED_LOGIN_REQUIRED": return `${code}: 当前未登录或凭据已失效,请运行 /wecom-login 或调用 wecom_login({ mode: "start" }) 扫码登录。`;
1296
+ case "REFRESH_OUTCOME_UNKNOWN_LOGIN_REQUIRED": return `${code}: 上一次续期请求网络状态不确定,为避免重放一次性 refresh_token 已中止自动续期,请重新扫码登录。`;
1297
+ case "WECOM_AUTH_REQUIRED_OPEN_WECOM_LOGIN": return `${code}: WorkBuddy 账号已登录,但尚未完成企业微信应用授权。请在浏览器打开 ${WECOM_LOGIN_URL} 完成授权后重试。`;
1298
+ case "ENTERPRISE_ACCOUNT_REQUIRED": return `${code}: 当前账号缺少企业 ID,请使用企业微信企业账号登录。`;
1299
+ case "APPROVAL_INTERACTION_BLOCKED": return `${code}: 该任务触发了企业微信敏感审批卡片,插件严禁代批,请用户在手机企业微信手动处理。`;
1300
+ case "WECOM_CLI_NOT_INSTALLED": return `${code}: 未检测到 @wecom/cli。如需使用文档/日程/会议等办公域能力,请先执行 npm install -g @wecom/cli。`;
1301
+ case "WECOM_CLI_WRITE_BLOCKED": return `${code}: wecom_cli 默认处于只读模式。如需启用写命令,请在 opencode.json 的插件 options 中显式设置 "allowCliWrite": true。`;
1302
+ default: return code;
1303
+ }
1304
+ }
1305
+ function formatTaskSummaryText(result) {
1306
+ const lines = [`状态: ${result.state} | 任务 ID: ${result.task_id}${result.from_cache ? " (缓存)" : ""}`, "说明: 以下内容由大圆 A2A 生成,属于只读摘要而非逐字原始记录。"];
1307
+ if (result.summary) lines.push("", result.summary);
1308
+ if (result.guidance) lines.push("", `提示: ${result.guidance}`);
1309
+ return lines.join("\n");
1310
+ }
1311
+ function formatStatusText(status, cliAvailable, receiptCount) {
1312
+ const lines = [
1313
+ `WeCom 登录状态: ${status.phase}`,
1314
+ `桌面端依赖: 无需安装(desktop_required = false)`,
1315
+ `企微 Token 就绪: ${status.wecom_configured ? "是" : "否"}`,
1316
+ `可选 @wecom/cli: ${cliAvailable ? "已安装" : "未安装(不影响大圆 A2A 查群)"}`,
1317
+ `近期查询回执: ${receiptCount} 条`
1318
+ ];
1319
+ if (status.phase !== "ready") lines.push("提示: 运行 /wecom-login 获取手机企微扫码链接。");
1320
+ return lines.join("\n");
1321
+ }
1322
+ const DAYUAN_TASK_RESULT_OUTPUT_SCHEMA = {
1323
+ type: "object",
1324
+ properties: {
1325
+ task_id: { type: "string" },
1326
+ state: { type: "string" },
1327
+ is_summary: { type: "boolean" },
1328
+ summary: { type: "string" },
1329
+ interaction_kind: { type: "string" },
1330
+ guidance: { type: "string" },
1331
+ raw_parts_count: { type: "number" },
1332
+ from_cache: { type: "boolean" }
1333
+ },
1334
+ additionalProperties: true
1335
+ };
1336
+ function createWecomPlugin(deps) {
1337
+ return Plugin.define({
1338
+ id: PLUGIN_ID,
1339
+ async setup(ctx) {
1340
+ const storage = wrapOpenCodeStorage(ctx.storage);
1341
+ const cliBinary = typeof ctx.options?.cliBinary === "string" ? ctx.options.cliBinary : void 0;
1342
+ const allowCliWrite = ctx.options?.allowCliWrite === true;
1343
+ const enableCliTool = ctx.options?.enableCliTool !== false;
1344
+ let emitAuthChanged;
1345
+ const auth = new WorkBuddyAuth({
1346
+ storage,
1347
+ transport: deps?.transport,
1348
+ clock: deps?.clock,
1349
+ onAuthChange: async (status) => {
1350
+ if (emitAuthChanged) await emitAuthChanged(status);
1351
+ }
1352
+ });
1353
+ const a2a = new DayuanA2AClient({
1354
+ auth,
1355
+ storage,
1356
+ transport: deps?.transport,
1357
+ clock: deps?.clock
1358
+ });
1359
+ const cli = new WecomCliBridge({
1360
+ binary: cliBinary,
1361
+ allowWrite: allowCliWrite,
1362
+ runner: deps?.cliRunner
1363
+ });
1364
+ const rpcReg = await ctx.rpc.register(WecomRpc, {
1365
+ async status(_input, callCtx) {
1366
+ const [authStatus, cliProbe, receipts] = await Promise.all([
1367
+ auth.status(),
1368
+ cli.probe(callCtx.signal),
1369
+ a2a.listReceipts(10)
1370
+ ]);
1371
+ return {
1372
+ auth: authStatus,
1373
+ wecom_auth_url: WECOM_LOGIN_URL,
1374
+ cli: cliProbe,
1375
+ recent_receipts: receipts
1376
+ };
1377
+ },
1378
+ async startLogin(_input, callCtx) {
1379
+ return auth.start({ signal: callCtx.signal });
1380
+ },
1381
+ async finishLogin(input, callCtx) {
1382
+ const raw = input;
1383
+ const waitSeconds = typeof raw?.wait_seconds === "number" ? raw.wait_seconds : 0;
1384
+ return { auth: waitSeconds > 0 ? await auth.waitForLogin({
1385
+ waitSeconds,
1386
+ signal: callCtx.signal
1387
+ }) : await (async () => {
1388
+ await auth.finish({ signal: callCtx.signal });
1389
+ if ((await auth.status()).phase === "ready") await auth.ensureWecom({ signal: callCtx.signal });
1390
+ return auth.status();
1391
+ })() };
1392
+ },
1393
+ async logout() {
1394
+ return { auth: await auth.logout() };
1395
+ },
1396
+ async recentReceipts(input) {
1397
+ const raw = input;
1398
+ return { receipts: await a2a.listReceipts(typeof raw?.limit === "number" ? raw.limit : 20) };
1399
+ }
1400
+ });
1401
+ emitAuthChanged = async (status) => {
1402
+ await rpcReg.events.emit("authChanged", {
1403
+ phase: status.phase,
1404
+ wecom_configured: status.wecom_configured
1405
+ }).catch(() => {});
1406
+ };
1407
+ const toolReg = await ctx.tool.transform((editor) => {
1408
+ editor.namespace({
1409
+ name: "wecom",
1410
+ description: "Enterprise WeChat (WeCom) & Dayuan A2A read-only integration (desktop-free QR auth, group/chat summary queries, optional @wecom/cli office bridge)."
1411
+ });
1412
+ editor.add({
1413
+ name: "wecom_status",
1414
+ description: "Inspect WeCom / WorkBuddy cloud auth status (zero network calls), optional @wecom/cli availability, and recent Dayuan query receipts.",
1415
+ input: {
1416
+ type: "object",
1417
+ properties: { include_receipts: {
1418
+ type: "boolean",
1419
+ description: "Include recent Dayuan A2A receipts (default true)."
1420
+ } },
1421
+ additionalProperties: false
1422
+ },
1423
+ output: {
1424
+ type: "object",
1425
+ properties: {
1426
+ auth: {
1427
+ type: "object",
1428
+ additionalProperties: true
1429
+ },
1430
+ wecom_auth_url: { type: "string" },
1431
+ cli: {
1432
+ type: "object",
1433
+ additionalProperties: true
1434
+ },
1435
+ recent_receipts: {
1436
+ type: "array",
1437
+ items: {
1438
+ type: "object",
1439
+ additionalProperties: true
1440
+ }
1441
+ }
1442
+ },
1443
+ additionalProperties: true
1444
+ },
1445
+ options: {
1446
+ namespace: "wecom",
1447
+ codemode: true
1448
+ },
1449
+ async execute(rawInput, toolCtx) {
1450
+ const input = rawInput ?? {};
1451
+ const [authStatus, cliProbe, receipts] = await Promise.all([
1452
+ auth.status(),
1453
+ cli.probe(toolCtx.signal),
1454
+ input.include_receipts === false ? Promise.resolve([]) : a2a.listReceipts(10)
1455
+ ]);
1456
+ return {
1457
+ output: {
1458
+ auth: authStatus,
1459
+ wecom_auth_url: WECOM_LOGIN_URL,
1460
+ cli: cliProbe,
1461
+ recent_receipts: receipts
1462
+ },
1463
+ content: formatStatusText(authStatus, cliProbe.available, receipts.length)
1464
+ };
1465
+ }
1466
+ });
1467
+ editor.add({
1468
+ name: "wecom_login",
1469
+ description: "Manage desktop-free WeCom QR login via WorkBuddy cloud: start QR session, wait for scan & WeCom token exchange, get secondary wecom-auth URL, or logout.",
1470
+ input: {
1471
+ type: "object",
1472
+ properties: {
1473
+ mode: {
1474
+ type: "string",
1475
+ enum: [
1476
+ "start",
1477
+ "finish",
1478
+ "wait",
1479
+ "wecom_auth",
1480
+ "logout"
1481
+ ],
1482
+ description: "start: create/reuse QR login URL; finish: single poll check; wait: poll until scan completes and exchange WeCom token; wecom_auth: return secondary WeCom authorization URL; logout: clear stored credentials."
1483
+ },
1484
+ wait_seconds: {
1485
+ type: "number",
1486
+ description: "Max seconds to wait when mode is \"wait\" (default 60, max 300)."
1487
+ }
1488
+ },
1489
+ additionalProperties: false
1490
+ },
1491
+ output: {
1492
+ type: "object",
1493
+ properties: {
1494
+ authorization_url: { type: "string" },
1495
+ state: { type: "string" },
1496
+ expires_in_seconds: { type: "number" },
1497
+ desktop_required: { type: "boolean" },
1498
+ reused: { type: "boolean" },
1499
+ auth: {
1500
+ type: "object",
1501
+ additionalProperties: true
1502
+ },
1503
+ result: {
1504
+ type: "object",
1505
+ additionalProperties: true
1506
+ }
1507
+ },
1508
+ additionalProperties: true
1509
+ },
1510
+ options: {
1511
+ namespace: "wecom",
1512
+ codemode: true
1513
+ },
1514
+ async execute(rawInput, toolCtx) {
1515
+ const input = rawInput ?? {};
1516
+ const mode = input.mode ?? "start";
1517
+ try {
1518
+ if (mode === "wecom_auth") {
1519
+ const info = auth.wecomLoginInfo();
1520
+ return {
1521
+ output: info,
1522
+ content: `请在浏览器打开以下企业微信应用授权链接并确认:\n${info.authorization_url}`
1523
+ };
1524
+ }
1525
+ if (mode === "logout") return {
1526
+ output: { auth: await auth.logout() },
1527
+ content: "已清除本机保存的 WorkBuddy / 企业微信登录凭据。"
1528
+ };
1529
+ if (mode === "start") {
1530
+ const started = await auth.start({ signal: toolCtx.signal });
1531
+ return {
1532
+ output: started,
1533
+ content: [
1534
+ "请在浏览器打开以下链接,并用手机企业微信扫码确认(无需安装桌面客户端):",
1535
+ started.authorization_url,
1536
+ "",
1537
+ "扫码确认后,调用 wecom_login({ mode: \"wait\" }) 即可完成换票。"
1538
+ ].join("\n")
1539
+ };
1540
+ }
1541
+ if (mode === "finish") {
1542
+ const finishResult = await auth.finish({ signal: toolCtx.signal });
1543
+ if (finishResult.phase === "ready") await auth.ensureWecom({ signal: toolCtx.signal });
1544
+ const status$1 = await auth.status();
1545
+ return {
1546
+ output: {
1547
+ result: finishResult,
1548
+ auth: status$1
1549
+ },
1550
+ content: `当前登录阶段: ${status$1.phase},企微凭据就绪: ${status$1.wecom_configured ? "是" : "否"}`
1551
+ };
1552
+ }
1553
+ const waitSeconds = typeof input.wait_seconds === "number" ? input.wait_seconds : 60;
1554
+ await toolCtx.progress({ message: "正在等待手机企业微信扫码确认并换取凭据..." });
1555
+ const status = await auth.waitForLogin({
1556
+ waitSeconds,
1557
+ signal: toolCtx.signal
1558
+ });
1559
+ return {
1560
+ output: { auth: status },
1561
+ content: status.phase === "ready" && status.wecom_configured ? "企业微信登录与换票已完成,后续查询将自动静默续期。" : `当前阶段: ${status.phase}(若仍未完成扫码,请确认已在浏览器完成企微扫码后再试)。`
1562
+ };
1563
+ } catch (err) {
1564
+ throw new Error(formatErrorHint(err));
1565
+ }
1566
+ }
1567
+ });
1568
+ editor.add({
1569
+ name: "wecom_read_start",
1570
+ description: "Start a strictly read-only Dayuan A2A query (search_groups, read_chat, or search_messages). Returns AI-generated summaries (is_summary: true), never raw verbatim logs.",
1571
+ input: {
1572
+ type: "object",
1573
+ properties: {
1574
+ action: {
1575
+ type: "string",
1576
+ enum: [
1577
+ "search_groups",
1578
+ "read_chat",
1579
+ "search_messages"
1580
+ ],
1581
+ description: "Read-only Dayuan A2A query action."
1582
+ },
1583
+ query: {
1584
+ type: "string",
1585
+ description: "Search keyword for search_groups or search_messages."
1586
+ },
1587
+ chat_name: {
1588
+ type: "string",
1589
+ description: "Target group/chat name (required for read_chat, optional scope for search_messages)."
1590
+ },
1591
+ question: {
1592
+ type: "string",
1593
+ description: "Question to answer from the chat (required for read_chat)."
1594
+ },
1595
+ time_range: {
1596
+ type: "string",
1597
+ description: "Optional time range hint, e.g. \"今天\" or \"最近3天\"."
1598
+ },
1599
+ limit: {
1600
+ type: "number",
1601
+ description: "Max group candidates for search_groups (1-20)."
1602
+ },
1603
+ request_id: {
1604
+ type: "string",
1605
+ description: "Optional stable idempotency key to prevent duplicate submissions."
1606
+ },
1607
+ wait_seconds: {
1608
+ type: "number",
1609
+ description: "Seconds to poll before returning (default 20, 0 for immediate async return)."
1610
+ }
1611
+ },
1612
+ required: ["action"],
1613
+ additionalProperties: false
1614
+ },
1615
+ output: DAYUAN_TASK_RESULT_OUTPUT_SCHEMA,
1616
+ options: {
1617
+ namespace: "wecom",
1618
+ codemode: true
1619
+ },
1620
+ async execute(rawInput, toolCtx) {
1621
+ const input = rawInput ?? {};
1622
+ const action = input.action;
1623
+ let typedInput;
1624
+ if (action === "search_groups") typedInput = {
1625
+ action: "search_groups",
1626
+ query: String(input.query ?? ""),
1627
+ limit: typeof input.limit === "number" ? input.limit : void 0,
1628
+ request_id: typeof input.request_id === "string" ? input.request_id : void 0,
1629
+ wait_seconds: typeof input.wait_seconds === "number" ? input.wait_seconds : void 0
1630
+ };
1631
+ else if (action === "read_chat") typedInput = {
1632
+ action: "read_chat",
1633
+ chat_name: String(input.chat_name ?? ""),
1634
+ question: String(input.question ?? ""),
1635
+ time_range: typeof input.time_range === "string" ? input.time_range : void 0,
1636
+ request_id: typeof input.request_id === "string" ? input.request_id : void 0,
1637
+ wait_seconds: typeof input.wait_seconds === "number" ? input.wait_seconds : void 0
1638
+ };
1639
+ else if (action === "search_messages") typedInput = {
1640
+ action: "search_messages",
1641
+ query: String(input.query ?? ""),
1642
+ chat_name: typeof input.chat_name === "string" ? input.chat_name : void 0,
1643
+ time_range: typeof input.time_range === "string" ? input.time_range : void 0,
1644
+ request_id: typeof input.request_id === "string" ? input.request_id : void 0,
1645
+ wait_seconds: typeof input.wait_seconds === "number" ? input.wait_seconds : void 0
1646
+ };
1647
+ else throw new Error("INVALID_ACTION");
1648
+ try {
1649
+ const result = await a2a.start(typedInput, {
1650
+ signal: toolCtx.signal,
1651
+ onProgress: async (update) => {
1652
+ await toolCtx.progress({
1653
+ task_id: update.task_id,
1654
+ state: update.state,
1655
+ poll_count: update.poll_count
1656
+ });
1657
+ }
1658
+ });
1659
+ return {
1660
+ output: result,
1661
+ content: formatTaskSummaryText(result)
1662
+ };
1663
+ } catch (err) {
1664
+ throw new Error(formatErrorHint(err));
1665
+ }
1666
+ }
1667
+ });
1668
+ editor.add({
1669
+ name: "wecom_read_result",
1670
+ description: "Poll or retrieve the cached result of a Dayuan A2A read-only task by task_id.",
1671
+ input: {
1672
+ type: "object",
1673
+ properties: {
1674
+ task_id: {
1675
+ type: "string",
1676
+ description: "Task ID returned by wecom_read_start."
1677
+ },
1678
+ wait_seconds: {
1679
+ type: "number",
1680
+ description: "Seconds to poll before returning (default 20)."
1681
+ }
1682
+ },
1683
+ required: ["task_id"],
1684
+ additionalProperties: false
1685
+ },
1686
+ output: DAYUAN_TASK_RESULT_OUTPUT_SCHEMA,
1687
+ options: {
1688
+ namespace: "wecom",
1689
+ codemode: true
1690
+ },
1691
+ async execute(rawInput, toolCtx) {
1692
+ const input = rawInput ?? {};
1693
+ try {
1694
+ const result = await a2a.getResult({
1695
+ task_id: input.task_id,
1696
+ wait_seconds: input.wait_seconds
1697
+ }, {
1698
+ signal: toolCtx.signal,
1699
+ onProgress: async (update) => {
1700
+ await toolCtx.progress({
1701
+ task_id: update.task_id,
1702
+ state: update.state,
1703
+ poll_count: update.poll_count
1704
+ });
1705
+ }
1706
+ });
1707
+ return {
1708
+ output: result,
1709
+ content: formatTaskSummaryText(result)
1710
+ };
1711
+ } catch (err) {
1712
+ throw new Error(formatErrorHint(err));
1713
+ }
1714
+ }
1715
+ });
1716
+ editor.add({
1717
+ name: "wecom_read_reply",
1718
+ description: "Send a plain-text clarification reply to a Dayuan A2A task in input_required state. Automatically blocks approval cards for safety.",
1719
+ input: {
1720
+ type: "object",
1721
+ properties: {
1722
+ task_id: {
1723
+ type: "string",
1724
+ description: "Task ID waiting for plain-text clarification."
1725
+ },
1726
+ text: {
1727
+ type: "string",
1728
+ description: "Clarification text to send."
1729
+ },
1730
+ request_id: {
1731
+ type: "string",
1732
+ description: "Optional message idempotency key."
1733
+ },
1734
+ wait_seconds: {
1735
+ type: "number",
1736
+ description: "Seconds to wait after replying (default 20)."
1737
+ }
1738
+ },
1739
+ required: ["task_id", "text"],
1740
+ additionalProperties: false
1741
+ },
1742
+ output: DAYUAN_TASK_RESULT_OUTPUT_SCHEMA,
1743
+ options: {
1744
+ namespace: "wecom",
1745
+ codemode: true
1746
+ },
1747
+ async execute(rawInput, toolCtx) {
1748
+ const input = rawInput ?? {};
1749
+ try {
1750
+ const result = await a2a.reply(input, {
1751
+ signal: toolCtx.signal,
1752
+ onProgress: async (update) => {
1753
+ await toolCtx.progress({
1754
+ task_id: update.task_id,
1755
+ state: update.state,
1756
+ poll_count: update.poll_count
1757
+ });
1758
+ }
1759
+ });
1760
+ return {
1761
+ output: result,
1762
+ content: formatTaskSummaryText(result)
1763
+ };
1764
+ } catch (err) {
1765
+ throw new Error(formatErrorHint(err));
1766
+ }
1767
+ }
1768
+ });
1769
+ if (enableCliTool) editor.add({
1770
+ name: "wecom_cli",
1771
+ description: "Optional bridge to official @wecom/cli for structured office domains (doc, smartsheet, calendar, meeting, mail, wedrive, contact, auth). Read-only by default.",
1772
+ input: {
1773
+ type: "object",
1774
+ properties: {
1775
+ domain: {
1776
+ type: "string",
1777
+ enum: [...ALLOWED_CLI_DOMAINS],
1778
+ description: "Allowed @wecom/cli office domain."
1779
+ },
1780
+ args: {
1781
+ type: "array",
1782
+ items: { type: "string" },
1783
+ description: "Subcommand and flags passed directly to the wecom CLI (no shell interpolation)."
1784
+ },
1785
+ timeout_ms: {
1786
+ type: "number",
1787
+ description: "Optional execution timeout in milliseconds (default 30000)."
1788
+ }
1789
+ },
1790
+ required: ["domain", "args"],
1791
+ additionalProperties: false
1792
+ },
1793
+ output: {
1794
+ type: "object",
1795
+ properties: {
1796
+ ok: { type: "boolean" },
1797
+ domain: { type: "string" },
1798
+ args: {
1799
+ type: "array",
1800
+ items: { type: "string" }
1801
+ },
1802
+ exit_code: { type: "number" },
1803
+ stdout: { type: "string" },
1804
+ stderr: { type: "string" },
1805
+ data: {}
1806
+ },
1807
+ additionalProperties: true
1808
+ },
1809
+ options: {
1810
+ namespace: "wecom",
1811
+ codemode: true
1812
+ },
1813
+ async execute(rawInput, toolCtx) {
1814
+ const input = rawInput ?? {};
1815
+ try {
1816
+ const res = await cli.run(input, toolCtx.signal);
1817
+ return {
1818
+ output: res,
1819
+ content: res.ok ? res.stdout.trim() || JSON.stringify(res.data ?? { ok: true }) : `wecom ${input.domain} 退出码 ${res.exit_code}: ${res.stderr.trim() || res.stdout.trim()}`
1820
+ };
1821
+ } catch (err) {
1822
+ throw new Error(formatErrorHint(err));
1823
+ }
1824
+ }
1825
+ });
1826
+ });
1827
+ const cmdReg = await ctx.command.transform((editor) => {
1828
+ editor.add({
1829
+ name: "wecom-login",
1830
+ description: "Generate a desktop-free WeCom QR login link via WorkBuddy cloud",
1831
+ async execute(invocation) {
1832
+ const started = await auth.start();
1833
+ await ctx.session.synthetic({
1834
+ sessionID: invocation.sessionID,
1835
+ description: "WeCom QR Login",
1836
+ resume: false,
1837
+ text: [
1838
+ "请在浏览器打开以下链接,并用手机企业微信扫码确认(无需安装桌面客户端):",
1839
+ started.authorization_url,
1840
+ "",
1841
+ "扫码完成后,告诉助手「我已扫码」或调用 `wecom_login({ mode: \"wait\" })` 完成换票。"
1842
+ ].join("\n")
1843
+ });
1844
+ }
1845
+ });
1846
+ editor.add({
1847
+ name: "wecom-status",
1848
+ description: "Show current WeCom / Dayuan A2A connection status",
1849
+ async execute(invocation) {
1850
+ const [authStatus, cliProbe, receipts] = await Promise.all([
1851
+ auth.status(),
1852
+ cli.probe(),
1853
+ a2a.listReceipts(5)
1854
+ ]);
1855
+ await ctx.session.synthetic({
1856
+ sessionID: invocation.sessionID,
1857
+ description: "WeCom Status",
1858
+ resume: false,
1859
+ text: formatStatusText(authStatus, cliProbe.available, receipts.length)
1860
+ });
1861
+ }
1862
+ });
1863
+ editor.add({
1864
+ name: "wecom-logout",
1865
+ description: "Clear stored WorkBuddy & WeCom credentials",
1866
+ async execute(invocation) {
1867
+ await auth.logout();
1868
+ await ctx.session.synthetic({
1869
+ sessionID: invocation.sessionID,
1870
+ description: "WeCom Logout",
1871
+ resume: false,
1872
+ text: "已清除本机保存的 WorkBuddy / 企业微信登录凭据。"
1873
+ });
1874
+ }
1875
+ });
1876
+ });
1877
+ const skillReg = await ctx.skill.transform((editor) => {
1878
+ editor.add({
1879
+ id: "wecom-dayuan",
1880
+ name: "wecom-dayuan",
1881
+ description: "企业微信大圆 A2A 只读群聊摘要与无桌面端扫码登录规范(含审批卡人工拦截与幂等回执要求)。",
1882
+ autoinvoke: false,
1883
+ path: "/embedded/opencode-plugin-wecom/wecom-dayuan/SKILL.md",
1884
+ content: EMBEDDED_SKILL_CONTENT
1885
+ });
1886
+ });
1887
+ return async () => {
1888
+ await Promise.allSettled([
1889
+ rpcReg.dispose(),
1890
+ toolReg.dispose(),
1891
+ cmdReg.dispose(),
1892
+ skillReg.dispose()
1893
+ ]);
1894
+ };
1895
+ }
1896
+ });
1897
+ }
1898
+ var src_default = createWecomPlugin();
1899
+
1900
+ //#endregion
1901
+ export { ALLOWED_CLI_DOMAINS, DayuanA2AClient, PLUGIN_ID, WECOM_LOGIN_URL, WORKBUDDY_ORIGIN, WecomCliBridge, WecomError, WecomRpc, WorkBuddyAuth, createWecomPlugin, src_default as default, formatLoginUrl };