@searchfe/openclaw-baiduapp 0.1.0-beta.1 → 0.1.0-beta.3

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 CHANGED
@@ -4231,7 +4231,16 @@ async function getAccessToken(account) {
4231
4231
  }
4232
4232
  const url = `${TOKEN_URL}?appKey=${encodeURIComponent(account.appKey)}&appSecret=${encodeURIComponent(account.appSecret)}`;
4233
4233
  const resp = await fetch(url);
4234
- const data = await resp.json();
4234
+ const text = await resp.text();
4235
+ if (!text) {
4236
+ throw new Error(`gettoken failed: empty response (status=${resp.status})`);
4237
+ }
4238
+ let data;
4239
+ try {
4240
+ data = JSON.parse(text);
4241
+ } catch {
4242
+ throw new Error(`gettoken failed: invalid JSON response (status=${resp.status}, body=${text.slice(0, 200)})`);
4243
+ }
4235
4244
  if (data.errcode !== void 0 && data.errcode !== 0) {
4236
4245
  throw new Error(`gettoken failed: ${data.errmsg ?? "unknown error"} (errcode=${data.errcode})`);
4237
4246
  }
@@ -4270,7 +4279,24 @@ async function sendBaiduAppMessage(account, target, message) {
4270
4279
  body: JSON.stringify(payload),
4271
4280
  headers: { "Content-Type": "application/json" }
4272
4281
  });
4273
- const data = await resp.json();
4282
+ const text = await resp.text();
4283
+ if (!text) {
4284
+ return {
4285
+ ok: false,
4286
+ errcode: resp.status,
4287
+ errmsg: `empty response from server (status=${resp.status})`
4288
+ };
4289
+ }
4290
+ let data;
4291
+ try {
4292
+ data = JSON.parse(text);
4293
+ } catch {
4294
+ return {
4295
+ ok: false,
4296
+ errcode: resp.status,
4297
+ errmsg: `invalid JSON response (status=${resp.status}, body=${text.slice(0, 200)})`
4298
+ };
4299
+ }
4274
4300
  return {
4275
4301
  ok: data.errcode === 0,
4276
4302
  errcode: data.errcode,
@@ -4308,8 +4334,9 @@ async function dispatchBaiduAppMessage(params) {
4308
4334
  const accountConfig = account?.config ?? {};
4309
4335
  const dmPolicy = resolveDmPolicy(accountConfig);
4310
4336
  const allowFrom = resolveAllowFrom(accountConfig);
4337
+ logger.debug(`dispatch: sender=${senderId} dmPolicy=${dmPolicy} allowFrom=[${allowFrom.join(",")}]`);
4311
4338
  if (dmPolicy === "disabled") {
4312
- logger.debug("policy rejected: dm disabled");
4339
+ logger.info(`dispatch rejected: dm disabled for account ${account.accountId}`);
4313
4340
  return;
4314
4341
  }
4315
4342
  const policyResult = checkDmPolicy({
@@ -4318,12 +4345,12 @@ async function dispatchBaiduAppMessage(params) {
4318
4345
  allowFrom
4319
4346
  });
4320
4347
  if (!policyResult.allowed) {
4321
- logger.debug(`policy rejected: ${policyResult.reason}`);
4348
+ logger.info(`dispatch rejected: policy=${dmPolicy} reason=${policyResult.reason} sender=${senderId}`);
4322
4349
  return;
4323
4350
  }
4324
4351
  const channel = core.channel;
4325
4352
  if (!channel?.routing?.resolveAgentRoute || !channel.reply?.dispatchReplyWithBufferedBlockDispatcher) {
4326
- logger.debug("core routing or buffered dispatcher missing, skipping dispatch");
4353
+ logger.warn("core routing or buffered dispatcher missing, skipping dispatch");
4327
4354
  return;
4328
4355
  }
4329
4356
  const route = channel.routing.resolveAgentRoute({
@@ -4332,7 +4359,13 @@ async function dispatchBaiduAppMessage(params) {
4332
4359
  accountId: account.accountId,
4333
4360
  peer: { kind: "dm", id: chatId }
4334
4361
  });
4362
+ logger.info(
4363
+ `route resolved: sessionKey=${route.sessionKey} agentId=${route.agentId ?? "default"} accountId=${route.accountId}`
4364
+ );
4335
4365
  const rawBody = extractBaiduAppContent(msg);
4366
+ logger.debug(
4367
+ `message content extracted: len=${rawBody.length} preview="${rawBody.slice(0, 80)}${rawBody.length > 80 ? "..." : ""}"`
4368
+ );
4336
4369
  const fromLabel = `user:${senderId}`;
4337
4370
  const storePath = channel.session?.resolveStorePath?.(safeCfg.session?.store, {
4338
4371
  agentId: route.agentId
@@ -4398,6 +4431,7 @@ async function dispatchBaiduAppMessage(params) {
4398
4431
  });
4399
4432
  }
4400
4433
  const tableMode = channel.text?.resolveMarkdownTableMode ? channel.text.resolveMarkdownTableMode({ cfg: safeCfg, channel: "baidu-app", accountId: account.accountId }) : void 0;
4434
+ logger.info(`dispatching to agent: sessionKey=${route.sessionKey} sender=${senderId}`);
4401
4435
  await channel.reply.dispatchReplyWithBufferedBlockDispatcher({
4402
4436
  ctx: ctxPayload,
4403
4437
  cfg: safeCfg,
@@ -4405,9 +4439,11 @@ async function dispatchBaiduAppMessage(params) {
4405
4439
  deliver: async (payload) => {
4406
4440
  const rawText = payload.text ?? "";
4407
4441
  if (!rawText.trim()) {
4442
+ logger.debug("deliver callback: empty text, skipping");
4408
4443
  return;
4409
4444
  }
4410
4445
  const converted = channel.text?.convertMarkdownTables && tableMode ? channel.text.convertMarkdownTables(rawText, tableMode) : rawText;
4446
+ logger.debug(`deliver callback: textLen=${converted.length}`);
4411
4447
  hooks.onChunk(converted);
4412
4448
  },
4413
4449
  onError: (err, info) => {
@@ -4416,6 +4452,7 @@ async function dispatchBaiduAppMessage(params) {
4416
4452
  }
4417
4453
  }
4418
4454
  });
4455
+ logger.info(`agent reply dispatch complete: sessionKey=${route.sessionKey} sender=${senderId}`);
4419
4456
  }
4420
4457
  function decodeEncodingAESKey(encodingAESKey) {
4421
4458
  const trimmed = encodingAESKey.trim();
@@ -4863,14 +4900,14 @@ async function handleBaiduAppWebhookRequest(req, res) {
4863
4900
  msgSignature = xmlData.MsgSignature ?? signature;
4864
4901
  msgTimestamp = xmlData.TimeStamp ?? timestamp;
4865
4902
  msgNonce = xmlData.Nonce ?? nonce;
4866
- logger.info(
4867
- `[baidu-app] inbound xml parsed: hasEncrypt=${Boolean(encrypt)}, msg_signature=${msgSignature ? "yes" : "no"}`
4868
- );
4903
+ logger.info(`inbound xml parsed: hasEncrypt=${Boolean(encrypt)}, msg_signature=${msgSignature ? "yes" : "no"}`);
4869
4904
  } else {
4870
4905
  try {
4871
4906
  const record = JSON.parse(rawBody);
4872
4907
  encrypt = String(record.encrypt ?? record.Encrypt ?? "");
4908
+ logger.info(`inbound json parsed: hasEncrypt=${Boolean(encrypt)}`);
4873
4909
  } catch {
4910
+ logger.warn(`inbound payload parse failed: not valid xml or json`);
4874
4911
  res.statusCode = 400;
4875
4912
  res.end("invalid payload format");
4876
4913
  return true;
@@ -4894,12 +4931,15 @@ async function handleBaiduAppWebhookRequest(req, res) {
4894
4931
  });
4895
4932
  });
4896
4933
  if (signatureMatched.length === 0) {
4934
+ logger.warn(`signature verification failed: checked ${targets.length} account(s), none matched`);
4897
4935
  res.statusCode = 401;
4898
4936
  res.end("unauthorized");
4899
4937
  return true;
4900
4938
  }
4939
+ logger.debug(`signature verified: ${signatureMatched.length} account(s) matched`);
4901
4940
  const decryptable = signatureMatched.filter((candidate) => Boolean(candidate.account.encodingAESKey));
4902
4941
  if (decryptable.length === 0) {
4942
+ logger.warn(`no account has encodingAESKey configured`);
4903
4943
  res.statusCode = 500;
4904
4944
  res.end("baidu-app not configured");
4905
4945
  return true;
@@ -4909,6 +4949,7 @@ async function handleBaiduAppWebhookRequest(req, res) {
4909
4949
  encrypt
4910
4950
  });
4911
4951
  if (decryptedCandidates.length === 0) {
4952
+ logger.warn(`decrypt failed for all ${decryptable.length} candidate account(s)`);
4912
4953
  res.statusCode = 400;
4913
4954
  res.end("decrypt failed");
4914
4955
  return true;
@@ -4916,6 +4957,7 @@ async function handleBaiduAppWebhookRequest(req, res) {
4916
4957
  const selected = selectDecryptedTarget({ candidates: decryptedCandidates, logger });
4917
4958
  const target = selected.target;
4918
4959
  if (!target.account.configured || !target.account.token || !target.account.encodingAESKey) {
4960
+ logger.warn(`selected account ${target.account.accountId} not fully configured`);
4919
4961
  res.statusCode = 500;
4920
4962
  res.end("baidu-app not configured");
4921
4963
  return true;
@@ -4924,9 +4966,16 @@ async function handleBaiduAppWebhookRequest(req, res) {
4924
4966
  target.statusSink?.({ lastInboundAt: Date.now() });
4925
4967
  const msgtype = String(msg.msgtype ?? msg.MsgType ?? "").toLowerCase();
4926
4968
  const msgid = msg.msgid ?? msg.MsgId ? String(msg.msgid ?? msg.MsgId) : void 0;
4969
+ const inboundSenderId = msg.from?.userid?.trim() ?? msg.FromUserName?.trim();
4970
+ logger.info(
4971
+ `inbound: type=${msgtype || "unknown"} msgid=${msgid ?? "none"} sender=${inboundSenderId ?? "unknown"} account=${target.account.accountId}`
4972
+ );
4927
4973
  if (msgtype === "stream") {
4928
4974
  const streamId2 = String(msg.stream?.id ?? "").trim();
4929
4975
  const state = streamId2 ? streams.get(streamId2) : void 0;
4976
+ logger.info(
4977
+ `[REPLY-MODE:STREAM-POLL] stream poll request: streamId=${streamId2 || "none"} found=${Boolean(state)} finished=${state?.finished ?? "n/a"} contentLen=${state?.content.length ?? 0}`
4978
+ );
4930
4979
  const reply = state ? buildStreamReplyFromState(state) : buildStreamReplyFromState({
4931
4980
  streamId: streamId2 || "unknown",
4932
4981
  finished: true,
@@ -4945,6 +4994,7 @@ async function handleBaiduAppWebhookRequest(req, res) {
4945
4994
  }
4946
4995
  if (msgid && msgidToStreamId.has(msgid)) {
4947
4996
  const streamId2 = msgidToStreamId.get(msgid) ?? "";
4997
+ logger.debug(`duplicate msgid detected: msgid=${msgid} streamId=${streamId2}, returning placeholder`);
4948
4998
  const reply = buildStreamPlaceholderReply(streamId2);
4949
4999
  jsonOk(
4950
5000
  res,
@@ -4961,11 +5011,13 @@ async function handleBaiduAppWebhookRequest(req, res) {
4961
5011
  const eventtype = String(
4962
5012
  msg.event?.eventtype ?? msg.Event ?? ""
4963
5013
  ).toLowerCase();
5014
+ logger.info(`event received: type=${eventtype || "unknown"}`);
4964
5015
  if (eventtype === "enter_chat" || eventtype === "subscribe") {
4965
5016
  const welcome = target.account.config.welcomeText?.trim();
4966
5017
  if (welcome && target.account.canSendActive) {
4967
5018
  const senderId2 = msg.from?.userid?.trim() ?? msg.FromUserName?.trim();
4968
5019
  if (senderId2) {
5020
+ logger.info(`sending welcome message to ${senderId2}`);
4969
5021
  sendBaiduAppMessage(target.account, { userId: senderId2 }, welcome).catch((err) => {
4970
5022
  logger.error(`failed to send welcome message: ${String(err)}`);
4971
5023
  });
@@ -5006,6 +5058,7 @@ async function handleBaiduAppWebhookRequest(req, res) {
5006
5058
  finished: false,
5007
5059
  content: ""
5008
5060
  });
5061
+ logger.info(`stream created: streamId=${streamId} msgid=${msgid ?? "none"}`);
5009
5062
  const core = tryGetBaiduAppRuntime();
5010
5063
  const senderId = msg.from?.userid?.trim() ?? msg.FromUserName?.trim();
5011
5064
  if (core) {
@@ -5013,6 +5066,9 @@ async function handleBaiduAppWebhookRequest(req, res) {
5013
5066
  if (state) {
5014
5067
  state.started = true;
5015
5068
  }
5069
+ logger.info(
5070
+ `agent dispatch started: streamId=${streamId} sender=${senderId ?? "unknown"} canSendActive=${target.account.canSendActive}`
5071
+ );
5016
5072
  const hooks = {
5017
5073
  onChunk: (text) => {
5018
5074
  const current = streams.get(streamId);
@@ -5020,6 +5076,9 @@ async function handleBaiduAppWebhookRequest(req, res) {
5020
5076
  return;
5021
5077
  }
5022
5078
  appendStreamContent(current, text);
5079
+ logger.debug(
5080
+ `chunk received: streamId=${streamId} chunkLen=${text.length} totalLen=${current.content.length}`
5081
+ );
5023
5082
  target.statusSink?.({ lastOutboundAt: Date.now() });
5024
5083
  },
5025
5084
  onError: (err) => {
@@ -5046,15 +5105,34 @@ async function handleBaiduAppWebhookRequest(req, res) {
5046
5105
  if (current) {
5047
5106
  current.finished = true;
5048
5107
  current.updatedAt = Date.now();
5108
+ const contentLen = current.content.trim().length;
5109
+ logger.info(
5110
+ `agent dispatch done: streamId=${streamId} contentLen=${contentLen} canSendActive=${target.account.canSendActive} sender=${senderId ?? "none"}`
5111
+ );
5112
+ if (!target.account.canSendActive) {
5113
+ logger.warn(
5114
+ `active send skipped: appKey/appSecret not configured for account ${target.account.accountId}`
5115
+ );
5116
+ } else if (!senderId) {
5117
+ logger.warn(`active send skipped: senderId is empty`);
5118
+ } else if (!contentLen) {
5119
+ logger.warn(`active send skipped: agent produced no content`);
5120
+ }
5049
5121
  if (target.account.canSendActive && senderId && current.content.trim()) {
5050
5122
  try {
5051
5123
  const chunks = splitMessageByBytes(current.content, MAX_MESSAGE_BYTES);
5052
- for (const chunk of chunks) {
5053
- await sendBaiduAppMessage(target.account, { userId: senderId }, chunk);
5124
+ logger.info(
5125
+ `[REPLY-MODE:ACTIVE-SEND] active send starting: streamId=${streamId} to=${senderId} chunks=${chunks.length} contentLen=${contentLen}`
5126
+ );
5127
+ for (let i = 0; i < chunks.length; i++) {
5128
+ await sendBaiduAppMessage(target.account, { userId: senderId }, chunks[i]);
5129
+ logger.debug(`active send chunk ${i + 1}/${chunks.length} sent: streamId=${streamId}`);
5054
5130
  }
5055
- logger.info(`active send complete: streamId=${streamId}, ${chunks.length} chunks`);
5131
+ logger.info(
5132
+ `[REPLY-MODE:ACTIVE-SEND] active send complete: streamId=${streamId} chunks=${chunks.length}`
5133
+ );
5056
5134
  } catch (err) {
5057
- logger.error(`active send failed: ${String(err)}`);
5135
+ logger.error(`active send failed: streamId=${streamId} error=${String(err)}`);
5058
5136
  }
5059
5137
  }
5060
5138
  }
@@ -5066,9 +5144,10 @@ async function handleBaiduAppWebhookRequest(req, res) {
5066
5144
  current.finished = true;
5067
5145
  current.updatedAt = Date.now();
5068
5146
  }
5069
- logger.error(`baidu-app agent failed: ${String(err)}`);
5147
+ logger.error(`agent dispatch failed: streamId=${streamId} error=${String(err)}`);
5070
5148
  });
5071
5149
  } else {
5150
+ logger.warn(`runtime not available: streamId=${streamId} \u2014 agent dispatch skipped, no reply will be generated`);
5072
5151
  const state = streams.get(streamId);
5073
5152
  if (state) {
5074
5153
  state.finished = true;
@@ -5076,6 +5155,7 @@ async function handleBaiduAppWebhookRequest(req, res) {
5076
5155
  }
5077
5156
  }
5078
5157
  const placeholderReply = buildStreamPlaceholderReply(streamId);
5158
+ logger.debug(`stream placeholder reply sent: streamId=${streamId}`);
5079
5159
  jsonOk(
5080
5160
  res,
5081
5161
  buildEncryptedJsonReply({