cli-wechat-bridge 1.2.0 → 1.2.2

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.
Files changed (50) hide show
  1. package/README.md +25 -10
  2. package/bin/wechat-check-update.mjs +0 -0
  3. package/bin/wechat-claude.mjs +0 -0
  4. package/bin/wechat-codex.mjs +0 -0
  5. package/bin/wechat-daemon.mjs +0 -0
  6. package/bin/wechat-opencode.mjs +0 -0
  7. package/bin/wechat-pi.mjs +0 -0
  8. package/bin/wechat-setup.mjs +0 -0
  9. package/bin/wecom-check-update.mjs +0 -0
  10. package/bin/wecom-claude.mjs +0 -0
  11. package/bin/wecom-codex.mjs +0 -0
  12. package/bin/wecom-daemon.mjs +0 -0
  13. package/bin/wecom-opencode.mjs +0 -0
  14. package/bin/wecom-pi.mjs +0 -0
  15. package/bin/wecom-setup.mjs +0 -0
  16. package/dist/bridge/adapter-control.js +19 -12
  17. package/dist/bridge/bridge-adapters.claude.js +219 -115
  18. package/dist/bridge/bridge-adapters.codex.js +295 -90
  19. package/dist/bridge/bridge-adapters.core.js +84 -7
  20. package/dist/bridge/bridge-adapters.opencode.js +344 -74
  21. package/dist/bridge/bridge-adapters.pi.js +23 -18
  22. package/dist/bridge/bridge-adapters.shared.js +9 -9
  23. package/dist/bridge/bridge-session-resume.js +13 -6
  24. package/dist/bridge/bridge-utils.js +94 -144
  25. package/dist/bridge/claude-hooks.js +60 -3
  26. package/dist/bridge/claude-native-controls.js +32 -13
  27. package/dist/bridge/codex-visible-thread-proxy.js +140 -0
  28. package/dist/bridge/language-control.js +33 -0
  29. package/dist/bridge/native-terminal-control.js +38 -10
  30. package/dist/bridge/opencode-v2-compat.js +458 -0
  31. package/dist/bridge/wechat-bridge.js +57 -42
  32. package/dist/channels/channel-driver-factory.js +44 -0
  33. package/dist/channels/local/local-channel-port.js +40 -0
  34. package/dist/channels/local/local-driver.js +217 -0
  35. package/dist/channels/wechat/wechat-driver.js +11 -2
  36. package/dist/channels/wecom/wecom-driver.js +8 -1
  37. package/dist/companion/local-companion.js +27 -7
  38. package/dist/companion/opencode-v2-tui-bridge-plugin.js +93 -0
  39. package/dist/companion/pi-tui-bridge-extension.js +10 -4
  40. package/dist/core/bridge-control.js +3 -0
  41. package/dist/core/bridge-defer.js +3 -2
  42. package/dist/core/bridge-event-forwarder.js +3 -0
  43. package/dist/core/channel-types.js +5 -1
  44. package/dist/daemon/wechat-daemon.js +202 -124
  45. package/dist/i18n/index.js +25 -11
  46. package/dist/i18n/messages-en.js +244 -1
  47. package/dist/i18n/messages-zh.js +244 -1
  48. package/dist/runtime/legacy-adapter-runtime.js +7 -4
  49. package/dist/wechat/channel-config.js +3 -2
  50. package/package.json +6 -2
@@ -22,6 +22,8 @@ import { canDrainDeferredCodexInboundQueue, formatDeferredCodexInboundQueueMessa
22
22
  import { TurnCoordinator } from "../core/turn-coordinator.js";
23
23
  import { resolveOutboundConversationTarget } from "../core/outbound-target.js";
24
24
  import { handleAdapterControl } from "./adapter-control.js";
25
+ import { handleLanguageControl } from "./language-control.js";
26
+ import { LANGUAGE_FILE } from "../wechat/channel-config.js";
25
27
  import { forwardBridgeEvent } from "../core/bridge-event-forwarder.js";
26
28
  import { isDirectModuleRun } from "../core/direct-run.js";
27
29
  import { WechatChannelPort } from "../channels/wechat/wechat-channel-port.js";
@@ -706,7 +708,7 @@ async function main() {
706
708
  task: nextActiveTask,
707
709
  conversation: channelMessage.conversation,
708
710
  onBusy: async () => {
709
- await queueInboundReply(message.senderId, `${options.adapter} is still working. Wait for the current reply or use /stop.`);
711
+ await queueInboundReply(message.senderId, t("bridge.busy.remote", { adapter: options.adapter }));
710
712
  },
711
713
  forward: async () => {
712
714
  await dispatchInboundWechatText({
@@ -752,7 +754,7 @@ async function main() {
752
754
  if (chatType === "direct") {
753
755
  const result = await channelDriver.sendText({
754
756
  target: channelDriver.directConversation(senderId),
755
- text: "Unauthorized.",
757
+ text: t("channel.unauthorized"),
756
758
  context: "notice",
757
759
  log: (entry) => stateStore.appendLog(entry),
758
760
  });
@@ -884,7 +886,7 @@ async function main() {
884
886
  const result = await turns.dispatch({
885
887
  task: nextActiveTask,
886
888
  onBusy: async () => {
887
- await queueWechatMessage(message.senderId, `${options.adapter} is still working. Wait for the current reply or use /stop.`);
889
+ await queueWechatMessage(message.senderId, t("bridge.busy.remote", { adapter: options.adapter }));
888
890
  },
889
891
  forward: async () => {
890
892
  await dispatchInboundWechatText({
@@ -954,7 +956,7 @@ function syncSharedSessionState(stateStore, adapter) {
954
956
  }
955
957
  }
956
958
  }
957
- function wireAdapterEvents(params) {
959
+ export function wireAdapterEvents(params) {
958
960
  const { adapter, channelDriver, resumeCoordinator, options, transport, stateStore, outputBatcher, queueWechatAttachmentAction, queueWechatMessage, trackWechatForwardTask, maybeDrainDeferredInboundMessages, getActiveTask, clearActiveTask, syncSharedSessionState, syncLocalClientEndpoint, requestShutdown, wecomTransport, getWecomTarget, } = params;
959
961
  const channelPort = options.channelId === "wecom"
960
962
  ? new WecomChannelPort({
@@ -984,10 +986,12 @@ function wireAdapterEvents(params) {
984
986
  syncLocalClientEndpoint();
985
987
  const adapterState = adapter.getState();
986
988
  const bridgeState = stateStore.getState();
987
- if (bridgeState.pendingConfirmation && !adapterState.pendingApproval) {
989
+ if (bridgeState.pendingConfirmation && (!adapterState.pendingApproval
990
+ || (adapterState.pendingApprovals !== undefined && bridgeState.pendingConfirmation.requestId !== adapterState.pendingApproval.requestId))) {
988
991
  stateStore.clearPendingConfirmation();
989
992
  }
990
- if (bridgeState.pendingUserInput && !adapterState.pendingUserInput) {
993
+ if (bridgeState.pendingUserInput && (!adapterState.pendingUserInput
994
+ || (bridgeState.pendingUserInput.requestId !== undefined && bridgeState.pendingUserInput.requestId !== adapterState.pendingUserInput.requestId))) {
991
995
  stateStore.clearPendingUserInput();
992
996
  }
993
997
  const authorizedUserId = stateStore.getState().authorizedUserId;
@@ -1050,14 +1054,21 @@ function wireAdapterEvents(params) {
1050
1054
  },
1051
1055
  approvalRequired: (next) => {
1052
1056
  trackWechatForwardTask(outputBatcher.flushNow().then(async () => {
1057
+ const liveState = adapter.getState();
1058
+ if (liveState.pendingApprovals !== undefined && liveState.pendingApproval?.requestId !== next.request.requestId)
1059
+ return;
1053
1060
  const pending = toPendingApproval(next.request);
1054
- stateStore.setPendingConfirmation(pending);
1055
1061
  stateStore.appendLog(`Approval requested (${pending.source}): ${pending.commandPreview}`);
1056
- await queueWechatMessage(authorizedUserId, formatApprovalMessage(pending, adapterState), "approval_required", eventTarget);
1062
+ await queueWechatMessage(authorizedUserId, formatApprovalMessage(pending, liveState), "approval_required", eventTarget);
1063
+ if (adapter.getState().pendingApproval?.requestId === pending.requestId) {
1064
+ stateStore.setPendingConfirmation(pending);
1065
+ }
1057
1066
  }));
1058
1067
  },
1059
1068
  userInputRequired: (next) => {
1060
1069
  trackWechatForwardTask(outputBatcher.flushNow().then(async () => {
1070
+ if (next.request.requestId !== undefined && adapter.getState().pendingUserInput?.requestId !== next.request.requestId)
1071
+ return;
1061
1072
  const pending = toPendingUserInput(next.request);
1062
1073
  stateStore.setPendingUserInput(pending);
1063
1074
  stateStore.appendLog(`User input requested: questions=${pending.questions.length}`);
@@ -1155,12 +1166,12 @@ function formatInboundMessagePreview(message) {
1155
1166
  }
1156
1167
  return "(empty)";
1157
1168
  }
1158
- async function handleInboundMessage(params) {
1169
+ export async function handleInboundMessage(params) {
1159
1170
  const { message, channelMessage, channelDriver, } = params;
1160
1171
  const { options, stateStore, adapter, resumeCoordinator, queueWechatMessage, outputBatcher, clearActiveTask, dispatchInboundText, deferInboundMessage, } = params;
1161
1172
  const state = stateStore.getState();
1162
1173
  if (message.senderId !== state.authorizedUserId) {
1163
- await queueWechatMessage(message.senderId, `Unauthorized. This bridge only accepts messages from ${channelDriver.operatorDescription}.`);
1174
+ await queueWechatMessage(message.senderId, t("bridge.unauthorized", { mode: t("bridge.mode.bridge"), operator: channelDriver.operatorDescription }));
1164
1175
  return null;
1165
1176
  }
1166
1177
  const systemCommand = parseWechatControlCommand(message.text, {
@@ -1169,19 +1180,24 @@ async function handleInboundMessage(params) {
1169
1180
  hasPendingUserInput: Boolean(state.pendingUserInput),
1170
1181
  });
1171
1182
  switch (systemCommand?.type) {
1183
+ case "language":
1184
+ await queueWechatMessage(message.senderId, await handleLanguageControl({
1185
+ target: systemCommand.target, settingsFile: params.localeSettingsFile ?? LANGUAGE_FILE, adapters: [adapter],
1186
+ }));
1187
+ return null;
1172
1188
  case "model":
1173
1189
  case "plan":
1174
1190
  await queueWechatMessage(message.senderId, await handleAdapterControl(adapter, message.senderId, systemCommand));
1175
1191
  return null;
1176
1192
  case "broadcast":
1177
- await queueWechatMessage(message.senderId, "/all is only available in daemon mode. Start the daemon with wechat-daemon or wecom-daemon to broadcast to all workers.");
1193
+ await queueWechatMessage(message.senderId, t("bridge.broadcast.daemonOnly"));
1178
1194
  return null;
1179
1195
  case "status":
1180
1196
  await queueWechatMessage(message.senderId, formatStatusReport(stateStore.getState(), adapter.getState()));
1181
1197
  return null;
1182
1198
  case "resume": {
1183
1199
  if (!isWechatResumeEnabled(options.adapter)) {
1184
- await queueWechatMessage(message.senderId, `${channelDriver.displayName} /resume is disabled in ${options.adapter} mode. Use /resume directly inside "${channelDriver.id}-${options.adapter}"; the remote channel will follow the active local session.`);
1200
+ await queueWechatMessage(message.senderId, t("bridge.resume.disabled", { channel: channelDriver.displayName, adapter: options.adapter, command: `${channelDriver.id}-${options.adapter}` }));
1185
1201
  return null;
1186
1202
  }
1187
1203
  try {
@@ -1201,7 +1217,7 @@ async function handleInboundMessage(params) {
1201
1217
  }
1202
1218
  case "new_session": {
1203
1219
  if (!adapter.createSession) {
1204
- await queueWechatMessage(message.senderId, `/new is not available in ${options.adapter} mode.`);
1220
+ await queueWechatMessage(message.senderId, t("bridge.newSession.unavailable", { adapter: options.adapter }));
1205
1221
  return null;
1206
1222
  }
1207
1223
  await outputBatcher.flushNow();
@@ -1217,8 +1233,8 @@ async function handleInboundMessage(params) {
1217
1233
  case "stop": {
1218
1234
  const interrupted = await adapter.interrupt();
1219
1235
  await queueWechatMessage(message.senderId, interrupted
1220
- ? "Interrupt signal sent to the active worker."
1221
- : "No running worker was available to interrupt.");
1236
+ ? t("bridge.interrupt.workerSent")
1237
+ : t("bridge.interrupt.workerIdle"));
1222
1238
  return null;
1223
1239
  }
1224
1240
  case "reset":
@@ -1230,47 +1246,48 @@ async function handleInboundMessage(params) {
1230
1246
  resumeCoordinator.clear();
1231
1247
  await adapter.reset();
1232
1248
  stateStore.appendLog("Worker reset by owner.");
1233
- await queueWechatMessage(message.senderId, "Worker session has been reset.");
1249
+ await queueWechatMessage(message.senderId, t("bridge.reset.done"));
1234
1250
  return null;
1235
1251
  case "confirm": {
1236
1252
  const pending = state.pendingConfirmation;
1237
1253
  if (!pending) {
1238
- await queueWechatMessage(message.senderId, "No pending approval request.");
1254
+ await queueWechatMessage(message.senderId, t("approval.noPending"));
1239
1255
  return null;
1240
1256
  }
1241
- const confirmed = await adapter.resolveApproval("confirm");
1257
+ const confirmed = await adapter.resolveApproval("confirm", pending.requestId);
1242
1258
  if (!confirmed) {
1243
- await queueWechatMessage(message.senderId, "The worker could not apply this approval request.");
1259
+ await queueWechatMessage(message.senderId, t("bridge.approval.applyFailed"));
1244
1260
  return null;
1245
1261
  }
1246
- stateStore.clearPendingConfirmation();
1262
+ if (stateStore.getState().pendingConfirmation?.requestId === pending.requestId) {
1263
+ stateStore.clearPendingConfirmation();
1264
+ }
1247
1265
  stateStore.appendLog(`Approval confirmed: ${pending.commandPreview}`);
1248
- await queueWechatMessage(message.senderId, "Approval confirmed. Continuing...");
1249
- return {
1250
- startedAt: Date.now(),
1251
- inputPreview: pending.commandPreview,
1252
- };
1266
+ await queueWechatMessage(message.senderId, t("approval.confirmed"));
1267
+ return null;
1253
1268
  }
1254
1269
  case "deny": {
1255
1270
  const pending = state.pendingConfirmation;
1256
1271
  if (!pending) {
1257
- await queueWechatMessage(message.senderId, "No pending approval request.");
1272
+ await queueWechatMessage(message.senderId, t("approval.noPending"));
1258
1273
  return null;
1259
1274
  }
1260
- const denied = await adapter.resolveApproval("deny");
1275
+ const denied = await adapter.resolveApproval("deny", pending.requestId);
1261
1276
  if (!denied) {
1262
- await queueWechatMessage(message.senderId, "The worker could not deny this approval request cleanly.");
1277
+ await queueWechatMessage(message.senderId, t("bridge.approval.denyFailed"));
1263
1278
  return null;
1264
1279
  }
1265
- stateStore.clearPendingConfirmation();
1280
+ if (stateStore.getState().pendingConfirmation?.requestId === pending.requestId) {
1281
+ stateStore.clearPendingConfirmation();
1282
+ }
1266
1283
  stateStore.appendLog(`Approval denied: ${pending.commandPreview}`);
1267
- await queueWechatMessage(message.senderId, "Approval denied.");
1284
+ await queueWechatMessage(message.senderId, t("approval.denied"));
1268
1285
  return null;
1269
1286
  }
1270
1287
  case "answer": {
1271
1288
  const pending = state.pendingUserInput;
1272
1289
  if (!pending) {
1273
- await queueWechatMessage(message.senderId, "No pending user input request.");
1290
+ await queueWechatMessage(message.senderId, t("bridge.answer.none"));
1274
1291
  return null;
1275
1292
  }
1276
1293
  const parsed = parsePendingUserInputAnswerCommand(systemCommand.raw, pending);
@@ -1278,18 +1295,16 @@ async function handleInboundMessage(params) {
1278
1295
  await queueWechatMessage(message.senderId, parsed.error);
1279
1296
  return null;
1280
1297
  }
1281
- const submitted = await adapter.submitUserInput(parsed.answers);
1298
+ const submitted = await adapter.submitUserInput(parsed.answers, pending.requestId);
1282
1299
  if (!submitted) {
1283
- await queueWechatMessage(message.senderId, "The worker could not apply this answer.");
1300
+ await queueWechatMessage(message.senderId, t("bridge.answer.failed"));
1284
1301
  return null;
1285
1302
  }
1286
- stateStore.clearPendingUserInput();
1303
+ if (stateStore.getState().pendingUserInput?.requestId === pending.requestId)
1304
+ stateStore.clearPendingUserInput();
1287
1305
  stateStore.appendLog(`User input answered: ${parsed.preview}`);
1288
- await queueWechatMessage(message.senderId, "Answer submitted. Continuing...");
1289
- return {
1290
- startedAt: Date.now(),
1291
- inputPreview: parsed.preview,
1292
- };
1306
+ await queueWechatMessage(message.senderId, t("bridge.answer.sent"));
1307
+ return null;
1293
1308
  }
1294
1309
  }
1295
1310
  const adapterState = adapter.getState();
@@ -1316,16 +1331,16 @@ async function handleInboundMessage(params) {
1316
1331
  const pendingUserInput = stateStore.getState().pendingUserInput;
1317
1332
  await queueWechatMessage(message.senderId, pendingUserInput
1318
1333
  ? formatPendingUserInputReminder(pendingUserInput)
1319
- : `${options.adapter} is waiting for structured input. Reply with /answer <key>=<value> ...`);
1334
+ : t("bridge.input.waiting", { adapter: options.adapter }));
1320
1335
  },
1321
1336
  remindBusy: async () => {
1322
1337
  const currentState = adapter.getState();
1323
1338
  if ((options.adapter === "codex" || options.adapter === "opencode" || options.adapter === "pi") &&
1324
1339
  currentState.activeTurnOrigin === "local") {
1325
- await queueWechatMessage(message.senderId, `${options.adapter === "opencode" ? "OpenCode" : options.adapter === "pi" ? "Pi" : "codex"} is currently busy with a local terminal turn. Wait for it to finish or use /stop.`);
1340
+ await queueWechatMessage(message.senderId, t("bridge.busy.local", { adapter: options.adapter === "opencode" ? "OpenCode" : options.adapter === "pi" ? "Pi" : "codex" }));
1326
1341
  return;
1327
1342
  }
1328
- await queueWechatMessage(message.senderId, `${options.adapter} is still working. Wait for the current reply or use /stop.`);
1343
+ await queueWechatMessage(message.senderId, t("bridge.busy.remote", { adapter: options.adapter }));
1329
1344
  },
1330
1345
  defer: async () => {
1331
1346
  await deferInboundMessage(message);
@@ -0,0 +1,44 @@
1
+ import { WecomChannelDriver } from "./wecom/wecom-driver.js";
2
+ import { WechatChannelDriver } from "./wechat/wechat-driver.js";
3
+ import { LocalChannelDriver } from "./local/local-driver.js";
4
+ /**
5
+ * Single construction point for channel drivers. Adding a channel means
6
+ * adding a driver implementation and one branch here; orchestration layers
7
+ * stay channel-neutral.
8
+ */
9
+ export function createChannelDriver(input) {
10
+ if (input.channelId === "wecom") {
11
+ if (!input.wecomTransport) {
12
+ throw new Error("The wecom channel requires a WeCom transport.");
13
+ }
14
+ return new WecomChannelDriver({
15
+ transport: input.wecomTransport,
16
+ accountId: input.accountId,
17
+ operatorId: input.authorizedUserId,
18
+ logError: input.logError,
19
+ });
20
+ }
21
+ if (input.channelId === "local") {
22
+ const files = input.localFiles ?? {
23
+ inboxFile: "",
24
+ transcriptFile: "",
25
+ };
26
+ if (!files.inboxFile || !files.transcriptFile) {
27
+ throw new Error("The local channel requires inbox and transcript file paths.");
28
+ }
29
+ return new LocalChannelDriver({
30
+ operatorId: input.authorizedUserId,
31
+ inboxFile: files.inboxFile,
32
+ transcriptFile: files.transcriptFile,
33
+ log: input.log,
34
+ });
35
+ }
36
+ if (!input.wechatTransport) {
37
+ throw new Error("The wechat channel requires a WeChat transport.");
38
+ }
39
+ return new WechatChannelDriver({
40
+ transport: input.wechatTransport,
41
+ logError: input.logError,
42
+ buildInboundPrompt: input.buildWechatInboundPrompt,
43
+ });
44
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Channel boundary for local loopback output. Unlike WeChat there is no
3
+ * plain-text conversion: the harness consumes the raw final reply.
4
+ */
5
+ export class LocalChannelPort {
6
+ channelId = "local";
7
+ deps;
8
+ constructor(deps) {
9
+ this.deps = deps;
10
+ }
11
+ async send(output) {
12
+ if (output.target.channelId !== "local") {
13
+ throw new Error(`Local channel cannot send to ${output.target.channelId}.`);
14
+ }
15
+ const recipientId = output.target.recipientId;
16
+ const prefixText = (text) => this.deps.prefixText?.(output.adapter, text) ?? text;
17
+ const context = typeof output.metadata?.sendContext === "string"
18
+ ? output.metadata.sendContext
19
+ : output.kind;
20
+ if (output.kind === "final_reply") {
21
+ const rawText = output.text ?? "";
22
+ if (!rawText.trim()) {
23
+ this.deps.onEmptyVisibleReply?.(output.adapter, rawText);
24
+ return true;
25
+ }
26
+ const sent = await this.deps.sendText(recipientId, prefixText(rawText), "final_reply");
27
+ if (sent) {
28
+ this.deps.onTextSent?.(output.adapter, rawText);
29
+ }
30
+ return true;
31
+ }
32
+ if (output.attachment) {
33
+ await this.deps.sendAttachment?.(recipientId, output.attachment);
34
+ }
35
+ if (output.text?.trim()) {
36
+ return Boolean(await this.deps.sendText(recipientId, prefixText(output.text), context));
37
+ }
38
+ return true;
39
+ }
40
+ }
@@ -0,0 +1,217 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 UNLINEARITY <unlinearity@gmail.com>
3
+ // Source: https://github.com/UNLINEARITY/CLI-WeChat-Bridge
4
+ // This file is part of CLI-WeChat-Bridge. Modifications and derivative works
5
+ // must be released under AGPL-3.0-or-later with full source code; see
6
+ // LICENSE.txt. Network services built on it must offer source to users.
7
+ import { t } from "../../i18n/index.js";
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import { getWorkspaceChannelPaths } from "../../wechat/channel-config.js";
11
+ /**
12
+ * Loopback channel for local end-to-end runs. Inbound messages are JSONL
13
+ * lines appended to the inbox file; every outbound text is appended to the
14
+ * transcript file so an external harness can drive and observe the full
15
+ * bridge pipeline without a remote messaging platform.
16
+ */
17
+ export const LOCAL_CHANNEL_OPERATOR_ID = "local-operator";
18
+ export function getLocalChannelFiles(cwd) {
19
+ const workspaceDir = getWorkspaceChannelPaths(cwd).workspaceDir;
20
+ return {
21
+ inboxFile: path.join(workspaceDir, "local-inbox.jsonl"),
22
+ transcriptFile: path.join(workspaceDir, "local-transcript.jsonl"),
23
+ };
24
+ }
25
+ export class LocalChannelDriver {
26
+ id = "local";
27
+ displayName = "Local";
28
+ get operatorDescription() { return t("operator.local"); }
29
+ capabilities = {
30
+ streamingReplies: false,
31
+ outboundAttachments: false,
32
+ multiConversation: false,
33
+ pushInbound: true,
34
+ };
35
+ operatorId;
36
+ inboxFile;
37
+ transcriptFile;
38
+ pollIntervalMs;
39
+ log;
40
+ handlers = null;
41
+ timer = null;
42
+ inboxOffset = 0;
43
+ pendingLine = "";
44
+ messageSeq = 0;
45
+ constructor(options) {
46
+ this.operatorId = options.operatorId;
47
+ this.inboxFile = options.inboxFile;
48
+ this.transcriptFile = options.transcriptFile;
49
+ this.pollIntervalMs = options.pollIntervalMs ?? 200;
50
+ this.log = options.log ?? (() => { });
51
+ }
52
+ defaultConversation() {
53
+ return this.directConversation(this.operatorId);
54
+ }
55
+ directConversation(senderId) {
56
+ return {
57
+ channelId: "local",
58
+ conversationId: senderId,
59
+ recipientId: senderId,
60
+ metadata: { chatType: "direct" },
61
+ };
62
+ }
63
+ start(handlers) {
64
+ this.handlers = handlers;
65
+ fs.mkdirSync(path.dirname(this.inboxFile), { recursive: true });
66
+ // Start at end-of-file so lines left over from earlier runs are ignored.
67
+ this.inboxOffset = this.measureInboxSize();
68
+ this.pendingLine = "";
69
+ this.timer = setInterval(() => {
70
+ void this.pumpInbox();
71
+ }, this.pollIntervalMs);
72
+ this.timer.unref?.();
73
+ this.log("local_channel_started");
74
+ }
75
+ /** Clears the inbox watcher. Not part of ChannelDriver; callers may stop explicitly. */
76
+ stop() {
77
+ if (this.timer) {
78
+ clearInterval(this.timer);
79
+ }
80
+ this.timer = null;
81
+ this.handlers = null;
82
+ }
83
+ waitUntilReady() {
84
+ return Promise.resolve();
85
+ }
86
+ async sendText(params) {
87
+ const { target, text, context, log } = params;
88
+ this.appendTranscript({
89
+ ts: new Date().toISOString(),
90
+ direction: "outbound",
91
+ context,
92
+ conversationId: target.conversationId,
93
+ recipientId: target.recipientId,
94
+ text,
95
+ });
96
+ log(`local_send_completed: context=${context} recipient=${target.recipientId} chars=${Array.from(text).length}`);
97
+ return { status: "sent" };
98
+ }
99
+ buildInboundPrompt(text, attachments) {
100
+ if (attachments.length === 0) {
101
+ return text;
102
+ }
103
+ const lines = attachments.map((attachment) => {
104
+ const label = attachment.fileName ? ` (${attachment.fileName})` : "";
105
+ return `- ${attachment.path}${label}`;
106
+ });
107
+ return `${text}\n\nLocal attachments:\n${lines.join("\n")}`;
108
+ }
109
+ measureInboxSize() {
110
+ try {
111
+ return fs.statSync(this.inboxFile).size;
112
+ }
113
+ catch {
114
+ return 0;
115
+ }
116
+ }
117
+ async pumpInbox() {
118
+ const handlers = this.handlers;
119
+ if (!handlers) {
120
+ return;
121
+ }
122
+ let size;
123
+ try {
124
+ size = fs.statSync(this.inboxFile).size;
125
+ }
126
+ catch {
127
+ return;
128
+ }
129
+ if (size < this.inboxOffset) {
130
+ // The inbox was truncated; restart from the beginning.
131
+ this.inboxOffset = 0;
132
+ this.pendingLine = "";
133
+ }
134
+ if (size === this.inboxOffset) {
135
+ return;
136
+ }
137
+ let chunk;
138
+ try {
139
+ const fd = fs.openSync(this.inboxFile, "r");
140
+ try {
141
+ const buffer = Buffer.alloc(size - this.inboxOffset);
142
+ fs.readSync(fd, buffer, 0, buffer.length, this.inboxOffset);
143
+ chunk = buffer.toString("utf8");
144
+ }
145
+ finally {
146
+ fs.closeSync(fd);
147
+ }
148
+ }
149
+ catch {
150
+ return;
151
+ }
152
+ this.inboxOffset = size;
153
+ const complete = chunk.endsWith("\n");
154
+ const combined = this.pendingLine + chunk;
155
+ const parts = combined.split("\n");
156
+ this.pendingLine = complete ? "" : (parts.pop() ?? "");
157
+ for (const line of parts) {
158
+ const trimmed = line.trim();
159
+ if (!trimmed) {
160
+ continue;
161
+ }
162
+ try {
163
+ await this.dispatchInboxLine(trimmed, handlers);
164
+ }
165
+ catch (error) {
166
+ this.log(`local_inbound_failed: error=${error instanceof Error ? error.message : String(error)}`);
167
+ }
168
+ }
169
+ }
170
+ async dispatchInboxLine(line, handlers) {
171
+ let parsed;
172
+ try {
173
+ parsed = JSON.parse(line);
174
+ }
175
+ catch {
176
+ this.log("local_inbox_invalid_json: skipped one line");
177
+ return;
178
+ }
179
+ if (typeof parsed?.text !== "string" || !parsed.text.trim()) {
180
+ this.log("local_inbox_invalid_line: skipped one line without text");
181
+ return;
182
+ }
183
+ const senderId = typeof parsed.senderId === "string" && parsed.senderId
184
+ ? parsed.senderId
185
+ : this.operatorId;
186
+ const conversationId = typeof parsed.conversationId === "string" && parsed.conversationId
187
+ ? parsed.conversationId
188
+ : senderId;
189
+ const attachments = Array.isArray(parsed.attachments)
190
+ ? parsed.attachments.filter((attachment) => Boolean(attachment) &&
191
+ typeof attachment.path === "string" &&
192
+ typeof attachment.kind === "string")
193
+ : [];
194
+ this.messageSeq += 1;
195
+ const message = {
196
+ id: `local-${Date.now().toString(36)}-${this.messageSeq}`,
197
+ conversation: { ...this.directConversation(senderId), conversationId },
198
+ senderId,
199
+ text: parsed.text,
200
+ attachments,
201
+ createdAt: new Date().toISOString(),
202
+ };
203
+ this.appendTranscript({
204
+ ts: message.createdAt,
205
+ direction: "inbound",
206
+ context: "inbound",
207
+ conversationId,
208
+ recipientId: senderId,
209
+ text: parsed.text,
210
+ });
211
+ await handlers.onInboundMessage(message);
212
+ }
213
+ appendTranscript(record) {
214
+ fs.mkdirSync(path.dirname(this.transcriptFile), { recursive: true });
215
+ fs.appendFileSync(this.transcriptFile, `${JSON.stringify(record)}\n`, "utf8");
216
+ }
217
+ }
@@ -1,16 +1,25 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 UNLINEARITY <unlinearity@gmail.com>
3
+ // Source: https://github.com/UNLINEARITY/CLI-WeChat-Bridge
4
+ // This file is part of CLI-WeChat-Bridge. Modifications and derivative works
5
+ // must be released under AGPL-3.0-or-later with full source code; see
6
+ // LICENSE.txt. Network services built on it must offer source to users.
7
+ import { t } from "../../i18n/index.js";
1
8
  import { WECHAT_SEND_MAX_ATTEMPTS, computeWechatSendRetryDelayMs, formatWechatContextTokenStaleLogEntry, formatWechatSendFailureLogEntry, formatWechatSendRetryLogEntry, isRetryableWechatSendError, isWechatContextUnavailableError, } from "../../channels/wechat/wechat-forwarding.js";
2
9
  import { describeWechatTransportError, isWechatContextTokenStaleError, } from "../../wechat/wechat-transport.js";
3
10
  import { formatDuration } from "../../core/text-utils.js";
4
11
  const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
5
12
  /** Per-recipient typing tickets with a random-refresh TTL and retry backoff. */
6
13
  class TypingTicketCache {
14
+ cache = new Map();
7
15
  fetchTicket;
8
16
  log;
9
17
  ttlMs;
10
18
  initialRetryMs;
11
19
  maxRetryMs;
12
- cache = new Map();
13
20
  constructor(fetchTicket, log, ttlMs = 24 * 60 * 60 * 1000, initialRetryMs = 2_000, maxRetryMs = 60 * 60 * 1000) {
21
+ // Plain assignments instead of parameter properties so Node's
22
+ // strip-types source mode can load this module.
14
23
  this.fetchTicket = fetchTicket;
15
24
  this.log = log;
16
25
  this.ttlMs = ttlMs;
@@ -59,7 +68,7 @@ const WECHAT_CONTEXT_STALE_HINT = "WeChat conversation context is stale or unava
59
68
  export class WechatChannelDriver {
60
69
  id = "wechat";
61
70
  displayName = "WeChat";
62
- operatorDescription = "the configured WeChat owner";
71
+ get operatorDescription() { return t("operator.wechat"); }
63
72
  capabilities = {
64
73
  streamingReplies: false,
65
74
  outboundAttachments: false,
@@ -1,3 +1,10 @@
1
+ // SPDX-License-Identifier: AGPL-3.0-or-later
2
+ // Copyright (c) 2026 UNLINEARITY <unlinearity@gmail.com>
3
+ // Source: https://github.com/UNLINEARITY/CLI-WeChat-Bridge
4
+ // This file is part of CLI-WeChat-Bridge. Modifications and derivative works
5
+ // must be released under AGPL-3.0-or-later with full source code; see
6
+ // LICENSE.txt. Network services built on it must offer source to users.
7
+ import { t } from "../../i18n/index.js";
1
8
  import { buildWecomInboundPrompt, formatWecomVisibleText, } from "./wecom-message.js";
2
9
  import { truncatePreview } from "../../core/text-utils.js";
3
10
  export function toWecomOutputKind(context) {
@@ -22,7 +29,7 @@ export function toWecomOutputKind(context) {
22
29
  export class WecomChannelDriver {
23
30
  id = "wecom";
24
31
  displayName = "WeCom";
25
- operatorDescription = "the paired WeCom operator";
32
+ get operatorDescription() { return t("operator.wecom"); }
26
33
  capabilities = {
27
34
  streamingReplies: true,
28
35
  outboundAttachments: true,