dsh-message-gateway 0.1.19 → 0.1.21

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/lib/index.js CHANGED
@@ -15,8 +15,8 @@ __export(gateway_store_exports, {
15
15
  saveStore: () => saveStore
16
16
  });
17
17
  import { chmod, mkdir, readFile, rename, writeFile } from "node:fs/promises";
18
- import { homedir } from "node:os";
19
- import { join } from "node:path";
18
+ import { homedir as homedir2 } from "node:os";
19
+ import { join as join2 } from "node:path";
20
20
  async function loadStore() {
21
21
  try {
22
22
  const text = await readFile(FILE, "utf8");
@@ -30,7 +30,7 @@ async function loadStore() {
30
30
  }
31
31
  }
32
32
  async function saveStore(data) {
33
- await mkdir(join(homedir(), ".dsh"), { recursive: true });
33
+ await mkdir(join2(homedir2(), ".dsh"), { recursive: true });
34
34
  const tmp = `${FILE}.tmp`;
35
35
  await writeFile(tmp, JSON.stringify(data, null, 2), { mode: 384 });
36
36
  await chmod(tmp, 384);
@@ -40,7 +40,7 @@ var FILE;
40
40
  var init_gateway_store = __esm({
41
41
  "src/host/gateway-store.ts"() {
42
42
  "use strict";
43
- FILE = join(homedir(), ".dsh", "gateway.json");
43
+ FILE = join2(homedir2(), ".dsh", "gateway.json");
44
44
  }
45
45
  });
46
46
 
@@ -3201,22 +3201,216 @@ function sanitizeSecrets(text) {
3201
3201
 
3202
3202
  // src/host/wecom-bridge.ts
3203
3203
  import { WSClient } from "@wecom/aibot-node-sdk";
3204
+
3205
+ // src/host/wecom-smartsheet.ts
3206
+ import { createRequire } from "node:module";
3207
+ import { execFile } from "node:child_process";
3208
+ import { createHash } from "node:crypto";
3209
+ import { existsSync, mkdirSync } from "node:fs";
3210
+ import { homedir } from "node:os";
3211
+ import { join, dirname } from "node:path";
3212
+ function configDirFor(botId, secret) {
3213
+ const fp = createHash("sha256").update(`${botId}:${secret}`, "utf8").digest("hex").slice(0, 8);
3214
+ return join(homedir(), ".local", "share", "dsh-message-gateway", "wecom-cli", `${botId.replace(/[^A-Za-z0-9_-]/g, "_")}-${fp}`);
3215
+ }
3216
+ function resolveCliBinary() {
3217
+ const require2 = createRequire(import.meta.url);
3218
+ const platformMap = {
3219
+ "darwin-arm64": "@wecom/cli-darwin-arm64",
3220
+ "darwin-x64": "@wecom/cli-darwin-x64",
3221
+ "linux-arm64": "@wecom/cli-linux-arm64",
3222
+ "linux-x64": "@wecom/cli-linux-x64",
3223
+ "win32-x64": "@wecom/cli-win32-x64"
3224
+ };
3225
+ const key = `${process.platform}-${process.arch}`;
3226
+ const pkg = platformMap[key];
3227
+ if (!pkg) throw new Error(`wecom-cli: unsupported platform ${key}`);
3228
+ const binaryName = process.platform === "win32" ? "wecom-cli.exe" : "wecom-cli";
3229
+ try {
3230
+ const pkgDir = require2.resolve(`${pkg}/package.json`);
3231
+ return join(dirname(pkgDir), "bin", binaryName);
3232
+ } catch {
3233
+ throw new Error("wecom-cli: cannot locate platform binary, reinstall @wecom/cli (do not use --no-optional)");
3234
+ }
3235
+ }
3236
+ function runCli(bin, argv, configDir, timeoutMs = 9e4) {
3237
+ return new Promise((resolve, reject) => {
3238
+ const env = {
3239
+ ...process.env,
3240
+ WECOM_CLI_CONFIG_DIR: configDir,
3241
+ WECOM_CLI_LOG_LEVEL: "warn"
3242
+ };
3243
+ const child = execFile(bin, argv, { env, timeout: timeoutMs, windowsHide: true }, (error, stdout, stderr) => {
3244
+ if (error && error.code === "ETIMEDOUT") {
3245
+ reject(new Error(`wecom-cli \u6267\u884C\u8D85\u65F6\uFF1A${argv.join(" ")}`));
3246
+ return;
3247
+ }
3248
+ const code = error === null ? 0 : typeof error.code === "number" ? error.code : 1;
3249
+ resolve({ code, stdout: String(stdout), stderr: String(stderr) });
3250
+ });
3251
+ child.stdin?.end();
3252
+ });
3253
+ }
3254
+ function isAuthorized(dir) {
3255
+ return existsSync(join(dir, "credentials.enc")) && existsSync(join(dir, ".encryption_key"));
3256
+ }
3257
+ var WecomSmartsheetClient = class {
3258
+ constructor(creds) {
3259
+ this.creds = creds;
3260
+ this.bin = resolveCliBinary();
3261
+ const botId = creds.botId ?? "";
3262
+ const secret = creds.secret ?? "";
3263
+ if (!botId || !secret) throw new Error("\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u51ED\u636E\u4E0D\u5B8C\u6574\uFF08\u7F3A\u5C11 botId \u6216 secret\uFF09");
3264
+ this.dir = configDirFor(botId, secret);
3265
+ }
3266
+ bin;
3267
+ dir;
3268
+ authDone = false;
3269
+ /** 确保已授权(幂等短路,避免重复鉴权触发频率限制)。 */
3270
+ async ensureAuthorized() {
3271
+ if (this.authDone && isAuthorized(this.dir)) return;
3272
+ mkdirSync(this.dir, { recursive: true });
3273
+ if (!isAuthorized(this.dir)) {
3274
+ const res = await runCli(this.bin, ["auth", "init", "--bot-id", this.creds.botId ?? "", "--secret", this.creds.secret ?? ""], this.dir, 6e4);
3275
+ if (res.code !== 0) {
3276
+ throw new Error(`\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u6388\u6743\u5931\u8D25\uFF1A${res.stderr.trim() || res.stdout.trim() || `exit ${res.code}`}`);
3277
+ }
3278
+ }
3279
+ this.authDone = true;
3280
+ }
3281
+ /** 映射字段类型为企微官方字段类型标识。 */
3282
+ mapFieldType(type) {
3283
+ switch (type?.toLowerCase()) {
3284
+ case "number":
3285
+ return "number";
3286
+ case "single_select":
3287
+ case "select":
3288
+ return "single_select";
3289
+ case "multi_select":
3290
+ return "select";
3291
+ case "date":
3292
+ case "date_time":
3293
+ case "datetime":
3294
+ return "date_time";
3295
+ case "user":
3296
+ case "member":
3297
+ return "user";
3298
+ case "checkbox":
3299
+ return "checkbox";
3300
+ case "text":
3301
+ default:
3302
+ return "text";
3303
+ }
3304
+ }
3305
+ /**
3306
+ * 创建一份全新的在线智能表格(Smartsheet)。
3307
+ */
3308
+ async createSmartsheet(options) {
3309
+ try {
3310
+ await this.ensureAuthorized();
3311
+ const fields = (options.fields && options.fields.length > 0 ? options.fields : [
3312
+ { title: "\u6807\u9898", type: "text" },
3313
+ { title: "\u72B6\u6001", type: "single_select", options: ["\u672A\u5F00\u59CB", "\u8FDB\u884C\u4E2D", "\u5DF2\u5B8C\u6210"] },
3314
+ { title: "\u8D1F\u8D23\u4EBA", type: "user" },
3315
+ { title: "\u622A\u6B62\u65E5\u671F", type: "date_time" }
3316
+ ]).map((f, idx) => {
3317
+ const fieldType = this.mapFieldType(f.type);
3318
+ const item = {
3319
+ field_title: f.title,
3320
+ field_type: fieldType
3321
+ };
3322
+ if ((fieldType === "single_select" || fieldType === "select") && f.options) {
3323
+ item[fieldType === "select" ? "property_select" : "property_single_select"] = {
3324
+ options: f.options.map((text, oi) => ({ id: String(oi + 1), text: String(text) }))
3325
+ };
3326
+ }
3327
+ void idx;
3328
+ return item;
3329
+ });
3330
+ const rows = (options.records ?? []).map((rec) => {
3331
+ const values = fields.map((f) => {
3332
+ const title = String(f.field_title);
3333
+ const raw = rec[title];
3334
+ const fieldType = String(f.field_type);
3335
+ if (fieldType === "number") {
3336
+ const n = Number(raw ?? 0);
3337
+ return { data_type: "NUMBER", cell_value: { number: Number.isFinite(n) ? n : 0 } };
3338
+ }
3339
+ if (fieldType === "single_select" || fieldType === "select") {
3340
+ const text = String(raw ?? "");
3341
+ const f2 = f;
3342
+ const property = f2.property_single_select ?? f2.property_select ?? {};
3343
+ const options2 = property.options ?? [];
3344
+ const hit = options2.find((o) => o.text === text);
3345
+ return {
3346
+ data_type: "SELECT",
3347
+ cell_value: { select: { value: hit ? [hit.id] : [], options: options2 } }
3348
+ };
3349
+ }
3350
+ return { data_type: "TEXT", cell_value: { text: String(raw ?? "") } };
3351
+ });
3352
+ return { values };
3353
+ });
3354
+ const body = JSON.stringify({
3355
+ name: options.title || "\u65B0\u5EFA\u667A\u80FD\u8868\u683C",
3356
+ sheet_title: options.sheetTitle || "\u6570\u636E\u8868",
3357
+ fields,
3358
+ ...rows.length > 0 ? { grid_data: { start_row: 0, start_column: 0, rows } } : {}
3359
+ });
3360
+ const res = await runCli(this.bin, ["smartsheet", "create", "--json", body], this.dir, 9e4);
3361
+ if (res.code !== 0) {
3362
+ return { ok: false, error: `\u521B\u5EFA\u667A\u80FD\u8868\u683C\u5931\u8D25\uFF1A${res.stderr.trim() || res.stdout.trim() || `exit ${res.code}`}` };
3363
+ }
3364
+ const parsed = JSON.parse(res.stdout);
3365
+ if (parsed.errcode !== 0 || !parsed.docid) {
3366
+ return { ok: false, error: `\u521B\u5EFA\u667A\u80FD\u8868\u683C\u5931\u8D25 [${parsed.errcode}]: ${parsed.errmsg || "\u672A\u77E5\u9519\u8BEF"}` };
3367
+ }
3368
+ return { ok: true, docid: parsed.docid, url: parsed.url || `https://doc.weixin.qq.com/smartsheet/${parsed.docid}` };
3369
+ } catch (error) {
3370
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
3371
+ }
3372
+ }
3373
+ };
3374
+
3375
+ // src/host/wecom-bridge.ts
3204
3376
  var WecomBridge = class {
3205
3377
  constructor(cred, callbacks) {
3206
3378
  this.cred = cred;
3207
3379
  this.callbacks = callbacks;
3380
+ this.smartsheetClient = new WecomSmartsheetClient({
3381
+ botId: cred.botId,
3382
+ secret: cred.secret
3383
+ });
3208
3384
  }
3209
3385
  client = null;
3386
+ smartsheetClient = null;
3210
3387
  started = false;
3211
3388
  status = { state: "idle", detail: "", connectedAt: null };
3212
3389
  setStatus(state, detail = "") {
3213
3390
  this.status = {
3214
3391
  state,
3215
3392
  detail,
3216
- connectedAt: state === "connected" ? Date.now() : this.status.connectedAt
3393
+ connectedAt: state === "connected" ? this.status.connectedAt ?? Date.now() : null
3217
3394
  };
3218
3395
  this.callbacks.onStatus(this.status);
3219
3396
  }
3397
+ /** 获取智能表格操作客户端 */
3398
+ getSmartsheetClient() {
3399
+ return this.smartsheetClient;
3400
+ }
3401
+ /** 获取底层已认证连接的 WSClient 实例 */
3402
+ getClient() {
3403
+ return this.client;
3404
+ }
3405
+ /**
3406
+ * 创建企业微信智能表格。
3407
+ */
3408
+ async createSmartsheet(options) {
3409
+ if (!this.smartsheetClient) {
3410
+ return { ok: false, error: "\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u8868\u683C\u5BA2\u6237\u7AEF\u672A\u521D\u59CB\u5316" };
3411
+ }
3412
+ return await this.smartsheetClient.createSmartsheet(options);
3413
+ }
3220
3414
  /** 建立常驻连接(断线由 SDK 自动指数退避重连)。 */
3221
3415
  start() {
3222
3416
  if (this.started) return;
@@ -3224,7 +3418,9 @@ var WecomBridge = class {
3224
3418
  this.setStatus("connecting");
3225
3419
  const client = new WSClient({ botId: this.cred.botId, secret: this.cred.secret });
3226
3420
  this.client = client;
3227
- client.on("authenticated", () => this.setStatus("connected", `botId ${this.cred.botId}`));
3421
+ client.on("authenticated", () => {
3422
+ this.setStatus("connected", `botId ${this.cred.botId}`);
3423
+ });
3228
3424
  client.on("message.text", (frame) => {
3229
3425
  const content = frame.body?.text?.content ?? "";
3230
3426
  if (content.trim() !== "") this.callbacks.onText(content, frame);
@@ -5958,7 +6154,7 @@ ${cred.secret}`;
5958
6154
  }
5959
6155
 
5960
6156
  // src/host/callback-bridges.ts
5961
- import { createHash, createDecipheriv, createCipheriv, randomBytes } from "node:crypto";
6157
+ import { createHash as createHash2, createDecipheriv, createCipheriv, randomBytes } from "node:crypto";
5962
6158
  var TOKEN_TTL_MS = 7e6;
5963
6159
  var tokenCache = /* @__PURE__ */ new Map();
5964
6160
  function cachedToken(key) {
@@ -5971,7 +6167,7 @@ function setCachedToken(key, token) {
5971
6167
  }
5972
6168
  function sha1Sorted(parts) {
5973
6169
  const sorted = [...parts].sort();
5974
- return createHash("sha1").update(sorted.join("")).digest("hex");
6170
+ return createHash2("sha1").update(sorted.join("")).digest("hex");
5975
6171
  }
5976
6172
  function xmlField(xml, name) {
5977
6173
  const match = xml.match(new RegExp(`<${name}>(?:<!\\[CDATA\\[)?([\\s\\S]*?)(?:\\]\\]>)?<\\/${name}>`));
@@ -6759,9 +6955,9 @@ function apply(ctx, config = Config({})) {
6759
6955
  }
6760
6956
  });
6761
6957
  const disposeRoutes = registerGatewayRoutes(ctx, manager);
6762
- let disposeTool;
6958
+ let disposeTools;
6763
6959
  if (ctx.tools) {
6764
- disposeTool = ctx.tools.register(defineTool({
6960
+ const disposeSend = ctx.tools.register(defineTool({
6765
6961
  name: "send_chat_message",
6766
6962
  description: "\u5411\u5DF2\u8FDE\u63A5\u7684\u6D88\u606F\u5E73\u53F0\uFF08Telegram / Discord / \u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA / Email \u7B49\uFF09\u4E3B\u52A8\u63A8\u9001\u6587\u672C\u6D88\u606F\u3002\u4F8B\u5982\u628A\u4EE3\u7801\u603B\u7ED3\u3001\u4EFB\u52A1\u7ED3\u679C\u63A8\u9001\u81F3\u6307\u5B9A\u7684\u7FA4\u804A\u6216\u79C1\u4FE1\u9891\u9053\u3002",
6767
6963
  parameters: {
@@ -6825,9 +7021,66 @@ function apply(ctx, config = Config({})) {
6825
7021
  return `\u5DF2\u6210\u529F\u63A8\u9001\u81F3 [${platform}] \u76EE\u6807 ${target}`;
6826
7022
  }
6827
7023
  }));
7024
+ const disposeSmartsheet = ctx.tools.register(defineTool({
7025
+ name: "wecom_create_smartsheet",
7026
+ description: "\u5728\u4F01\u4E1A\u5FAE\u4FE1\u4E2D\u521B\u5EFA\u4E00\u4EFD\u5168\u65B0\u7684\u5728\u7EBF\u667A\u80FD\u8868\u683C\uFF08Smartsheet\uFF09\uFF0C\u652F\u6301\u5B9A\u4E49\u8868\u683C\u6807\u9898\u3001\u5B57\u6BB5\u5217\uFF08\u6587\u672C/\u5355\u9009/\u591A\u9009/\u4EBA\u5458/\u65E5\u671F/\u6570\u5B57\u7B49\uFF09\u4E0E\u521D\u59CB\u6570\u636E\u884C\uFF0C\u5E76\u8FD4\u56DE\u667A\u80FD\u8868\u683C\u5728\u7EBF\u8BBF\u95EE\u94FE\u63A5\u3002",
7027
+ parameters: {
7028
+ title: {
7029
+ type: "string",
7030
+ required: true,
7031
+ description: "\u667A\u80FD\u8868\u683C\u6587\u6863\u6807\u9898\uFF08\u5982\uFF1A2026\u5E74Q3\u9879\u76EE\u5F00\u53D1\u6392\u671F\u8868\uFF09"
7032
+ },
7033
+ sheetTitle: {
7034
+ type: "string",
7035
+ description: "\u9996\u4E2A\u5DE5\u4F5C\u8868\u540D\u79F0\uFF08\u9ED8\u8BA4\uFF1A\u6570\u636E\u8868\uFF09"
7036
+ },
7037
+ fields: {
7038
+ type: "array",
7039
+ description: '\u5217\u5B57\u6BB5\u5B9A\u4E49\u5217\u8868\uFF0C\u5982 [{"title": "\u4EFB\u52A1\u540D\u79F0", "type": "text"}, {"title": "\u72B6\u6001", "type": "single_select", "options": ["\u5F85\u529E", "\u8FDB\u884C\u4E2D", "\u5DF2\u5B8C\u6210"]}]'
7040
+ },
7041
+ records: {
7042
+ type: "array",
7043
+ description: '\u521D\u59CB\u586B\u5165\u7684\u6570\u636E\u884C\u5217\u8868\uFF0C\u5982 [{"\u4EFB\u52A1\u540D\u79F0": "\u9700\u6C42\u8BC4\u5BA1", "\u72B6\u6001": "\u5DF2\u5B8C\u6210"}]'
7044
+ }
7045
+ },
7046
+ output: {
7047
+ schema: { type: "string" },
7048
+ render: (_args, value) => [{ type: "text", text: String(value) }]
7049
+ },
7050
+ async execute(args) {
7051
+ const title = String(args.title ?? "").trim();
7052
+ if (!title) return "\u9519\u8BEF\uFF1A\u8868\u683C\u6807\u9898 title \u4E3A\u5FC5\u586B\u9879";
7053
+ const store = await loadStore();
7054
+ const wecomCred = store.platforms["wecom-aibot"] || store.platforms["wecom"];
7055
+ if (!wecomCred || !wecomCred.secret && !wecomCred.corpId && !wecomCred.botId) {
7056
+ return "\u9519\u8BEF\uFF1A\u672A\u5728\u6D88\u606F\u5E73\u53F0\u4E2D\u914D\u7F6E\u4F01\u4E1A\u5FAE\u4FE1\u51ED\u636E\uFF0C\u8BF7\u5148\u5728\u4FA7\u8FB9\u680F\u300C\u6D88\u606F\u5E73\u53F0\u300D\u4E2D\u914D\u7F6E\u4F01\u4E1A\u5FAE\u4FE1\u667A\u80FD\u673A\u5668\u4EBA\u6216\u81EA\u5EFA\u5E94\u7528\u51ED\u636E";
7057
+ }
7058
+ const client = new WecomSmartsheetClient({
7059
+ botId: wecomCred.botId,
7060
+ secret: wecomCred.secret,
7061
+ corpId: wecomCred.corpId
7062
+ });
7063
+ const res = await client.createSmartsheet({
7064
+ title,
7065
+ sheetTitle: args.sheetTitle,
7066
+ fields: args.fields,
7067
+ records: args.records
7068
+ });
7069
+ if (!res.ok) {
7070
+ return `\u521B\u5EFA\u667A\u80FD\u8868\u683C\u5931\u8D25\uFF1A${res.error}`;
7071
+ }
7072
+ return `\u2705 \u667A\u80FD\u8868\u683C\u300C${title}\u300D\u521B\u5EFA\u6210\u529F\uFF01
7073
+ - \u6587\u6863 ID: ${res.docid}
7074
+ - \u5728\u7EBF\u8BBF\u95EE\u94FE\u63A5: ${res.url}`;
7075
+ }
7076
+ }));
7077
+ disposeTools = () => {
7078
+ disposeSend();
7079
+ disposeSmartsheet();
7080
+ };
6828
7081
  }
6829
7082
  return () => {
6830
- disposeTool?.();
7083
+ disposeTools?.();
6831
7084
  disposeRoutes();
6832
7085
  void manager.dispose();
6833
7086
  };
@@ -6849,6 +7102,7 @@ export {
6849
7102
  WechatMpBridge,
6850
7103
  WecomAppBridge,
6851
7104
  WecomBridge,
7105
+ WecomSmartsheetClient,
6852
7106
  WhatsappBridge,
6853
7107
  apply,
6854
7108
  cleanBody,