shennian 0.3.1 → 0.3.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.
- package/README.md +3 -1
- package/dist/publish-build-manifest.json +273 -343
- package/dist/src/agents/command-spec.js +2 -2
- package/dist/src/agents/detect.js +1 -1
- package/dist/src/agents/model-registry/discovery.js +2 -2
- package/dist/src/agents/model-registry/parsers.d.ts +1 -0
- package/dist/src/agents/model-registry/parsers.js +4 -4
- package/dist/src/agents/native-capabilities.d.ts +10 -0
- package/dist/src/agents/native-capabilities.js +1 -0
- package/dist/src/agents/platform-instructions.js +5 -5
- package/dist/src/agents/workbuddy.d.ts +44 -0
- package/dist/src/agents/workbuddy.js +3 -0
- package/dist/src/commands/daemon.d.ts +1 -0
- package/dist/src/commands/daemon.js +9 -9
- package/dist/src/commands/integration.d.ts +2 -0
- package/dist/src/commands/integration.js +1 -0
- package/dist/src/commands/manager.js +1 -2
- package/dist/src/commands/pair-browser.d.ts +43 -0
- package/dist/src/commands/pair-browser.js +1 -0
- package/dist/src/commands/pair.d.ts +2 -0
- package/dist/src/commands/pair.js +11 -8
- package/dist/src/commands/room.d.ts +13 -0
- package/dist/src/commands/room.js +4 -0
- package/dist/src/commands/upgrade.d.ts +3 -0
- package/dist/src/commands/upgrade.js +1 -1
- package/dist/src/config/index.d.ts +3 -1
- package/dist/src/config/index.js +2 -1
- package/dist/src/daemon-ipc/client.d.ts +8 -0
- package/dist/src/daemon-ipc/client.js +3 -0
- package/dist/src/daemon-ipc/paths.d.ts +7 -0
- package/dist/src/daemon-ipc/paths.js +1 -0
- package/dist/src/daemon-ipc/protocol.d.ts +30 -0
- package/dist/src/daemon-ipc/protocol.js +1 -0
- package/dist/src/daemon-ipc/secret.d.ts +3 -0
- package/dist/src/daemon-ipc/secret.js +3 -0
- package/dist/src/daemon-ipc/server.d.ts +13 -0
- package/dist/src/daemon-ipc/server.js +3 -0
- package/dist/src/index.js +2 -2
- package/dist/src/integrations/claude-room-plugin-lifecycle.d.ts +47 -0
- package/dist/src/integrations/claude-room-plugin-lifecycle.js +1 -0
- package/dist/src/integrations/codex-room-plugin-lifecycle.d.ts +49 -0
- package/dist/src/integrations/codex-room-plugin-lifecycle.js +1 -0
- package/dist/src/integrations/room-plugin-bundles.d.ts +23 -0
- package/dist/src/integrations/room-plugin-bundles.js +1 -0
- package/dist/src/integrations/room-plugin-lifecycle-common.d.ts +17 -0
- package/dist/src/integrations/room-plugin-lifecycle-common.js +1 -0
- package/dist/src/integrations/room-plugin-shared.d.ts +23 -0
- package/dist/src/integrations/room-plugin-shared.js +2 -0
- package/dist/src/integrations/room-session-hook.d.ts +30 -0
- package/dist/src/integrations/room-session-hook.js +2 -0
- package/dist/src/integrations/workbuddy-plugin-bundle.d.ts +15 -0
- package/dist/src/integrations/workbuddy-plugin-bundle.js +1 -0
- package/dist/src/integrations/workbuddy-plugin-lifecycle.d.ts +52 -0
- package/dist/src/integrations/workbuddy-plugin-lifecycle.js +2 -0
- package/dist/src/integrations/workbuddy-session-hook.d.ts +22 -0
- package/dist/src/integrations/workbuddy-session-hook.js +1 -0
- package/dist/src/manager/prompt.d.ts +1 -1
- package/dist/src/manager/prompt.js +1 -1
- package/dist/src/manager/retired-external-channel-compat.d.ts +78 -0
- package/dist/src/manager/retired-external-channel-compat.js +1 -0
- package/dist/src/manager/runtime.d.ts +1 -3
- package/dist/src/manager/runtime.js +7 -7
- package/dist/src/relay/client.d.ts +2 -0
- package/dist/src/relay/client.js +1 -1
- package/dist/src/room/activation-audit.d.ts +15 -0
- package/dist/src/room/activation-audit.js +2 -0
- package/dist/src/room/activation-policy.d.ts +8 -0
- package/dist/src/room/activation-policy.js +1 -0
- package/dist/src/room/activation-service.d.ts +25 -0
- package/dist/src/room/activation-service.js +2 -0
- package/dist/src/room/attachment-cache.d.ts +40 -0
- package/dist/src/room/attachment-cache.js +2 -0
- package/dist/src/room/attachment-upload.d.ts +20 -0
- package/dist/src/room/attachment-upload.js +1 -0
- package/dist/src/room/authorized-action-coordinator.d.ts +40 -0
- package/dist/src/room/authorized-action-coordinator.js +1 -0
- package/dist/src/room/authorized-action-ipc.d.ts +11 -0
- package/dist/src/room/authorized-action-ipc.js +1 -0
- package/dist/src/room/device-authorization-client.d.ts +49 -0
- package/dist/src/room/device-authorization-client.js +1 -0
- package/dist/src/room/host-session-observation-ipc.d.ts +9 -0
- package/dist/src/room/host-session-observation-ipc.js +1 -0
- package/dist/src/room/host-session-observations.d.ts +54 -0
- package/dist/src/room/host-session-observations.js +2 -0
- package/dist/src/room/invite-bootstrap.d.ts +35 -0
- package/dist/src/room/invite-bootstrap.js +1 -0
- package/dist/src/room/invocation-token-ipc.d.ts +9 -0
- package/dist/src/room/invocation-token-ipc.js +1 -0
- package/dist/src/room/invocation-token.d.ts +53 -0
- package/dist/src/room/invocation-token.js +1 -0
- package/dist/src/room/jsonl-mirror.d.ts +73 -0
- package/dist/src/room/jsonl-mirror.js +6 -0
- package/dist/src/room/managed-room-session.d.ts +143 -0
- package/dist/src/room/managed-room-session.js +3 -0
- package/dist/src/room/mirror-sync-service.d.ts +33 -0
- package/dist/src/room/mirror-sync-service.js +1 -0
- package/dist/src/room/operator-ipc.d.ts +11 -0
- package/dist/src/room/operator-ipc.js +1 -0
- package/dist/src/room/pending-authorized-actions.d.ts +69 -0
- package/dist/src/room/pending-authorized-actions.js +3 -0
- package/dist/src/room/room-action-client.d.ts +208 -0
- package/dist/src/room/room-action-client.js +1 -0
- package/dist/src/room/room-action-ipc.d.ts +33 -0
- package/dist/src/room/room-action-ipc.js +1 -0
- package/dist/src/room/room-action-schema.d.ts +3 -0
- package/dist/src/room/room-action-schema.js +1 -0
- package/dist/src/room/room-authorized-action-executor.d.ts +23 -0
- package/dist/src/room/room-authorized-action-executor.js +1 -0
- package/dist/src/room/room-binding-client.d.ts +51 -0
- package/dist/src/room/room-binding-client.js +1 -0
- package/dist/src/room/room-binding-ipc.d.ts +29 -0
- package/dist/src/room/room-binding-ipc.js +1 -0
- package/dist/src/room/session-registry-ipc.d.ts +14 -0
- package/dist/src/room/session-registry-ipc.js +1 -0
- package/dist/src/room/session-registry.d.ts +128 -0
- package/dist/src/room/session-registry.js +2 -0
- package/dist/src/room/tool-schema.d.ts +114 -0
- package/dist/src/room/tool-schema.js +1 -0
- package/dist/src/room/tool-server.d.ts +5 -0
- package/dist/src/room/tool-server.js +3 -0
- package/dist/src/session/handlers/agent-capabilities.d.ts +3 -0
- package/dist/src/session/handlers/agent-capabilities.js +1 -0
- package/dist/src/session/handlers/agent-config.js +1 -1
- package/dist/src/session/handlers/chat.js +2 -2
- package/dist/src/session/handlers/control.js +1 -1
- package/dist/src/session/handlers/fs.d.ts +1 -0
- package/dist/src/session/handlers/fs.js +1 -1
- package/dist/src/session/manager.d.ts +16 -6
- package/dist/src/session/manager.js +1 -1
- package/dist/src/session/types.d.ts +5 -0
- package/dist/src/upgrade/engine.d.ts +14 -1
- package/dist/src/upgrade/engine.js +2 -2
- package/dist/src/upgrade/scheduler.d.ts +45 -0
- package/dist/src/upgrade/scheduler.js +1 -0
- package/node_modules/@shennian/wire/dist/agent-capabilities.d.ts +17 -0
- package/node_modules/@shennian/wire/dist/agent-capabilities.d.ts.map +1 -0
- package/node_modules/@shennian/wire/dist/agent-capabilities.js +2 -0
- package/node_modules/@shennian/wire/dist/agent-capabilities.js.map +1 -0
- package/node_modules/@shennian/wire/dist/index.d.ts +2 -1
- package/node_modules/@shennian/wire/dist/index.d.ts.map +1 -1
- package/node_modules/@shennian/wire/dist/index.js +2 -1
- package/node_modules/@shennian/wire/dist/index.js.map +1 -1
- package/node_modules/@shennian/wire/dist/machine.d.ts +1 -0
- package/node_modules/@shennian/wire/dist/machine.d.ts.map +1 -1
- package/node_modules/@shennian/wire/dist/methods.d.ts +1 -1
- package/node_modules/@shennian/wire/dist/methods.d.ts.map +1 -1
- package/node_modules/@shennian/wire/dist/room.d.ts +112 -0
- package/node_modules/@shennian/wire/dist/room.d.ts.map +1 -0
- package/node_modules/@shennian/wire/dist/room.js +4 -0
- package/node_modules/@shennian/wire/dist/room.js.map +1 -0
- package/node_modules/@shennian/wire/dist/session.d.ts +2 -2
- package/node_modules/@shennian/wire/dist/session.d.ts.map +1 -1
- package/node_modules/@shennian/wire/dist/session.js +1 -1
- package/node_modules/@shennian/wire/dist/session.js.map +1 -1
- package/package.json +3 -5
- package/dist/scripts/wechat-rpa-confirmation.mjs +0 -5
- package/dist/src/agents/pi-context.d.ts +0 -42
- package/dist/src/agents/pi-context.js +0 -12
- package/dist/src/agents/pi.d.ts +0 -70
- package/dist/src/agents/pi.js +0 -17
- package/dist/src/channels/base.d.ts +0 -144
- package/dist/src/channels/base.js +0 -1
- package/dist/src/channels/registry.d.ts +0 -8
- package/dist/src/channels/registry.js +0 -1
- package/dist/src/channels/reply-split.d.ts +0 -1
- package/dist/src/channels/reply-split.js +0 -10
- package/dist/src/channels/runtime.d.ts +0 -138
- package/dist/src/channels/runtime.js +0 -5
- package/dist/src/channels/secret-registry.d.ts +0 -35
- package/dist/src/channels/secret-registry.js +0 -1
- package/dist/src/channels/websocket.d.ts +0 -55
- package/dist/src/channels/websocket.js +0 -8
- package/dist/src/channels/wechat-channel/anchor.d.ts +0 -10
- package/dist/src/channels/wechat-channel/anchor.js +0 -1
- package/dist/src/channels/wechat-channel/automation-lane.d.ts +0 -35
- package/dist/src/channels/wechat-channel/automation-lane.js +0 -2
- package/dist/src/channels/wechat-channel/client.d.ts +0 -283
- package/dist/src/channels/wechat-channel/client.js +0 -1
- package/dist/src/channels/wechat-channel/cooldown.d.ts +0 -21
- package/dist/src/channels/wechat-channel/cooldown.js +0 -1
- package/dist/src/channels/wechat-channel/core/fixture-compare.d.ts +0 -52
- package/dist/src/channels/wechat-channel/core/fixture-compare.js +0 -1
- package/dist/src/channels/wechat-channel/core/media-action-plan.d.ts +0 -3
- package/dist/src/channels/wechat-channel/core/media-action-plan.js +0 -1
- package/dist/src/channels/wechat-channel/core/schema.d.ts +0 -67
- package/dist/src/channels/wechat-channel/core/schema.js +0 -1
- package/dist/src/channels/wechat-channel/core/trace-comparator.d.ts +0 -28
- package/dist/src/channels/wechat-channel/core/trace-comparator.js +0 -1
- package/dist/src/channels/wechat-channel/fingerprint.d.ts +0 -31
- package/dist/src/channels/wechat-channel/fingerprint.js +0 -1
- package/dist/src/channels/wechat-channel/helper-assets.d.ts +0 -103
- package/dist/src/channels/wechat-channel/helper-assets.js +0 -1
- package/dist/src/channels/wechat-channel/helper-client.d.ts +0 -87
- package/dist/src/channels/wechat-channel/helper-client.js +0 -3
- package/dist/src/channels/wechat-channel/helper-protocol.d.ts +0 -122
- package/dist/src/channels/wechat-channel/helper-protocol.js +0 -1
- package/dist/src/channels/wechat-channel/human-coordination.d.ts +0 -25
- package/dist/src/channels/wechat-channel/human-coordination.js +0 -1
- package/dist/src/channels/wechat-channel/index.d.ts +0 -21
- package/dist/src/channels/wechat-channel/index.js +0 -1
- package/dist/src/channels/wechat-channel/ledger.d.ts +0 -48
- package/dist/src/channels/wechat-channel/ledger.js +0 -2
- package/dist/src/channels/wechat-channel/media-cache-resolver.d.ts +0 -42
- package/dist/src/channels/wechat-channel/media-cache-resolver.js +0 -1
- package/dist/src/channels/wechat-channel/media-resolver.d.ts +0 -186
- package/dist/src/channels/wechat-channel/media-resolver.js +0 -1
- package/dist/src/channels/wechat-channel/message-key.d.ts +0 -19
- package/dist/src/channels/wechat-channel/message-key.js +0 -1
- package/dist/src/channels/wechat-channel/observer.d.ts +0 -171
- package/dist/src/channels/wechat-channel/observer.js +0 -7
- package/dist/src/channels/wechat-channel/outbound-ledger.d.ts +0 -96
- package/dist/src/channels/wechat-channel/outbound-ledger.js +0 -2
- package/dist/src/channels/wechat-channel/outbound-sender.d.ts +0 -74
- package/dist/src/channels/wechat-channel/outbound-sender.js +0 -1
- package/dist/src/channels/wechat-channel/pacing.d.ts +0 -3
- package/dist/src/channels/wechat-channel/pacing.js +0 -1
- package/dist/src/channels/wechat-channel/preflight.d.ts +0 -46
- package/dist/src/channels/wechat-channel/preflight.js +0 -1
- package/dist/src/channels/wechat-channel/runner.d.ts +0 -43
- package/dist/src/channels/wechat-channel/runner.js +0 -1
- package/dist/src/channels/wechat-channel/runtime.d.ts +0 -50
- package/dist/src/channels/wechat-channel/runtime.js +0 -1
- package/dist/src/channels/wechat-channel/scheduler.d.ts +0 -74
- package/dist/src/channels/wechat-channel/scheduler.js +0 -1
- package/dist/src/channels/wechat-channel/vector-store.d.ts +0 -44
- package/dist/src/channels/wechat-channel/vector-store.js +0 -1
- package/dist/src/channels/wechat-rpa/macos-flow.d.ts +0 -55
- package/dist/src/channels/wechat-rpa/macos-flow.js +0 -1
- package/dist/src/channels/wechat-rpa/macos.d.ts +0 -11
- package/dist/src/channels/wechat-rpa/macos.js +0 -21
- package/dist/src/channels/wechat-rpa/normalizer.d.ts +0 -49
- package/dist/src/channels/wechat-rpa/normalizer.js +0 -7
- package/dist/src/channels/wechat-rpa/product-channel.d.ts +0 -76
- package/dist/src/channels/wechat-rpa/product-channel.js +0 -16
- package/dist/src/channels/wechat-rpa-session-sync.d.ts +0 -26
- package/dist/src/channels/wechat-rpa-session-sync.js +0 -1
- package/dist/src/channels/wechat-rpa.d.ts +0 -104
- package/dist/src/channels/wechat-rpa.js +0 -6
- package/dist/src/channels/wecom.d.ts +0 -51
- package/dist/src/channels/wecom.js +0 -4
- package/dist/src/commands/external-attachments.d.ts +0 -9
- package/dist/src/commands/external-attachments.js +0 -1
- package/dist/src/commands/external.d.ts +0 -2
- package/dist/src/commands/external.js +0 -1
- package/dist/src/commands/helper-runtime-official-download.d.ts +0 -80
- package/dist/src/commands/helper-runtime-official-download.js +0 -1
- package/dist/src/commands/runtime.d.ts +0 -120
- package/dist/src/commands/runtime.js +0 -1
- package/dist/src/commands/wechat/command.d.ts +0 -3
- package/dist/src/commands/wechat/command.js +0 -1
- package/dist/src/commands/wechat/direct.d.ts +0 -14
- package/dist/src/commands/wechat/direct.js +0 -2
- package/dist/src/commands/wechat/doctor.d.ts +0 -2
- package/dist/src/commands/wechat/doctor.js +0 -1
- package/dist/src/commands/wechat/ipc.d.ts +0 -9
- package/dist/src/commands/wechat/ipc.js +0 -1
- package/dist/src/commands/wechat/operations.d.ts +0 -3
- package/dist/src/commands/wechat/operations.js +0 -4
- package/dist/src/commands/wechat/output.d.ts +0 -7
- package/dist/src/commands/wechat/output.js +0 -4
- package/dist/src/commands/wechat/types.d.ts +0 -142
- package/dist/src/commands/wechat/types.js +0 -1
- package/dist/src/commands/wechat/utils.d.ts +0 -16
- package/dist/src/commands/wechat/utils.js +0 -1
- package/dist/src/commands/wechat.d.ts +0 -6
- package/dist/src/commands/wechat.js +0 -1
- package/dist/src/devtools/wechat-channel-action-smoke.d.ts +0 -105
- package/dist/src/devtools/wechat-channel-action-smoke.js +0 -10
- package/dist/src/devtools/wechat-channel-download-report.d.ts +0 -111
- package/dist/src/devtools/wechat-channel-download-report.js +0 -2
- package/dist/src/devtools/wechat-channel-markdown-report.d.ts +0 -6
- package/dist/src/devtools/wechat-channel-markdown-report.js +0 -5
- package/dist/src/devtools/wechat-channel-product-steps.d.ts +0 -9
- package/dist/src/devtools/wechat-channel-product-steps.js +0 -40
- package/dist/src/session/handlers/skills.d.ts +0 -7
- package/dist/src/session/handlers/skills.js +0 -1
- package/dist/src/session/handlers/wechat-helper-runtime.d.ts +0 -33
- package/dist/src/session/handlers/wechat-helper-runtime.js +0 -1
- package/dist/src/skills/registry.d.ts +0 -16
- package/dist/src/skills/registry.js +0 -15
- package/dist/src/skills/setup.d.ts +0 -11
- package/dist/src/skills/setup.js +0 -1
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{randomUUID as m}from"node:crypto";import u from"ws";import{ChannelSecretRegistry as f}from"./secret-registry.js";const C="wss://openws.work.weixin.qq.com",w="aibot_subscribe",_="aibot_msg_callback",y="aibot_callback",S="aibot_send_msg",R="aibot_respond_msg",I="ping",h=[2e3,5e3,1e4,3e4],g=4e3;class q{onMessage;type="wecom";secrets=new f;connections=new Map;constructor(e){this.onMessage=e}async connect(e){if(!e.enabled)return;const t=this.ensureConnection(e);return t.connecting||(t.stopped=!1,t.config=e,t.connecting=this.openConnection(t).finally(()=>{t.connecting=null})),t.connecting}async disconnect(e){const t=this.connections.get(e.id);if(!t)return;t.stopped=!0,t.reconnectTimer&&clearTimeout(t.reconnectTimer),t.pingTimer&&clearInterval(t.pingTimer),t.reconnectTimer=null,t.pingTimer=null;for(const r of t.pending.values())clearTimeout(r.timer),r.reject(new Error("WeCom adapter disconnected"));t.pending.clear();const n=t.socket;t.socket=null,n&&await new Promise(r=>{n.once("close",()=>r()),n.close(),setTimeout(r,500)}),this.connections.delete(e.id)}async send(e,t){const n=this.ensureConnection(e);await this.connect(e);const r=t.text.trim();if(!r)throw new Error("Reply text is required");const s=t.messageId?n.replyReqIds.get(t.messageId):void 0,i=n.lastChatReqIds.get(t.conversationId),o=s||i?{msg:{msgtype:"markdown",markdown:{content:r.slice(0,g)}},req_id:s||i}:{chatid:t.conversationId,msgtype:"markdown",markdown:{content:r.slice(0,g)}},c=s||i?R:S,d=await this.sendRequest(n,c,o);this.raiseForWeComError(d,"send message")}async health(e){const t=this.readSecret(e);return!t?.botId||!t.secret?{ok:!1,message:"WeCom adapter requires local credentials"}:this.connections.get(e.id)?.socket?.readyState===u.OPEN?{ok:!0}:{ok:!1,message:"WeCom websocket disconnected"}}ensureConnection(e){let t=this.connections.get(e.id);return t||(t={config:e,socket:null,connecting:null,deviceId:m().replace(/-/g,""),stopped:!1,reconnectAttempt:0,reconnectTimer:null,pingTimer:null,pending:new Map,replyReqIds:new Map,lastChatReqIds:new Map,dedup:new Set,dedupQueue:[],seenContextLineKeys:new Set,seenContextLineQueue:[]},this.connections.set(e.id,t)),t.config=e,t}readSecret(e){const t=this.secrets.get(e.secretRef);if(!t||t.type!=="wecom"||!t.botId||!t.secret)throw new Error("WeCom outbound adapter is not configured on this daemon");return t}async openConnection(e){const t=this.readSecret(e.config),n=new u(C);e.socket=n,await new Promise((s,i)=>{const o=()=>{n.off("open",c),n.off("error",d)},c=()=>{o(),s()},d=a=>{o(),i(a)};n.once("open",c),n.once("error",d)}),n.on("message",s=>{const i=this.parsePayload(s.toString());i&&this.handlePayload(e,i)}),n.on("close",()=>this.scheduleReconnect(e)),n.on("error",()=>this.scheduleReconnect(e));const r=await this.sendRequest(e,w,{bot_id:t.botId,secret:t.secret,device_id:e.deviceId},2e4);this.raiseForWeComError(r,"subscribe"),e.reconnectAttempt=0,e.pingTimer&&clearInterval(e.pingTimer),e.pingTimer=setInterval(()=>{this.sendJson(e,{cmd:I,headers:{req_id:this.newReqId("ping")},body:{}}).catch(()=>{})},3e4),e.pingTimer.unref()}scheduleReconnect(e){if(e.stopped||e.reconnectTimer||e.connecting)return;const t=h[Math.min(e.reconnectAttempt,h.length-1)];e.reconnectAttempt+=1,e.reconnectTimer=setTimeout(()=>{e.reconnectTimer=null,this.connect(e.config).catch(()=>{})},t),e.reconnectTimer.unref()}async sendJson(e,t){if(!e.socket||e.socket.readyState!==u.OPEN)throw new Error("WeCom websocket is not connected");e.socket.send(JSON.stringify(t))}async sendRequest(e,t,n,r=15e3){const s=this.newReqId(t);return new Promise((i,o)=>{const c=setTimeout(()=>{e.pending.delete(s),o(new Error(`WeCom request timed out: ${t}`))},r);c.unref(),e.pending.set(s,{resolve:i,reject:o,timer:c}),this.sendJson(e,{cmd:t,headers:{req_id:s},body:n}).catch(d=>{clearTimeout(c),e.pending.delete(s),o(d instanceof Error?d:new Error(String(d)))})})}handlePayload(e,t){const n=this.payloadReqId(t),r=String(t.cmd||"");if(n&&e.pending.has(n)&&!this.isCallbackCommand(r)){const p=e.pending.get(n);clearTimeout(p.timer),e.pending.delete(n),p.resolve(t);return}if(!this.isCallbackCommand(r))return;const s=this.asRecord(t.body);if(!s)return;const i=String(s.msgid||n||m());if(this.isDuplicate(e,i))return;n&&e.replyReqIds.set(i,n);const o=this.asRecord(s.from)??{},c=String(o.userid||""),d=String(o.name||o.userid||""),a=String(s.chatid||c).trim();if(!a)return;n&&e.lastChatReqIds.set(a,n);const l=this.filterContextText(e,a,this.extractText(s).trim());l&&this.onMessage?.({managerSessionId:e.config.managerSessionId,channelId:e.config.id,channelType:"wecom",conversationId:a,messageId:i,sender:{id:c||a,name:d||c||a},text:l,attachments:[],receivedAt:new Date().toISOString(),replyTarget:""})}isDuplicate(e,t){if(e.dedup.has(t))return!0;if(e.dedup.add(t),e.dedupQueue.push(t),e.dedupQueue.length>1e3){const n=e.dedupQueue.shift();n&&e.dedup.delete(n)}return!1}extractText(e){const t=String(e.msgtype||"").toLowerCase();if(t==="mixed"){const r=this.asRecord(e.mixed);return(Array.isArray(r?.msg_item)?r?.msg_item:[]).map(i=>{const o=this.asRecord(i);return String(o?.msgtype||"").toLowerCase()!=="text"?"":String(this.asRecord(o?.text)?.content||"").trim()}).filter(Boolean).join(`
|
|
2
|
-
`).trim()}const n=String(this.asRecord(e.text)?.content||"").trim();return n||(t==="voice"?String(this.asRecord(e.voice)?.content||"").trim():t==="appmsg"?String(this.asRecord(e.appmsg)?.title||"").trim():"")}filterContextText(e,t,n){if(!n.includes("\u5916\u90E8\u6D88\u606F\u4E0A\u4E0B\u6587")&&!n.includes("\u5916\u90E8\u4F01\u4E1A\u5FAE\u4FE1\u7FA4\u6D88\u606F\u4E0A\u4E0B\u6587"))return n;const r=n.split(/\r?\n/),s=[],i=[];let o=!1;for(const c of r){const d=this.normalizeContextLine(c);if(!d){o||s.push(c);continue}o=!0;const a=`${t}
|
|
3
|
-
${d}`;e.seenContextLineKeys.has(a)||(this.rememberContextLine(e,a),i.push(c))}return o?i.length?[...s,...i].filter(c=>c.trim()).join(`
|
|
4
|
-
`).trim():"":n}normalizeContextLine(e){const t=e.trim().replace(/^=>\s*/,"");return/^\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}\s+.+/.test(t)?t:null}rememberContextLine(e,t){for(e.seenContextLineKeys.add(t),e.seenContextLineQueue.push(t);e.seenContextLineQueue.length>2e3;){const n=e.seenContextLineQueue.shift();n&&e.seenContextLineKeys.delete(n)}}raiseForWeComError(e,t){const n=typeof e.errcode=="number"?e.errcode:Number(e.errcode||0);if(!Number.isFinite(n)||n===0)return;const r=String(e.errmsg||"unknown error");throw new Error(`WeCom ${t} failed: ${r} (${n})`)}parsePayload(e){try{const t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}payloadReqId(e){const n=this.asRecord(e.headers)?.req_id;return typeof n=="string"&&n?n:null}asRecord(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}isCallbackCommand(e){return e===_||e===y}newReqId(e){return`${e}_${m().replace(/-/g,"")}`}}export{q as WeComChannelAdapter};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
export type ExternalAttachmentKind = 'image' | 'video' | 'file';
|
|
2
|
-
export type ExternalAttachmentPayload = {
|
|
3
|
-
kind: ExternalAttachmentKind;
|
|
4
|
-
name: string;
|
|
5
|
-
mimeType: string;
|
|
6
|
-
size: number;
|
|
7
|
-
localPath: string;
|
|
8
|
-
};
|
|
9
|
-
export declare function readExternalAttachment(filePath: string, kind: ExternalAttachmentKind): ExternalAttachmentPayload;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import m from"node:fs";import n from"node:path";const p={".jpg":"image/jpeg",".jpeg":"image/jpeg",".png":"image/png",".gif":"image/gif",".webp":"image/webp",".mp4":"video/mp4",".mov":"video/quicktime",".pdf":"application/pdf",".txt":"text/plain",".md":"text/markdown",".csv":"text/csv",".doc":"application/msword",".docx":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",".xls":"application/vnd.ms-excel",".xlsx":"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",".ppt":"application/vnd.ms-powerpoint",".pptx":"application/vnd.openxmlformats-officedocument.presentationml.presentation",".zip":"application/zip"},a=Number(process.env.SHENNIAN_EXTERNAL_ATTACHMENT_MAX_BYTES||20*1024*1024);function r(i,t){const e=n.extname(i).toLowerCase();return p[e]?p[e]:t==="image"?"image/jpeg":t==="video"?"video/mp4":"application/octet-stream"}function l(i,t){const e=n.resolve(i),o=m.statSync(e);if(!o.isFile())throw new Error(`Attachment is not a file: ${e}`);if(o.size>a)throw new Error(`Attachment is too large: ${o.size} bytes. Max: ${a} bytes.`);return{kind:t,name:n.basename(e),mimeType:r(e,t),size:o.size,localPath:e}}export{l as readExternalAttachment};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import d from"node:fs";import s from"chalk";import{resolveShennianPath as c}from"../config/index.js";import{readExternalAttachment as a}from"./external-attachments.js";function p(){const n=c("runtime","manager-ipc.json");try{const t=JSON.parse(d.readFileSync(n,"utf-8")),e=Number(t.pid);return Number.isInteger(e)&&e>0&&!m(e)?{error:`Manager IPC runtime file is stale for PID ${e}. Restart the desktop daemon and retry.`}:{url:typeof t.url=="string"?t.url:void 0,token:typeof t.token=="string"?t.token:void 0}}catch{return{}}}function l(n){const t=!process.env.SHENNIAN_MANAGER_IPC_URL||!process.env.SHENNIAN_MANAGER_IPC_TOKEN?p():{};t.error&&(console.error(s.red(`\u2717 ${t.error}`)),process.exit(1));const e=process.env.SHENNIAN_MANAGER_IPC_URL||t.url,o=process.env.SHENNIAN_MANAGER_IPC_TOKEN||t.token,i=n?.trim()||process.env.SHENNIAN_EXTERNAL_SESSION_ID||process.env.SHENNIAN_MANAGER_SESSION_ID;return(!e||!o||!i)&&(console.error(s.red("\u2717 This command must run inside a Shennian conversation with an external channel, or pass --session-id <id>.")),process.exit(1)),{url:e,token:o,sessionId:i}}function m(n){try{return process.kill(n,0),!0}catch{return!1}}async function r(n){const t=l(n.sessionId),e=n.replyTarget?.trim()||process.env.SHENNIAN_EXTERNAL_REPLY_TARGET||void 0,o=await fetch(`${t.url}/external/reply`,{method:"POST",headers:{authorization:`Bearer ${t.token}`,"content-type":"application/json","x-shennian-manager-session-id":t.sessionId},body:JSON.stringify({managerSessionId:t.sessionId,text:n.text,attachment:n.attachment,idempotencyKey:n.idempotencyKey,replyTarget:e})}),i=await o.json().catch(()=>({ok:!1,error:o.statusText}));if(!o.ok||!i.ok)throw new Error(i.error||`External send failed: ${o.status}`);console.log("ok")}function E(n){const t=n.command("external").description("External channel tools for this Shennian conversation");t.command("send").description("Send a message to the external channel bound to this conversation").requiredOption("--text <text>","Message text").option("--session-id <id>","Shennian conversation/session id; defaults to injected current-session env").option("--reply-target <id>","Daemon-generated reply target; defaults to SHENNIAN_EXTERNAL_REPLY_TARGET or latest external message").option("--idempotency-key <key>","Idempotency key").action(async e=>{await r({text:e.text,replyTarget:e.replyTarget,idempotencyKey:e.idempotencyKey,sessionId:e.sessionId})}),t.command("send-image").description("Send an image file to the external channel bound to this conversation").requiredOption("--path <path>","Image file path").option("--caption <text>","Optional text to send before the image").option("--session-id <id>","Shennian conversation/session id; defaults to injected current-session env").option("--reply-target <id>","Daemon-generated reply target; defaults to SHENNIAN_EXTERNAL_REPLY_TARGET or latest external message").option("--idempotency-key <key>","Idempotency key").action(async e=>{await r({text:e.caption,attachment:a(e.path,"image"),replyTarget:e.replyTarget,idempotencyKey:e.idempotencyKey,sessionId:e.sessionId})}),t.command("send-video").description("Send a video file to the external channel bound to this conversation").requiredOption("--path <path>","Video file path").option("--caption <text>","Optional text to send before the video").option("--session-id <id>","Shennian conversation/session id; defaults to injected current-session env").option("--reply-target <id>","Daemon-generated reply target; defaults to SHENNIAN_EXTERNAL_REPLY_TARGET or latest external message").option("--idempotency-key <key>","Idempotency key").action(async e=>{await r({text:e.caption,attachment:a(e.path,"video"),replyTarget:e.replyTarget,idempotencyKey:e.idempotencyKey,sessionId:e.sessionId})}),t.command("send-file").description("Send a file to the external channel bound to this conversation").requiredOption("--path <path>","File path").option("--caption <text>","Optional text to send before the file").option("--session-id <id>","Shennian conversation/session id; defaults to injected current-session env").option("--reply-target <id>","Daemon-generated reply target; defaults to SHENNIAN_EXTERNAL_REPLY_TARGET or latest external message").option("--idempotency-key <key>","Idempotency key").action(async e=>{await r({text:e.caption,attachment:a(e.path,"file"),replyTarget:e.replyTarget,idempotencyKey:e.idempotencyKey,sessionId:e.sessionId})})}export{E as registerExternalCommand};
|
|
@@ -1,80 +0,0 @@
|
|
|
1
|
-
type HelperRuntimePlatform = 'darwin' | 'win32';
|
|
2
|
-
export type HelperRuntimeOfficialArtifact = {
|
|
3
|
-
platform: HelperRuntimePlatform;
|
|
4
|
-
arch: string;
|
|
5
|
-
helperVersion: string;
|
|
6
|
-
protocolVersion: number;
|
|
7
|
-
minCliVersion: string;
|
|
8
|
-
url: string;
|
|
9
|
-
sizeBytes: number;
|
|
10
|
-
sha256: string;
|
|
11
|
-
packageManifestSha256?: string;
|
|
12
|
-
evidenceUrl?: string;
|
|
13
|
-
};
|
|
14
|
-
export type HelperRuntimeOfficialManifest = {
|
|
15
|
-
schemaVersion: 1;
|
|
16
|
-
kind: 'shennian-helper-runtime-index';
|
|
17
|
-
channel: string;
|
|
18
|
-
generatedAt: string;
|
|
19
|
-
artifacts: HelperRuntimeOfficialArtifact[];
|
|
20
|
-
};
|
|
21
|
-
export type HelperRuntimeOfficialDownloadFailureReason = 'helper_runtime_manifest_unavailable' | 'helper_runtime_artifact_unavailable' | 'helper_runtime_download_failed' | 'helper_runtime_artifact_integrity_mismatch' | 'helper_runtime_artifact_invalid';
|
|
22
|
-
export type HelperRuntimeOfficialDownloadResult = {
|
|
23
|
-
ok: true;
|
|
24
|
-
sourceDir: string;
|
|
25
|
-
tempDir: string;
|
|
26
|
-
cleanup: () => void;
|
|
27
|
-
channel: string;
|
|
28
|
-
manifestUrl: string;
|
|
29
|
-
artifactUrl: string;
|
|
30
|
-
artifactSha256: string;
|
|
31
|
-
artifactSizeBytes: number;
|
|
32
|
-
platform: HelperRuntimePlatform;
|
|
33
|
-
arch: string;
|
|
34
|
-
helperVersion: string;
|
|
35
|
-
protocolVersion: number;
|
|
36
|
-
minCliVersion: string;
|
|
37
|
-
} | {
|
|
38
|
-
ok: false;
|
|
39
|
-
reasonCode: HelperRuntimeOfficialDownloadFailureReason;
|
|
40
|
-
message: string;
|
|
41
|
-
manifestUrl?: string;
|
|
42
|
-
artifactUrl?: string;
|
|
43
|
-
};
|
|
44
|
-
type FetchLike = (url: string, init?: {
|
|
45
|
-
signal?: AbortSignal;
|
|
46
|
-
}) => Promise<Response>;
|
|
47
|
-
export type HelperRuntimeOfficialDownloadOptions = {
|
|
48
|
-
platform: HelperRuntimePlatform;
|
|
49
|
-
arch?: string;
|
|
50
|
-
env?: NodeJS.ProcessEnv;
|
|
51
|
-
channel?: string;
|
|
52
|
-
manifestUrl?: string;
|
|
53
|
-
fetchImpl?: FetchLike;
|
|
54
|
-
timeoutMs?: number;
|
|
55
|
-
maxBytes?: number;
|
|
56
|
-
workRoot?: string;
|
|
57
|
-
downloadFile?: (input: {
|
|
58
|
-
url: string;
|
|
59
|
-
outputPath: string;
|
|
60
|
-
fetchImpl: FetchLike;
|
|
61
|
-
timeoutMs: number;
|
|
62
|
-
maxBytes: number;
|
|
63
|
-
}) => Promise<void>;
|
|
64
|
-
extractZip?: (input: {
|
|
65
|
-
zipPath: string;
|
|
66
|
-
outputDir: string;
|
|
67
|
-
platform: HelperRuntimePlatform;
|
|
68
|
-
}) => Promise<void> | void;
|
|
69
|
-
};
|
|
70
|
-
export declare function downloadOfficialHelperRuntimePackage(options: HelperRuntimeOfficialDownloadOptions): Promise<HelperRuntimeOfficialDownloadResult>;
|
|
71
|
-
export declare function getOfficialHelperRuntimeManifestUrl(input?: {
|
|
72
|
-
env?: NodeJS.ProcessEnv;
|
|
73
|
-
channel?: string;
|
|
74
|
-
}): string;
|
|
75
|
-
export declare function selectOfficialHelperRuntimeArtifact(input: {
|
|
76
|
-
manifest: HelperRuntimeOfficialManifest;
|
|
77
|
-
platform: HelperRuntimePlatform;
|
|
78
|
-
arch: string;
|
|
79
|
-
}): HelperRuntimeOfficialArtifact | null;
|
|
80
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import U from"node:crypto";import{once as _}from"node:events";import o from"node:fs";import z from"node:os";import h from"node:path";import{spawnSync as y}from"node:child_process";const R="https://videoindustry.oss-cn-hangzhou.aliyuncs.com/shennian/helper-runtime",g="stable",$=5*6e4,I=350*1024*1024;async function X(e){const r=e.env??process.env,n=S(e.channel??r.SHENNIAN_HELPER_RUNTIME_CHANNEL)??g,t=e.manifestUrl??P({env:r,channel:n}),a=e.arch??process.arch,s=A(r.SHENNIAN_HELPER_RUNTIME_DOWNLOAD_TIMEOUT_MS)??e.timeoutMs??$,c=A(r.SHENNIAN_HELPER_RUNTIME_MAX_BYTES)??e.maxBytes??I,m=e.fetchImpl??globalThis.fetch?.bind(globalThis);if(!m)return{ok:!1,reasonCode:"helper_runtime_manifest_unavailable",message:"This Node.js runtime does not provide fetch for official Helper runtime download.",manifestUrl:t};const l=await L({manifestUrl:t,fetchImpl:m,timeoutMs:s});if(!l.ok)return l;const i=x({manifest:l.manifest,platform:e.platform,arch:a});if(!i)return{ok:!1,reasonCode:"helper_runtime_artifact_unavailable",message:`No official Helper runtime artifact is available for ${e.platform}/${a} on channel ${l.manifest.channel}.`,manifestUrl:t};const f=o.mkdtempSync(h.join(e.workRoot??z.tmpdir(),"shennian-helper-runtime-")),d=h.join(f,"helper-runtime.zip"),p=h.join(f,"source");try{await(e.downloadFile??C)({url:i.url,outputPath:d,fetchImpl:m,timeoutMs:s,maxBytes:c})}catch(u){return o.rmSync(f,{recursive:!0,force:!0}),{ok:!1,reasonCode:"helper_runtime_download_failed",message:`Official Helper runtime download failed: ${u instanceof Error?u.message:String(u)}`,manifestUrl:t,artifactUrl:i.url}}const H=o.statSync(d).size,T=O(d);if(H!==i.sizeBytes||T!==i.sha256)return o.rmSync(f,{recursive:!0,force:!0}),{ok:!1,reasonCode:"helper_runtime_artifact_integrity_mismatch",message:"Official Helper runtime artifact failed size or sha256 verification.",manifestUrl:t,artifactUrl:i.url};try{o.mkdirSync(p,{recursive:!0}),await(e.extractZip??M)({zipPath:d,outputDir:p,platform:e.platform}),v(p)}catch(u){return o.rmSync(f,{recursive:!0,force:!0}),{ok:!1,reasonCode:"helper_runtime_artifact_invalid",message:`Official Helper runtime artifact could not be extracted safely: ${u instanceof Error?u.message:String(u)}`,manifestUrl:t,artifactUrl:i.url}}return{ok:!0,sourceDir:p,tempDir:f,cleanup:()=>o.rmSync(f,{recursive:!0,force:!0}),channel:l.manifest.channel,manifestUrl:t,artifactUrl:i.url,artifactSha256:i.sha256,artifactSizeBytes:i.sizeBytes,platform:i.platform,arch:i.arch,helperVersion:i.helperVersion,protocolVersion:i.protocolVersion,minCliVersion:i.minCliVersion}}function P(e={}){const r=e.env??process.env,n=r.SHENNIAN_HELPER_RUNTIME_MANIFEST_URL?.trim();if(n)return n;const t=S(e.channel??r.SHENNIAN_HELPER_RUNTIME_CHANNEL)??g;return`${(r.SHENNIAN_HELPER_RUNTIME_BASE_URL?.trim()||R).replace(/\/+$/g,"")}/${encodeURIComponent(t)}/manifest.json`}function x(e){return N(e.manifest)?e.manifest.artifacts.filter(n=>n.platform===e.platform).find(n=>D(n.arch,e.arch))??null:null}async function L(e){try{const r=new AbortController,n=setTimeout(()=>r.abort(),e.timeoutMs);try{const t=await e.fetchImpl(e.manifestUrl,{signal:r.signal});if(!t.ok)throw new Error(`HTTP ${t.status}`);const a=JSON.parse(await t.text());if(!N(a))throw new Error("manifest schema is invalid");return{ok:!0,manifest:a}}finally{clearTimeout(n)}}catch(r){return{ok:!1,reasonCode:"helper_runtime_manifest_unavailable",message:`Official Helper runtime manifest is unavailable: ${r instanceof Error?r.message:String(r)}`,manifestUrl:e.manifestUrl}}}async function C(e){const r=new AbortController,n=setTimeout(()=>r.abort(),e.timeoutMs);let t=null;try{const a=await e.fetchImpl(e.url,{signal:r.signal});if(!a.ok)throw new Error(`HTTP ${a.status}`);if(!a.body)throw new Error("response body is empty");t=o.createWriteStream(e.outputPath,{flags:"wx"});const s=a.body.getReader();let c=0;for(;;){const{done:m,value:l}=await s.read();if(m)break;const i=Buffer.from(l);if(c+=i.byteLength,c>e.maxBytes)throw new Error(`download exceeded ${e.maxBytes} bytes`);t.write(i)||await _(t,"drain")}t.end(),await _(t,"finish")}finally{clearTimeout(n),t&&!t.closed&&t.destroy()}}async function M(e){if(k(e.zipPath),process.platform==="win32"){E("powershell.exe",["-NoProfile","-ExecutionPolicy","Bypass","-Command",`Expand-Archive -LiteralPath ${b(e.zipPath)} -DestinationPath ${b(e.outputDir)} -Force`]);return}if(e.platform==="darwin"&&w("ditto")){E("ditto",["-x","-k",e.zipPath,e.outputDir]);return}E("unzip",["-q",e.zipPath,"-d",e.outputDir])}function k(e){const r=w("unzip")?"unzip":w("tar")?"tar":null;if(!r)return;const n=r==="unzip"?y(r,["-Z","-1",e],{encoding:"utf8"}):y(r,["-tf",e],{encoding:"utf8"});if(n.status!==0)throw new Error(`unable to inspect zip entries with ${r}`);for(const t of n.stdout.split(/\r?\n/u).filter(Boolean)){const a=t.replace(/\\/g,"/");if(a.startsWith("/")||a.includes("../")||a===".."||/^[A-Za-z]:\//u.test(a))throw new Error(`unsafe zip entry: ${t}`)}}function v(e){const r=o.realpathSync(e),n=[e];for(;n.length>0;){const t=n.pop();if(t)for(const a of o.readdirSync(t,{withFileTypes:!0})){const s=h.join(t,a.name),c=o.realpathSync(s);if(c!==r&&!c.startsWith(`${r}${h.sep}`))throw new Error(`extracted path escapes target directory: ${s}`);a.isDirectory()&&n.push(s)}}}function N(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const r=e;return r.schemaVersion!==1||r.kind!=="shennian-helper-runtime-index"||!r.channel||typeof r.channel!="string"||!r.generatedAt||typeof r.generatedAt!="string"||!Array.isArray(r.artifacts)?!1:r.artifacts.every(B)}function B(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const r=e;return(r.platform==="darwin"||r.platform==="win32")&&typeof r.arch=="string"&&typeof r.helperVersion=="string"&&Number.isInteger(r.protocolVersion)&&typeof r.minCliVersion=="string"&&typeof r.url=="string"&&typeof r.sizeBytes=="number"&&Number.isInteger(r.sizeBytes)&&r.sizeBytes>0&&typeof r.sha256=="string"&&/^[a-f0-9]{64}$/iu.test(r.sha256)}function D(e,r){const n=e.toLowerCase(),t=r.toLowerCase();return n===t||n==="universal"||n==="all"||n===`win-${t}`||n===`darwin-${t}`}function S(e){const r=e?.trim();return!r||!/^[a-z0-9][a-z0-9._-]{0,63}$/iu.test(r)?null:r}function A(e){if(!e)return null;const r=Number(e);return Number.isInteger(r)&&r>0?r:null}function O(e){return U.createHash("sha256").update(o.readFileSync(e)).digest("hex")}function w(e){return y(e,["--version"],{stdio:"ignore"}).status===0}function E(e,r){const n=y(e,r,{stdio:"ignore"});if(n.status!==0)throw new Error(`${e} exited ${n.status}`)}function b(e){return`'${e.replace(/'/g,"''")}'`}export{X as downloadOfficialHelperRuntimePackage,P as getOfficialHelperRuntimeManifestUrl,x as selectOfficialHelperRuntimeArtifact};
|
|
@@ -1,120 +0,0 @@
|
|
|
1
|
-
import fs from 'node:fs';
|
|
2
|
-
import type { Command } from 'commander';
|
|
3
|
-
import { type WeChatChannelHelperRuntimePackageManifest } from '../channels/wechat-channel/helper-assets.js';
|
|
4
|
-
import { type HelperRuntimeOfficialDownloadOptions } from './helper-runtime-official-download.js';
|
|
5
|
-
type RuntimeCommandPlatform = 'darwin' | 'win32';
|
|
6
|
-
export type HelperRuntimeInstallResult = {
|
|
7
|
-
ok: true;
|
|
8
|
-
action: 'installed' | 'already_installed';
|
|
9
|
-
platform: RuntimeCommandPlatform;
|
|
10
|
-
targetPlatform: RuntimeCommandPlatform;
|
|
11
|
-
installed: true;
|
|
12
|
-
repairable: false;
|
|
13
|
-
targetDir: string;
|
|
14
|
-
helperDir: string;
|
|
15
|
-
helperPath: string;
|
|
16
|
-
helperVersion: string;
|
|
17
|
-
runtimeVersion: string;
|
|
18
|
-
protocolVersion: number;
|
|
19
|
-
minCliVersion?: string;
|
|
20
|
-
sha256?: {
|
|
21
|
-
runtimeManifest: string;
|
|
22
|
-
entrypoint: string | null;
|
|
23
|
-
};
|
|
24
|
-
packageManifestPath?: string;
|
|
25
|
-
packageKind?: string;
|
|
26
|
-
installTarget?: WeChatChannelHelperRuntimePackageManifest['installTarget'];
|
|
27
|
-
signature?: WeChatChannelHelperRuntimePackageManifest['signature'];
|
|
28
|
-
source?: 'local' | 'official-download';
|
|
29
|
-
officialDownload?: {
|
|
30
|
-
channel: string;
|
|
31
|
-
manifestUrl: string;
|
|
32
|
-
artifactUrl: string;
|
|
33
|
-
artifactSha256: string;
|
|
34
|
-
artifactSizeBytes: number;
|
|
35
|
-
arch: string;
|
|
36
|
-
helperVersion: string;
|
|
37
|
-
protocolVersion: number;
|
|
38
|
-
minCliVersion: string;
|
|
39
|
-
};
|
|
40
|
-
message: string;
|
|
41
|
-
} | {
|
|
42
|
-
ok: false;
|
|
43
|
-
platform?: RuntimeCommandPlatform;
|
|
44
|
-
targetPlatform?: RuntimeCommandPlatform;
|
|
45
|
-
installed?: boolean;
|
|
46
|
-
repairable: boolean;
|
|
47
|
-
reasonCode: string;
|
|
48
|
-
message: string;
|
|
49
|
-
repairSuggestion?: string;
|
|
50
|
-
checkedSources?: string[];
|
|
51
|
-
officialDownload?: {
|
|
52
|
-
manifestUrl?: string;
|
|
53
|
-
artifactUrl?: string;
|
|
54
|
-
};
|
|
55
|
-
};
|
|
56
|
-
export type HelperRuntimeStatusResult = {
|
|
57
|
-
ok: boolean;
|
|
58
|
-
platform?: RuntimeCommandPlatform;
|
|
59
|
-
targetPlatform?: RuntimeCommandPlatform;
|
|
60
|
-
installed: boolean;
|
|
61
|
-
repairable: boolean;
|
|
62
|
-
reasonCode?: string;
|
|
63
|
-
message: string;
|
|
64
|
-
helperDir?: string;
|
|
65
|
-
helperPath?: string;
|
|
66
|
-
helperVersion?: string;
|
|
67
|
-
runtimeVersion?: string;
|
|
68
|
-
protocolVersion?: number;
|
|
69
|
-
minCliVersion?: string;
|
|
70
|
-
sha256?: {
|
|
71
|
-
runtimeManifest: string;
|
|
72
|
-
entrypoint: string | null;
|
|
73
|
-
};
|
|
74
|
-
packageManifestPath?: string;
|
|
75
|
-
packageKind?: string;
|
|
76
|
-
installTarget?: WeChatChannelHelperRuntimePackageManifest['installTarget'];
|
|
77
|
-
signature?: WeChatChannelHelperRuntimePackageManifest['signature'];
|
|
78
|
-
runtimeRoot?: string | null;
|
|
79
|
-
repairSuggestion?: string;
|
|
80
|
-
checkedSources?: string[];
|
|
81
|
-
};
|
|
82
|
-
type RuntimeIo = {
|
|
83
|
-
existsSync?: typeof fs.existsSync;
|
|
84
|
-
lstatSync?: typeof fs.lstatSync;
|
|
85
|
-
readFileSync?: typeof fs.readFileSync;
|
|
86
|
-
realpathSync?: typeof fs.realpathSync;
|
|
87
|
-
mkdirSync?: typeof fs.mkdirSync;
|
|
88
|
-
rmSync?: typeof fs.rmSync;
|
|
89
|
-
cpSync?: typeof fs.cpSync;
|
|
90
|
-
renameSync?: typeof fs.renameSync;
|
|
91
|
-
chmodSync?: typeof fs.chmodSync;
|
|
92
|
-
homedir?: () => string;
|
|
93
|
-
stopMacHelperProcesses?: (targetDir: string) => void;
|
|
94
|
-
stopWindowsHelperProcesses?: () => void;
|
|
95
|
-
};
|
|
96
|
-
export declare function registerRuntimeCommand(program: Command): void;
|
|
97
|
-
export declare function getHelperRuntimeStatus(input?: {
|
|
98
|
-
platform?: NodeJS.Platform | string;
|
|
99
|
-
env?: NodeJS.ProcessEnv;
|
|
100
|
-
homedir?: string;
|
|
101
|
-
}): HelperRuntimeStatusResult;
|
|
102
|
-
export declare function installHelperRuntime(input?: {
|
|
103
|
-
source?: string;
|
|
104
|
-
platform?: NodeJS.Platform | string;
|
|
105
|
-
env?: NodeJS.ProcessEnv;
|
|
106
|
-
homedir?: string;
|
|
107
|
-
force?: boolean;
|
|
108
|
-
io?: RuntimeIo;
|
|
109
|
-
}): HelperRuntimeInstallResult;
|
|
110
|
-
export declare function installHelperRuntimeWithOfficialDownload(input?: {
|
|
111
|
-
source?: string;
|
|
112
|
-
platform?: NodeJS.Platform | string;
|
|
113
|
-
env?: NodeJS.ProcessEnv;
|
|
114
|
-
homedir?: string;
|
|
115
|
-
force?: boolean;
|
|
116
|
-
preferOfficialDownload?: boolean;
|
|
117
|
-
io?: RuntimeIo;
|
|
118
|
-
officialDownload?: false | Partial<HelperRuntimeOfficialDownloadOptions>;
|
|
119
|
-
}): Promise<HelperRuntimeInstallResult>;
|
|
120
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import m from"node:fs";import C from"node:os";import t from"node:path";import{spawnSync as H}from"node:child_process";import V from"chalk";import{getDefaultWeChatHelperRuntimeRoot as b,readWeChatChannelHelperRuntimePackageManifest as y,resolveWeChatChannelHelperAsset as R,SHENNIAN_HELPER_RUNTIME_DIR_ENV as L,WECHAT_CHANNEL_HELPER_DIR_ENV as N}from"../channels/wechat-channel/helper-assets.js";import{downloadOfficialHelperRuntimePackage as W}from"./helper-runtime-official-download.js";import{compareVersions as K,getCurrentVersion as j}from"../upgrade/engine.js";import{SerialWeChatAutomationLane as F}from"../channels/wechat-channel/automation-lane.js";const h="helper-runtime-package.json";function ke(e){const r=e.command("runtime").description("Install, repair, and inspect Shennian local runtimes");r.command("status").description("Print local Shennian runtime status").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(o=>{const a=M({platform:o.platform});_(a,!!o.json),a.ok||(process.exitCode=1)}),r.command("install").description("Install a Shennian runtime component").argument("<component>","Runtime component, currently only: helper").option("--source <path>","Helper runtime package/source directory").option("--channel <channel>","Official Helper runtime channel: stable or next").option("--manifest-url <url>","Official Helper runtime manifest URL override").option("--no-official-download","Do not fall back to Shennian official Helper runtime download").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(async(o,a)=>{const n=o==="helper"?await P({source:a.source,platform:a.platform,officialDownload:a.officialDownload===!1?!1:{channel:a.channel,manifestUrl:a.manifestUrl}}):D(o);_(n,!!a.json),n.ok||(process.exitCode=1)}),r.command("upgrade").description("Upgrade a Shennian runtime component").argument("<component>","Runtime component, currently only: helper").option("--source <path>","Helper runtime package/source directory").option("--channel <channel>","Official Helper runtime channel: stable or next").option("--manifest-url <url>","Official Helper runtime manifest URL override").option("--no-official-download","Do not use Shennian official Helper runtime download").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(async(o,a)=>{const n=o==="helper"?await P({source:a.source,platform:a.platform,force:!0,preferOfficialDownload:!a.source,officialDownload:a.officialDownload===!1?!1:{channel:a.channel,manifestUrl:a.manifestUrl}}):D(o);_(n,!!a.json),n.ok||(process.exitCode=1)}),r.command("repair").description("Repair a Shennian runtime component").argument("[component]","Runtime component, currently only: helper","helper").option("--source <path>","Helper runtime package/source directory").option("--channel <channel>","Official Helper runtime channel: stable or next").option("--manifest-url <url>","Official Helper runtime manifest URL override").option("--no-official-download","Do not fall back to Shennian official Helper runtime download").option("--json","Output JSON",!1).option("--platform <platform>","Platform override: darwin or win32").action(async(o,a)=>{const n=o==="helper"?await P({source:a.source,platform:a.platform,force:!0,preferOfficialDownload:!a.source,officialDownload:a.officialDownload===!1?!1:{channel:a.channel,manifestUrl:a.manifestUrl}}):D(o);_(n,!!a.json),n.ok||(process.exitCode=1)})}function M(e={}){const r=S(e.platform);if(!r)return{ok:!1,installed:!1,repairable:!1,reasonCode:"unsupported_platform",message:"Shennian Helper runtime is only available on macOS and Windows.",repairSuggestion:c("unsupported_platform")};const o=e.env??process.env,a=e.homedir,n=R({platform:r,env:o,homedir:a,includeInstalledDesktop:!1}),i=b({platform:r,env:o,homedir:a});if(!n.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:q(n.reasonCode),reasonCode:n.reasonCode,message:n.message,runtimeRoot:i,repairSuggestion:c(n.reasonCode),checkedSources:k({platform:r,env:o,homedir:a})};const s=y({platform:r,helperDir:n.helperDir});if(!s.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:s.reasonCode,message:s.message,helperDir:n.helperDir,helperPath:n.helperPath,helperVersion:n.version,runtimeVersion:n.version,protocolVersion:n.manifest.protocolVersion,runtimeRoot:i,repairSuggestion:c(s.reasonCode),checkedSources:k({platform:r,env:o,homedir:a})};const l=A({platform:r,packageManifest:s.manifest,currentCliVersion:j(),helperVersion:n.version,protocolVersion:n.manifest.protocolVersion});return l.ok?{ok:!0,platform:r,targetPlatform:r,installed:!0,repairable:!1,message:`Shennian Helper runtime is installed: ${n.helperDir}`,helperDir:n.helperDir,helperPath:n.helperPath,helperVersion:n.version,runtimeVersion:n.version,protocolVersion:n.manifest.protocolVersion,minCliVersion:s.manifest.minCliVersion,sha256:s.manifest.sha256,packageManifestPath:s.manifestPath,packageKind:s.manifest.packageKind,installTarget:s.manifest.installTarget,signature:s.manifest.signature,runtimeRoot:i}:{ok:!1,platform:r,targetPlatform:r,installed:!0,repairable:l.repairable,reasonCode:l.reasonCode,message:l.message,helperDir:n.helperDir,helperPath:n.helperPath,helperVersion:n.version,runtimeVersion:n.version,protocolVersion:n.manifest.protocolVersion,minCliVersion:s.manifest.minCliVersion,sha256:s.manifest.sha256,packageManifestPath:s.manifestPath,packageKind:s.manifest.packageKind,installTarget:s.manifest.installTarget,signature:s.manifest.signature,runtimeRoot:i,repairSuggestion:c(l.reasonCode,s.manifest.minCliVersion),checkedSources:k({platform:r,env:o,homedir:a})}}function I(e={}){const r=S(e.platform);if(!r)return{ok:!1,reasonCode:"unsupported_platform",message:"Shennian Helper runtime is only available on macOS and Windows.",repairable:!1,repairSuggestion:c("unsupported_platform")};const o=e.env??process.env,a=X(e.io),n=e.homedir??a.homedir(),i=M({platform:r,env:o,homedir:n});if(i.ok&&!e.force&&i.helperDir&&i.helperPath&&i.helperVersion&&i.protocolVersion)return{ok:!0,action:"already_installed",platform:r,targetPlatform:r,installed:!0,repairable:!1,targetDir:re(r,i.helperDir),helperDir:i.helperDir,helperPath:i.helperPath,helperVersion:i.helperVersion,runtimeVersion:i.helperVersion,protocolVersion:i.protocolVersion,minCliVersion:i.minCliVersion,sha256:i.sha256,packageManifestPath:i.packageManifestPath,packageKind:i.packageKind,installTarget:i.installTarget,signature:i.signature,message:`Shennian Helper runtime is already installed: ${i.helperDir}`};const s=e.source?[t.resolve(e.source)]:k({platform:r,env:o,homedir:n}),l=s.map(w=>Q({candidate:w,platform:r,io:a})).find(w=>w!=null);if(!l)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:"helper_runtime_source_missing",message:"No installable Shennian Helper runtime package was found. Open Shennian Desktop, pass --source, or download the official helper package.",repairSuggestion:c("helper_runtime_source_missing"),checkedSources:s};const d=y({platform:r,manifestPath:l.packageManifestPath});if(!d.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:d.reasonCode,message:d.message,repairSuggestion:c(d.reasonCode),checkedSources:s};const g=A({platform:r,packageManifest:d.manifest,currentCliVersion:j()});if(!g.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:g.repairable,reasonCode:g.reasonCode,message:g.message,repairSuggestion:c(g.reasonCode,d.manifest.minCliVersion),checkedSources:s};const u=ee({platform:r,env:o,homedir:n,packageKind:l.packageKind});if(!u)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!1,reasonCode:"helper_runtime_target_unavailable",message:"Unable to determine Helper runtime install target for this platform.",repairSuggestion:c("helper_runtime_target_unavailable"),checkedSources:s};const v=a.existsSync(u);v&&x({platform:r,targetDir:u,io:a}),ne({platform:r,sourceDir:l.sourceDir,targetDir:u,io:a}),v&&x({platform:r,targetDir:u,io:a}),se({sourceManifestPath:l.packageManifestPath,targetManifestPath:l.packageManifestPathInTarget(u),io:a});const f=R({platform:r,baseDir:l.manifestDirInTarget(u),verifyIntegrity:!0});if(!f.ok)return{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:f.reasonCode,message:`Installed Helper runtime could not be verified: ${f.message}`,repairSuggestion:c(f.reasonCode),checkedSources:s};le(r,f.helperPath,a);const p=y({platform:r,helperDir:f.helperDir});return p.ok?{ok:!0,action:"installed",platform:r,targetPlatform:r,installed:!0,repairable:!1,targetDir:u,helperDir:f.helperDir,helperPath:f.helperPath,helperVersion:f.version,runtimeVersion:f.version,protocolVersion:f.manifest.protocolVersion,minCliVersion:p.manifest.minCliVersion,sha256:p.manifest.sha256,packageManifestPath:p.manifestPath,packageKind:p.manifest.packageKind,installTarget:p.manifest.installTarget,signature:p.manifest.signature,message:`Installed Shennian Helper runtime to ${u}`}:{ok:!1,platform:r,targetPlatform:r,installed:!1,repairable:!0,reasonCode:p.reasonCode,message:`Installed Helper runtime package manifest could not be verified: ${p.message}`,repairSuggestion:c(p.reasonCode),checkedSources:s}}async function P(e={}){const r=new F({lockPath:B(e),owner:"helper-runtime-install",defaultWaitMs:0});try{return await r.run("helper-runtime-install",()=>G(e))}catch(o){if(z(o)){const a=S(e.platform)??void 0;return{ok:!1,platform:a,targetPlatform:a,installed:!1,repairable:!0,reasonCode:"wechat_automation_busy",message:o instanceof Error?o.message:String(o),repairSuggestion:"Wait for the current WeChat automation run to finish, then retry Helper install or repair."}}throw o}}function B(e){const r=e.env?.SHENNIAN_HOME?.trim()||process.env.SHENNIAN_HOME?.trim(),o=r?t.resolve(r):t.join(e.homedir??C.homedir(),".shennian");return t.join(o,"runtime","wechat-automation.lock")}function z(e){return e instanceof Error?e.message.includes("wechat_automation_busy"):String(e).includes("wechat_automation_busy")}async function G(e={}){if(e.preferOfficialDownload&&!e.source&&e.officialDownload!==!1)return await O(e);const r=I(e);return r.ok||e.source||e.officialDownload===!1||!J(r.reasonCode)?r.ok?{...r,source:r.source??"local"}:r:await O(e,r)}async function O(e,r){const o=S(e.platform);if(!o)return r??{ok:!1,repairable:!1,reasonCode:"unsupported_platform",message:"Shennian Helper runtime is only available on macOS and Windows.",repairSuggestion:c("unsupported_platform")};const a=e.officialDownload===!1||e.officialDownload==null?{}:e.officialDownload,n=await W({...a,platform:o,env:e.env??process.env});if(!n.ok)return{ok:!1,platform:o,targetPlatform:o,installed:!1,repairable:!0,reasonCode:n.reasonCode,message:n.message,repairSuggestion:c(n.reasonCode),checkedSources:r?.checkedSources,officialDownload:{manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl}};try{const i=I({...e,source:n.sourceDir,platform:o,force:e.force??e.preferOfficialDownload??!1});return i.ok?{...i,source:"official-download",officialDownload:{channel:n.channel,manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl,artifactSha256:n.artifactSha256,artifactSizeBytes:n.artifactSizeBytes,arch:n.arch,helperVersion:n.helperVersion,protocolVersion:n.protocolVersion,minCliVersion:n.minCliVersion}}:{...i,reasonCode:i.reasonCode==="helper_runtime_source_missing"?"helper_runtime_artifact_invalid":i.reasonCode,message:i.reasonCode==="helper_runtime_source_missing"?"Official Helper runtime artifact did not contain an installable runtime package.":i.message,repairSuggestion:c(i.reasonCode==="helper_runtime_source_missing"?"helper_runtime_artifact_invalid":i.reasonCode),officialDownload:{manifestUrl:n.manifestUrl,artifactUrl:n.artifactUrl}}}finally{n.cleanup()}}function J(e){return e==="helper_runtime_source_missing"||e==="helper_runtime_package_manifest_missing"||e==="helper_runtime_package_manifest_invalid"}function S(e){const r=e??process.platform;return r==="darwin"||r==="win32"?r:null}function A(e){return e.packageManifest.platform!==e.platform?{ok:!1,reasonCode:"helper_runtime_platform_mismatch",message:`Helper runtime package platform ${e.packageManifest.platform} does not match ${e.platform}.`,repairable:!0}:e.helperVersion&&e.packageManifest.helperVersion!==e.helperVersion?{ok:!1,reasonCode:"helper_runtime_version_mismatch",message:`Helper runtime package version ${e.packageManifest.helperVersion} does not match installed helper ${e.helperVersion}.`,repairable:!0}:e.protocolVersion&&e.packageManifest.protocolVersion!==e.protocolVersion?{ok:!1,reasonCode:"helper_runtime_protocol_mismatch",message:`Helper runtime package protocol ${e.packageManifest.protocolVersion} does not match installed helper protocol ${e.protocolVersion}.`,repairable:!0}:K(e.currentCliVersion,e.packageManifest.minCliVersion)!=="none"?{ok:!1,reasonCode:"helper_runtime_cli_too_old",message:`Shennian CLI ${e.currentCliVersion} is older than required ${e.packageManifest.minCliVersion}.`,repairable:!1}:{ok:!0}}function q(e){return e!=="unsupported_platform"&&e!=="helper_runtime_cli_too_old"}function c(e,r){if(e==="unsupported_platform")return"Use Shennian Helper runtime on macOS or Windows.";if(e==="unsupported_runtime_component")return"Use `shennian runtime install helper` or `shennian runtime repair helper`.";if(e==="helper_runtime_cli_too_old")return`Upgrade Shennian CLI${r?` to ${r} or newer`:""}, then retry.`;if(e==="helper_runtime_target_unavailable")return"Set the current user home/LOCALAPPDATA correctly, then retry.";if(e==="helper_runtime_required")return"Open Shennian Desktop or use the \u4F7F\u7528\u5FAE\u4FE1 page to install Helper.";if(e==="helper_runtime_source_missing")return"Open Shennian Desktop, retry from the \u4F7F\u7528\u5FAE\u4FE1 page, or pass `--source <path>`.";if(e==="helper_runtime_manifest_unavailable")return"Check network access to Shennian official downloads, then retry from the \u4F7F\u7528\u5FAE\u4FE1 page.";if(e==="helper_runtime_artifact_unavailable")return"Upgrade Shennian CLI or wait for this platform Helper runtime to be published.";if(e==="helper_runtime_download_failed")return"Check network access to Shennian official downloads, then retry.";if(e==="helper_runtime_artifact_integrity_mismatch")return"Retry the official Helper runtime download; the downloaded package did not match the published hash.";if(e==="helper_runtime_artifact_invalid")return"Retry after Shennian republishes a valid Helper runtime package for this platform.";if(e==="helper_runtime_package_manifest_missing"||e==="helper_runtime_package_manifest_invalid")return"Reinstall or repair the official Shennian Helper runtime package.";if(e==="helper_runtime_platform_mismatch")return"Install the Helper runtime package for this platform.";if(e==="helper_runtime_version_mismatch"||e==="helper_runtime_protocol_mismatch")return"Run `shennian runtime repair helper` with the matching official Helper runtime package.";if(e==="manifest_missing"||e==="helper_missing"||e==="integrity_mismatch"||e==="helper_not_executable")return"Run `shennian runtime repair helper` or reinstall Shennian Desktop."}function D(e){return{ok:!1,repairable:!1,reasonCode:"unsupported_runtime_component",message:`Unsupported runtime component: ${e}. Supported component: helper.`,repairSuggestion:c("unsupported_runtime_component")}}function X(e){return{existsSync:e?.existsSync??m.existsSync,lstatSync:e?.lstatSync??m.lstatSync,readFileSync:e?.readFileSync??m.readFileSync,realpathSync:e?.realpathSync??m.realpathSync,mkdirSync:e?.mkdirSync??m.mkdirSync,rmSync:e?.rmSync??m.rmSync,cpSync:e?.cpSync??m.cpSync,renameSync:e?.renameSync??m.renameSync,chmodSync:e?.chmodSync??m.chmodSync,homedir:e?.homedir??C.homedir,stopMacHelperProcesses:e?.stopMacHelperProcesses??oe,stopWindowsHelperProcesses:e?.stopWindowsHelperProcesses??ie}}function Q(e){const r=t.resolve(e.candidate);return!e.io.existsSync(r)||ae(r,e.io)?null:e.platform==="darwin"?Y(r,e.io):Z(r,e.io)}function Y(e,r){const o=e.endsWith(".app")?e:t.join(e,"Shennian Helper.app");if(r.existsSync(t.join(o,"Contents","Resources","wechat-channel","macos","manifest.json")))return{sourceDir:o,packageKind:"macos-app",packageManifestPath:T(r,[t.join(o,"Contents","Resources","helper-runtime-package.json"),t.join(e,h)]),packageManifestPathInTarget:n=>t.join(n,"Contents","Resources",h),manifestDirInTarget:n=>t.join(n,"Contents","Resources","wechat-channel","macos")};const a=r.existsSync(t.join(e,"manifest.json"))?e:t.join(e,"wechat-channel","macos");return r.existsSync(t.join(a,"manifest.json"))?{sourceDir:a,packageKind:"asset-dir",packageManifestPath:t.join(a,"helper-runtime-package.json"),packageManifestPathInTarget:n=>t.join(n,h),manifestDirInTarget:n=>n}:null}function Z(e,r){const o=t.basename(e).toLowerCase()==="shennian helper"?e:t.join(e,"Shennian Helper");if(r.existsSync(t.join(o,"resources","wechat-channel","windows","manifest.json")))return{sourceDir:o,packageKind:"windows-runtime",packageManifestPath:T(r,[t.join(o,"resources",h),t.join(e,h)]),packageManifestPathInTarget:n=>t.join(n,"resources",h),manifestDirInTarget:n=>t.join(n,"resources","wechat-channel","windows")};const a=r.existsSync(t.join(e,"manifest.json"))?e:t.join(e,"wechat-channel","windows");return r.existsSync(t.join(a,"manifest.json"))?{sourceDir:a,packageKind:"asset-dir",packageManifestPath:t.join(a,"helper-runtime-package.json"),packageManifestPathInTarget:n=>t.join(n,h),manifestDirInTarget:n=>n}:null}function ee(e){const r=b(e);if(!r)return null;if(e.platform==="darwin")return e.packageKind==="macos-app"?t.join(r,"Shennian Helper.app"):t.join(r,"wechat-channel","macos");if(e.packageKind==="windows-runtime"){const o=e.env.LOCALAPPDATA||(e.homedir?t.join(e.homedir,"AppData","Local"):"");return o?t.join(o,"Programs","Shennian Helper"):null}return t.join(r,"wechat-channel","windows")}function re(e,r){const o=t.resolve(r);if(e==="darwin"){const n=`${t.sep}Contents${t.sep}Resources${t.sep}wechat-channel${t.sep}macos`;return o.endsWith(n)?o.slice(0,-n.length):o}const a=`${t.sep}resources${t.sep}wechat-channel${t.sep}windows`;return o.endsWith(a)?o.slice(0,-a.length):o}function ne(e){const r=t.resolve(e.sourceDir),o=t.resolve(e.targetDir);if(r===o)return;const a=E(r,e.io),n=E(o,e.io);if(a&&n&&a===n)return;const i=`${o}.tmp-${process.pid}-${Date.now()}`;e.io.rmSync(i,{recursive:!0,force:!0}),e.io.mkdirSync(t.dirname(o),{recursive:!0}),e.io.cpSync(r,i,{recursive:!0}),e.io.rmSync(o,{recursive:!0,force:!0}),e.io.renameSync(i,o)}function x(e){e.io.existsSync(e.targetDir)&&(e.platform==="darwin"&&e.io.stopMacHelperProcesses(e.targetDir),e.platform==="win32"&&e.io.stopWindowsHelperProcesses())}function ae(e,r){try{return r.lstatSync(e).isSymbolicLink()}catch{return!1}}function E(e,r){try{return r.realpathSync(e)}catch{return null}}function oe(e){if(process.platform!=="darwin")return;const r=t.join(t.resolve(e),"Contents","MacOS","Shennian Helper"),o=H("ps",["-axo","pid=,command="],{encoding:"utf8"});if(o.status!==0)return;const a=o.stdout.split(/\r?\n/u).map(n=>{const i=/^\s*(\d+)\s+(.+)$/u.exec(n);if(!i)return null;const s=Number(i[1]),l=i[2];return Number.isInteger(s)&&l.includes(r)?s:null}).filter(n=>!!(n&&n!==process.pid));for(const n of a)try{process.kill(n,"SIGTERM")}catch{}$(a,1e3);for(const n of a)if(U(n))try{process.kill(n,"SIGKILL")}catch{}$(a,500)}function $(e,r){const o=Date.now()+r;for(;Date.now()<o&&e.some(U);)te(50)}function te(e){Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,e)}function U(e){try{return process.kill(e,0),!0}catch{return!1}}function ie(){if(process.platform!=="win32")return;const e=H("taskkill",["/IM","shennian-wechat-channel-helper.exe","/T","/F"],{stdio:"ignore",windowsHide:!0});if(e.status!==0&&e.status!==128)throw new Error(`taskkill shennian-wechat-channel-helper.exe exited ${e.status}`)}function se(e){const r=t.resolve(e.sourceManifestPath),o=t.resolve(e.targetManifestPath);!e.io.existsSync(r)||r===o||(e.io.mkdirSync(t.dirname(o),{recursive:!0}),e.io.cpSync(r,o))}function T(e,r){return r.find(o=>e.existsSync(o))??r[0]}function le(e,r,o){if(e==="darwin")try{const a=m.statSync(r);(a.mode&73)===0&&o.chmodSync(r,a.mode|493)}catch{}}function k(e){const r=e.homedir||(e.platform==="win32"?e.env.USERPROFILE:e.env.HOME),o=[],a=n=>{if(!n)return;const i=t.resolve(n);o.includes(i)||o.push(i)};if(a(e.env.SHENNIAN_HELPER_PACKAGE_DIR),a(e.env[N]),a(e.env[L]),e.platform==="darwin")r&&(a(t.join(r,"Applications","Shennian.app","Contents","Resources")),a(t.join(r,"Applications","Shennian Helper.app"))),a(t.join("/Applications","Shennian.app","Contents","Resources")),a(t.join("/Applications","Shennian Helper.app"));else{const n=e.env.LOCALAPPDATA||(r?t.join(r,"AppData","Local"):""),i=e.env.ProgramFiles||e.env.PROGRAMFILES,s=e.env["ProgramFiles(x86)"]||e.env["PROGRAMFILES(X86)"];n&&(a(t.join(n,"Programs","Shennian","resources")),a(t.join(n,"Programs","Shennian Helper"))),i&&(a(t.join(i,"Shennian","resources")),a(t.join(i,"Shennian Helper"))),s&&(a(t.join(s,"Shennian","resources")),a(t.join(s,"Shennian Helper")))}return a(t.resolve(process.cwd(),"packages/helper-runtime/dist",e.platform==="darwin"?"macos":"windows")),a(t.resolve(process.cwd(),"packages/helper-runtime/wechat-channel",e.platform==="darwin"?"macos":"windows")),o}function _(e,r){if(r){console.log(JSON.stringify(e,null,2));return}if(e.ok){console.log(V.green(`\u2713 ${e.message}`)),"helperVersion"in e&&console.log(`version=${e.helperVersion} protocol=${e.protocolVersion}`),"helperPath"in e&&console.log(e.helperPath);return}console.error(V.red(`\u2717 ${e.reasonCode}`)),console.error(e.message)}export{M as getHelperRuntimeStatus,I as installHelperRuntime,P as installHelperRuntimeWithOfficialDownload,ke as registerRuntimeCommand};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{readExternalAttachment as g}from"../external-attachments.js";import{runWeChatDoctor as C}from"./doctor.js";import{runWeChatReadLatest as k,runWeChatSend as v}from"./operations.js";import{printReadLatestResult as y,printToolError as c,printToolResult as j}from"./output.js";import{clampPositiveInteger as u}from"./utils.js";const m=5*6e4,l=10*6e4;function _(e){const o=e.command("wechat").description("Use WeChat through Shennian local runtime");o.option("--conversation <name>","WeChat conversation/group name"),o.command("doctor").description("Check local Shennian, pairing, entitlement, credits, and WeChat runtime readiness").option("--json","Output JSON",!1).action(async r=>{const t=await C();if(r.json)console.log(JSON.stringify(t,null,2));else for(const a of t.checks){const n=a.ok?"\u2713":a.status==="warning"?"!":"\u2717";console.log(`${n} ${a.id}: ${a.message}`)}t.ok||(process.exitCode=1)}),o.command("write").aliases(["send"]).description("Write a message to a local WeChat conversation through Shennian").argument("[text...]","Message text").option("--conversation <name>","WeChat conversation/group name").option("--text <text>","Message text").option("--file <path>","File attachment path").option("--image <path>","Image attachment path").option("--video <path>","Video attachment path").option("--session-id <id>","Bind to an existing Shennian chat/session; omit for direct local WeChat tool mode").option("--work-dir <path>","Local tool work dir; defaults under ~/.shennian/wechat-cli").option("--idempotency-key <key>","Idempotency key").option("--dry-run","Validate the request and output the planned write without sending",!1).option("--trace-id <id>","Trace id included in JSON output").option("--timeout <ms>",`Manager IPC request timeout in milliseconds. Default: ${m}`).option("--transport <mode>","Execution transport: auto, daemon, or direct","auto").option("--format <format>","Output format: json or text","text").option("--json","Output JSON",!1).action(async(r,t,a)=>{let n;try{n=h(a,t.conversation);const i=t.text??r.join(" "),s=x(t),w=await v({conversation:n,text:i,attachment:s,sessionId:t.sessionId,workDir:t.workDir,idempotencyKey:t.idempotencyKey,dryRun:t.dryRun,traceId:t.traceId,timeoutMs:f(t.timeout),transport:p(t.transport)});j(w,t.json||t.format==="json")}catch(i){c("write",n||t.conversation,i,t.json||t.format==="json")}}),o.command("read").aliases(["read-latest","read_latest","latest"]).description("Read recent messages from a local WeChat conversation through Shennian").argument("[count]","Number of latest messages","10").option("--conversation <name>","WeChat conversation/group name").option("--limit <n>","Number of latest messages").option("--format <format>","Output format: markdown or json","markdown").option("--download <mode>","Attachment download mode: auto or never","auto").option("--trace-id <id>","Trace id included in JSON output").option("--timeout <ms>",`Manager IPC request timeout in milliseconds. Default: ${m}`).option("--session-id <id>","Bind to an existing Shennian chat/session; omit for direct local WeChat tool mode").option("--work-dir <path>","Local tool work dir; defaults under ~/.shennian/wechat-cli").option("--transport <mode>","Execution transport: auto, daemon, or direct","auto").option("--json","Output JSON",!1).action(async(r,t,a)=>{let n,i="markdown";try{n=h(a,t.conversation),i=S(t.json?"json":t.format);const s=await k({conversation:n,limit:u(t.limit??r,10),download:W(t.download),traceId:t.traceId,timeoutMs:f(t.timeout),sessionId:t.sessionId,workDir:t.workDir,transport:p(t.transport)});y(s,i)}catch(s){c("read",n||t.conversation,s,t.json||i==="json")}})}function h(e,o){const d=e.parent?.opts()??{},r=o||d.conversation||"";if(!r.trim())throw new Error("--conversation is required");return r}function x(e){const o=[e.file?{kind:"file",path:e.file}:null,e.image?{kind:"image",path:e.image}:null,e.video?{kind:"video",path:e.video}:null].filter(d=>!!d);if(o.length>1)throw new Error("Pass only one of --file, --image, or --video");if(o.length!==0)return g(o[0].path,o[0].kind)}function S(e){const o=String(e||"markdown").trim().toLowerCase();if(o==="json")return"json";if(o==="markdown"||o==="md"||o==="text")return"markdown";throw new Error(`Unsupported --format: ${e}. Use markdown or json.`)}function W(e){const o=String(e||"auto").trim().toLowerCase();if(o==="auto"||o==="never")return o;throw new Error(`Unsupported --download: ${e}. Use auto or never.`)}function p(e){const o=String(e||"auto").trim().toLowerCase();if(o==="auto"||o==="daemon"||o==="direct")return o;throw new Error(`Unsupported --transport: ${e}. Use auto, daemon, or direct.`)}function f(e){return e?Math.min(u(e,l),l):m}export{_ as registerWeChatCommand,f as resolveWeChatCommandTimeout};
|
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
import type { ExternalMessageEvent } from '../../channels/base.js';
|
|
2
|
-
import { type WeChatReadLatestOptions, type WeChatSendOptions, type WeChatSendResult, type WeChatToolBinding } from './types.js';
|
|
3
|
-
export declare function sendDirectWeChatMessageOnce(binding: WeChatToolBinding, options: WeChatSendOptions): Promise<{
|
|
4
|
-
pending?: boolean;
|
|
5
|
-
sendStatus?: WeChatSendResult['sendStatus'];
|
|
6
|
-
outDir?: string;
|
|
7
|
-
helperTracePath?: string | null;
|
|
8
|
-
}>;
|
|
9
|
-
export declare function readDirectWeChatLatestOnce(binding: WeChatToolBinding, options: WeChatReadLatestOptions): Promise<{
|
|
10
|
-
messages: ExternalMessageEvent[];
|
|
11
|
-
outDir: string;
|
|
12
|
-
helperTracePath: string | null;
|
|
13
|
-
activityGuardPath?: string | null;
|
|
14
|
-
}>;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import p from"node:fs";import f from"node:path";import{observedMessageToExternalEvent as P,weChatChannelBindingId as g}from"../../channels/wechat-rpa/product-channel.js";import{loadConfig as v}from"../../config/index.js";import{runWeChatChannelActionSmoke as w}from"../../devtools/wechat-channel-action-smoke.js";import{WeChatToolOperationError as k}from"./types.js";import{currentWeChatPlatform as E,isPendingSendStatus as A,isRecord as y,normalizeSendStatus as S,safePathSegment as T}from"./utils.js";async function H(e,t){const r=N(t.attachment),o=_(e,t,{kind:"send",steps:["open-read",r],text:t.text,attachment:t.attachment}),s=await w(o),a=s.steps.find(c=>c.step===r);if(!s.ok||!a?.ok){if(j(a))return{pending:!1,sendStatus:"sent_unconfirmed",outDir:s.outDir,helperTracePath:s.helperTracePath};const c=s.steps.find(h=>!h.ok&&!h.skipped),i=a?.reasonCode==="open_read_required"?c??a:a??c,u=i?.reasonCode||"wechat_direct_send_failed",m=i?.errorSummary||u;throw new k({reasonCode:u,message:m,outDir:s.outDir,helperTracePath:s.helperTracePath,traceId:t.traceId})}const n=S(a.details?.sendStatus)??"sent_unconfirmed";return{pending:A(n),sendStatus:n,outDir:s.outDir,helperTracePath:s.helperTracePath}}async function J(e,t){const r=[],o=t.download!=="never",s=o?"download-visible-media":"structure-window",a=_(e,t,{kind:"read",steps:[s],allowEmptyMedia:o,activityGuardEvents:r}),n=await w(a),c=r.length>0?x(n.outDir,r):null,i=n.steps.find(d=>d.step===s),u=f.join(n.outDir,o?"download-visible-messages.json":"structure-window-messages.json"),m=O(u),h=o&&m.length>0&&(i?.reasonCode==="media_original_pending_or_metadata_only"||i?.reasonCode==="only_preview_media_downloaded");if(!n.ok&&i?.reasonCode!=="no_observed_messages"&&!h){const d=i?.reasonCode||n.steps.find(l=>!l.ok&&!l.skipped)?.reasonCode||"wechat_direct_read_failed",I=i?.errorSummary||n.steps.find(l=>!l.ok&&!l.skipped)?.errorSummary||d;throw new k({reasonCode:d,message:I,outDir:n.outDir,helperTracePath:n.helperTracePath,activityGuardPath:c,traceId:t.traceId})}const C=M(e,t),D=W(e);return{messages:m.map(d=>P(C,D,d)).filter(d=>d!=null),outDir:n.outDir,helperTracePath:n.helperTracePath,activityGuardPath:c}}function N(e){return e?e.kind==="image"?"send-image":e.kind==="video"?"send-video":"send-file":"send-text"}function _(e,t,r){const o=t.traceId||`wechat-cli-${r.kind}-${Date.now().toString(36)}`,s=f.join(e.workDir,"runs",T(o)),a=r.attachment;return{conversation:e.conversationName,mode:"custom",steps:r.steps,outDir:s,workDir:e.workDir,traceId:o,runtimeId:e.channelId,machineId:process.env.SHENNIAN_MACHINE_ID||v().machineId||"local",sessionId:e.sessionId,serverUrl:v().serverUrl,platform:E(),text:r.text,...a?.localPath&&a.kind==="image"?{imagePath:a.localPath}:{},...a?.localPath&&a.kind==="video"?{videoPath:a.localPath}:{},...a?.localPath&&a.kind!=="image"&&a.kind!=="video"?{filePath:a.localPath}:{},allowEmptyMedia:r.allowEmptyMedia,...r.kind==="read"?{activityGuard:{useAutomationLease:!0,onEvent:r.activityGuardEvents?n=>r.activityGuardEvents?.push(n):void 0}}:{},skipRuntimeUpsert:!0,requireServer:!1}}function x(e,t){const r=f.join(e,"activity-guard.json");return p.mkdirSync(f.dirname(r),{recursive:!0}),p.writeFileSync(r,`${JSON.stringify({schema:"wechat-direct-read-activity-guard/v1",events:t},null,2)}
|
|
2
|
-
`,"utf8"),r}function M(e,t){return{id:e.channelId,type:"wechat-rpa",name:`WeChat ${e.conversationName}`,sessionId:e.sessionId,managerSessionId:e.sessionId,workDir:e.workDir,enabled:!0,secretRef:`wechat-cli:${e.channelId}`}}function W(e){return{bindingId:g(e.channelId,e.conversationName),sessionId:e.sessionId,conversationDisplayName:e.conversationName,enabled:!0,allowReply:!0,downloadMedia:!0}}function O(e){try{const t=JSON.parse(p.readFileSync(e,"utf-8"));return Array.isArray(t)?t.filter(y):[]}catch{return[]}}function j(e){if(e?.reasonCode!=="sent_text_not_observed")return!1;const t=y(e.details)?e.details:{},r=t.sendAccepted===!0,o=S(t.sendStatus);return r&&(o==="sent_unconfirmed"||o==="sent"||o==="ok")}export{J as readDirectWeChatLatestOnce,H as sendDirectWeChatMessageOnce};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{loadConfig as k}from"../../config/index.js";import{SERVERS as g}from"../../region.js";import{isRecord as l,stringValue as y}from"./utils.js";async function U(e={}){const r=k(),t=_(e.serverUrl||r.serverUrl||g.cn.url),c=e.machineToken||r.machineToken,o=e.machineId||r.machineId,m=e.fetchImpl||fetch,n=[s("cli_installed","Shennian CLI is installed."),c?s("machine_paired","Machine token is configured."):h("machine_paired","machine_not_paired","Machine is not paired. Run shennian pair first.")];if(!c)return u({checks:n,serverUrl:t,machineId:o});try{const a=await m(`${t}/api/channels/wechat/runtime-policy`,{headers:{authorization:`Bearer ${c}`}}),i=await a.json().catch(()=>null);if(!a.ok||i?.ok===!1){const d=y(i?.reasonCode)||a.statusText||"request_failed";return n.push(h("server_policy",d,`WeChat runtime policy is blocked: ${d}`)),u({checks:n,serverUrl:t,machineId:o})}const f=l(i?.usagePolicy)?i.usagePolicy:{};n.push(s("server_policy","Server WeChat policy is reachable.")),n.push(s("entitlement","Account has Pro / Team external channel entitlement.")),n.push(s("credits",f.billingMode==="credits"?"Credit billing is enabled; balance is checked by server calls.":"Credits are not metered in current billing mode."));const p=l(i?.runtime)&&l(i.runtime.current)?i.runtime.current:null;n.push(p?s("runtime_registered","Local WeChat runtime is registered on the server."):v("runtime_registered","runtime_not_registered","Local WeChat runtime is not registered yet; open Shennian Desktop/daemon and enable Use WeChat."))}catch(a){n.push(h("server_policy","network_unavailable",a instanceof Error?a.message:"Unable to reach Shennian server."))}return u({checks:n,serverUrl:t,machineId:o})}function u(e){return{ok:e.checks.every(r=>r.ok||r.status==="warning"),checks:e.checks,serverUrl:e.serverUrl,machineId:e.machineId}}function s(e,r){return{id:e,ok:!0,status:"ready",message:r}}function v(e,r,t){return{id:e,ok:!1,status:"warning",reasonCode:r,message:t}}function h(e,r,t){return{id:e,ok:!1,status:"blocked",reasonCode:r,message:t}}function _(e){return e.replace(/\/+$/,"")}export{U as runWeChatDoctor};
|
|
@@ -1,9 +0,0 @@
|
|
|
1
|
-
import { type IpcContext, type IpcResponse, type WeChatManagerIpcResolution, type WeChatToolBinding, type WeChatToolOptions } from './types.js';
|
|
2
|
-
export declare function loadManagerIpcFromRuntimeFile(): IpcContext;
|
|
3
|
-
export declare function tryLoadManagerIpcFromRuntimeFile(): IpcContext | null;
|
|
4
|
-
export declare function resolveWeChatManagerIpc(options: WeChatToolOptions): WeChatManagerIpcResolution | null;
|
|
5
|
-
export declare function shouldFallbackManagerToolToDirect(options: WeChatToolOptions, error: unknown): boolean;
|
|
6
|
-
export declare function ensureWeChatToolChannel(ctx: IpcContext, binding: WeChatToolBinding, options: WeChatToolOptions): Promise<IpcResponse>;
|
|
7
|
-
export declare function ipc(ctx: IpcContext, pathname: string, body: Record<string, unknown>, fetchImpl?: typeof fetch, timeoutMs?: number): Promise<IpcResponse>;
|
|
8
|
-
export declare function buildWeChatToolBinding(options: WeChatToolOptions): WeChatToolBinding;
|
|
9
|
-
export declare function trySyncWeChatToolChannel(ctx: IpcContext, binding: WeChatToolBinding, options: WeChatToolOptions): Promise<IpcResponse | null>;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import v from"node:fs";import S from"node:http";import P from"node:https";import k from"node:path";import{resolveShennianPath as g}from"../../config/index.js";import{weChatChannelConversationId as x}from"../../channels/wechat-rpa/product-channel.js";import{WeChatToolOperationError as w}from"./types.js";import{clampPositiveInteger as I,isAbortError as y,processExists as M,safePathSegment as T,stableId as E,stringValue as u}from"./utils.js";function p(){const r=g("runtime","manager-ipc.json");let e;try{e=JSON.parse(v.readFileSync(r,"utf-8"))}catch{throw new Error("Manager IPC is not available. Open Shennian Desktop or run `shennian start` first.")}const t=Number(e.pid);if(Number.isInteger(t)&&t>0&&!M(t))throw new Error(`Manager IPC runtime file is stale for PID ${t}. Restart Shennian Desktop or run \`shennian restart\`.`);const a=typeof e.url=="string"?e.url.replace(/\/+$/,""):"",s=typeof e.token=="string"?e.token:"";if(!a||!s)throw new Error(`Manager IPC runtime file is incomplete: ${r}`);return{url:a,token:s}}function $(){try{return p()}catch{return null}}function W(r){if(r.directRuntime)return null;const e=r.transport??"auto";if(e==="direct")return null;if(r.ipc)return{ctx:r.ipc,mode:"session"};if(r.sessionId?.trim())return{ctx:p(),mode:"session"};if(e==="daemon")return{ctx:p(),mode:"tool"};if(e==="auto"){const t=$();if(t)return{ctx:t,mode:"tool"}}return null}function _(r,e){if((r.transport??"auto")!=="auto"||r.sessionId?.trim()||r.ipc)return!1;const a=e instanceof Error?e.message:String(e||"");return/Unknown manager IPC path:\s*\/wechat-rpa\/tool\//i.test(a)||/Manager IPC is not available/i.test(a)||/Manager IPC runtime file is stale/i.test(a)||/Manager IPC runtime file is incomplete/i.test(a)}async function A(r,e,t){return C(r,"/wechat-rpa/channel/upsert",{managerSessionId:e.sessionId,id:e.channelId,name:`WeChat ${e.conversationName}`,workDir:e.workDir,enabled:!0,groups:[{name:e.conversationName}],canReply:!0,source:t.source||"wechat-channel",recentLimit:I(t.recentLimit,20),pollIntervalMs:I(t.pollIntervalMs,3e4),forceForeground:!0,downloadAttachments:t.download!=="never",privacyConsentAccepted:!0},t.fetchImpl,t.timeoutMs)}async function C(r,e,t,a=fetch,s){const m=String(t.managerSessionId||"");if(!m)throw new Error("managerSessionId is required");let o,c=0,f="";try{if(a===fetch){const n=await D(r,e,t,s);o=n.data,c=n.status,f=n.statusText}else{const n=s?new AbortController:null,i=n?setTimeout(()=>n.abort(),s):null;try{const l=await a(`${r.url}${e}`,{method:"POST",headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json","x-shennian-manager-session-id":m},body:JSON.stringify(t),signal:n?.signal});c=l.status,f=l.statusText,o=await l.json().catch(()=>({ok:!1,error:l.statusText}))}finally{i&&clearTimeout(i)}}}catch(n){throw new w({reasonCode:y(n)?"manager_ipc_timeout":"manager_ipc_network_failed",message:n instanceof Error?n.message:String(n||"manager ipc request failed"),traceId:u(t.traceId)||void 0})}if(c<200||c>=300||!o.ok){const n=u(o.reasonCode);throw n?new w({reasonCode:n,message:u(o.error)||n,outDir:u(o.outDir)||void 0,helperTracePath:u(o.helperTracePath)||null,activityGuardPath:u(o.activityGuardPath)||null,traceId:u(o.traceId)||void 0}):new Error(o.error||`Manager IPC failed: ${c||f}`)}return o}function D(r,e,t,a){const s=JSON.stringify(t),m=new URL(e,`${r.url}/`),o=m.protocol==="https:"?P:S;return new Promise((c,f)=>{const n=o.request(m,{method:"POST",headers:{authorization:`Bearer ${r.token}`,"content-type":"application/json","content-length":Buffer.byteLength(s),"x-shennian-manager-session-id":String(t.managerSessionId||"")},timeout:a},i=>{const l=[];i.on("data",h=>l.push(Buffer.from(h))),i.on("end",()=>{const h=Buffer.concat(l).toString("utf8");let d;try{d=h?JSON.parse(h):{ok:!1,error:i.statusMessage||"empty response"}}catch{d={ok:!1,error:i.statusMessage||"invalid json response"}}c({status:i.statusCode||0,statusText:i.statusMessage||"",data:d})})});n.on("timeout",()=>{n.destroy(Object.assign(new Error("Manager IPC request timed out"),{name:"AbortError"}))}),n.on("error",f),n.end(s)})}function L(r){const e=r.conversation.trim();if(!e)throw new Error("--conversation is required");const t=E("wechat-cli-conversation",e),a=r.sessionId?.trim()||`wechat-cli-${t.slice(-24)}`,s=`wechat-rpa:${a}`;return{sessionId:a,channelId:s,conversationId:x(e),conversationName:e,workDir:k.resolve(r.workDir||g("wechat-cli",T(e)))}}async function J(r,e,t){try{return await C(r,"/wechat-rpa/channel/sync",{managerSessionId:e.sessionId},t.fetchImpl,t.timeoutMs)}catch(a){if(y(a))return null;throw a}}export{L as buildWeChatToolBinding,A as ensureWeChatToolChannel,C as ipc,p as loadManagerIpcFromRuntimeFile,W as resolveWeChatManagerIpc,_ as shouldFallbackManagerToolToDirect,$ as tryLoadManagerIpcFromRuntimeFile,J as trySyncWeChatToolChannel};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import type { WeChatReadLatestOptions, WeChatReadLatestResult, WeChatSendOptions, WeChatSendResult } from './types.js';
|
|
2
|
-
export declare function runWeChatSend(options: WeChatSendOptions): Promise<WeChatSendResult>;
|
|
3
|
-
export declare function runWeChatReadLatest(options: WeChatReadLatestOptions): Promise<WeChatReadLatestResult>;
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{readDirectWeChatLatestOnce as P,sendDirectWeChatMessageOnce as R}from"./direct.js";import{buildWeChatToolBinding as y,ensureWeChatToolChannel as C,ipc as g,resolveWeChatManagerIpc as N,shouldFallbackManagerToolToDirect as p,trySyncWeChatToolChannel as S}from"./ipc.js";import{clampPositiveInteger as k,isExternalMessageEvent as D,isPendingSendStatus as v,isRecord as f,normalizeSendStatus as T,stableId as W,stringValue as u}from"./utils.js";async function M(t){const r=t.text.trim();if(!r&&!t.attachment)throw new Error("Message text or attachment is required");const e=y(t),n=t.attachment?A(t.attachment):void 0;if(t.dryRun)return{ok:!0,operation:"write",conversation:e.conversationName,conversationName:e.conversationName,conversationId:e.conversationId,sessionId:e.sessionId,channelId:e.channelId,traceId:t.traceId,outDir:e.workDir,helperTracePath:null,sendStatus:"dry_run",pending:!1,attachment:n,attachments:n?[n]:[],dryRun:!0,reasonCode:null,message:"Dry run completed. No WeChat message was sent."};const d=N(t);if(!d){const s=t.directRuntime?await t.directRuntime.send(e,t):await R(e,t);return{ok:!0,operation:"write",conversation:e.conversationName,conversationName:e.conversationName,conversationId:e.conversationId,sessionId:e.sessionId,channelId:e.channelId,traceId:t.traceId,outDir:s.outDir??e.workDir,helperTracePath:s.helperTracePath??null,sendStatus:s.sendStatus??(s.pending?"pending":"sent"),pending:s.pending===!0,attachment:n,attachments:n?[n]:[],reasonCode:null,message:s.pending?"WeChat message is queued for local sending; do not resend.":"WeChat message sent; do not resend."}}if(d.mode==="tool"){let s;try{s=await g(d.ctx,"/wechat-rpa/tool/send",{managerSessionId:e.sessionId,binding:e,text:r,attachment:t.attachment,traceId:t.traceId,timeoutMs:t.timeoutMs},t.fetchImpl,t.timeoutMs)}catch(h){if(p(t,h))return M({...t,transport:"direct"});throw h}const c=T(s.sendStatus)??(s.pending===!0?"pending":"sent");return{ok:!0,operation:"write",conversation:e.conversationName,conversationName:e.conversationName,conversationId:e.conversationId,sessionId:e.sessionId,channelId:e.channelId,traceId:t.traceId,outDir:u(s.outDir)||e.workDir,helperTracePath:u(s.helperTracePath)||null,sendStatus:c,pending:v(c),attachment:n,attachments:n?[n]:[],reasonCode:null,message:v(c)?"WeChat message is queued for local sending; do not resend.":"WeChat message sent; do not resend."}}const m=d.ctx;await C(m,e,t);const i=t.idempotencyKey||W("wechat-cli-send",`${e.channelId}
|
|
2
|
-
${e.conversationId}
|
|
3
|
-
${r}
|
|
4
|
-
${Date.now()}`),l=await g(m,"/external/reply",{managerSessionId:e.sessionId,channelId:e.channelId,conversationId:e.conversationId,text:r,attachment:t.attachment,idempotencyKey:i},t.fetchImpl,t.timeoutMs),o=await S(m,e,t),a=o?x(o,i,l.pending===!0):l.pending===!0?"queued":"ok";return{ok:!0,operation:"write",conversation:e.conversationName,conversationName:e.conversationName,conversationId:e.conversationId,sessionId:e.sessionId,channelId:e.channelId,traceId:t.traceId,outDir:e.workDir,helperTracePath:null,sendStatus:a,pending:v(a),attachment:n,attachments:n?[n]:[],reasonCode:null,message:o?a==="confirmed_echo"?"WeChat message sent and confirmed; do not resend.":a==="manual_review"?"WeChat message was submitted but needs manual review; do not resend.":"WeChat message submitted to local daemon; do not resend.":"WeChat message submitted to local daemon; confirmation sync timed out, but the message was already submitted \u2014 do not resend."}}async function b(t){const r=k(t.limit,10),e=y(t),n=N(t);if(!n){const a=t.directRuntime?{messages:await t.directRuntime.readLatest(e,{...t,limit:r,recentLimit:t.recentLimit??r}),outDir:e.workDir,helperTracePath:null,activityGuardPath:null}:await P(e,{...t,limit:r,recentLimit:t.recentLimit??r}),s=a.messages.filter(h=>h.conversationId===e.conversationId||h.conversationName===e.conversationName).slice(-r),c=w(s);return{ok:!0,operation:"read",conversation:e.conversationName,conversationName:e.conversationName,conversationId:e.conversationId,sessionId:e.sessionId,channelId:e.channelId,traceId:t.traceId,outDir:a.outDir,helperTracePath:a.helperTracePath,activityGuardPath:a.activityGuardPath??null,messages:s,attachments:c,count:s.length,reasonCode:null,message:`Read ${s.length} WeChat message(s).`}}if(n.mode==="tool"){let a;try{a=await g(n.ctx,"/wechat-rpa/tool/read",{managerSessionId:e.sessionId,binding:e,limit:r,download:t.download,traceId:t.traceId,timeoutMs:t.timeoutMs},t.fetchImpl,t.timeoutMs)}catch(I){if(p(t,I))return b({...t,transport:"direct"});throw I}const c=(Array.isArray(a.messages)?a.messages.filter(D):[]).filter(I=>I.conversationId===e.conversationId||I.conversationName===e.conversationName).slice(-r),h=w(c);return{ok:!0,operation:"read",conversation:e.conversationName,conversationName:e.conversationName,conversationId:e.conversationId,sessionId:e.sessionId,channelId:e.channelId,traceId:t.traceId,outDir:u(a.outDir)||e.workDir,helperTracePath:u(a.helperTracePath)||null,activityGuardPath:u(a.activityGuardPath)||null,messages:c,attachments:h,count:c.length,reasonCode:null,message:`Read ${c.length} WeChat message(s).`}}const d=n.ctx;await C(d,e,{...t,recentLimit:t.recentLimit??r});const m=await g(d,"/wechat-rpa/channel/sync",{managerSessionId:e.sessionId},t.fetchImpl,t.timeoutMs),l=(Array.isArray(m.messages)?m.messages.filter(D):[]).filter(a=>a.conversationId===e.conversationId||a.conversationName===e.conversationName).slice(-r),o=w(l);return{ok:!0,operation:"read",conversation:e.conversationName,conversationName:e.conversationName,conversationId:e.conversationId,sessionId:e.sessionId,channelId:e.channelId,traceId:t.traceId,outDir:e.workDir,helperTracePath:null,activityGuardPath:null,messages:l,attachments:o,count:l.length,reasonCode:null,message:`Read ${l.length} WeChat message(s).`}}function x(t,r,e){const n=f(t.channel)?t.channel:{},m=(Array.isArray(n.wechatRpaPendingReplies)?n.wechatRpaPendingReplies:[]).filter(f).find(a=>u(a.idempotencyKey)===r),i=u(m?.status);if(i==="confirmed_echo"||i==="sent_unconfirmed"||i==="manual_review"||i==="queued")return i;const o=(Array.isArray(n.wechatRpaRecentTaskSummaries)?n.wechatRpaRecentTaskSummaries:[]).filter(f).map(a=>u(a.status)).find(Boolean);return o==="sent"?"sent":o==="confirmed_echo"?"confirmed_echo":o==="manual_review"?"manual_review":e?"pending":"ok"}function A(t){return{kind:t.kind,name:t.name,mimeType:t.mimeType,size:t.size,localPath:t.localPath}}function w(t){return t.flatMap(r=>r.attachments??[])}export{b as runWeChatReadLatest,M as runWeChatSend};
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import type { WeChatReadLatestResult, WeChatSendResult, WeChatToolErrorResult } from './types.js';
|
|
2
|
-
export type WeChatReadOutputFormat = 'markdown' | 'json';
|
|
3
|
-
export declare function printToolResult(result: WeChatSendResult, json?: boolean): void;
|
|
4
|
-
export declare function printReadLatestResult(result: WeChatReadLatestResult, format: WeChatReadOutputFormat): void;
|
|
5
|
-
export declare function printToolError(operation: 'read' | 'write', conversation: string | undefined, error: unknown, json?: boolean): void;
|
|
6
|
-
export declare function buildWeChatToolErrorResult(operation: 'read' | 'write', conversation: string | undefined, error: unknown): WeChatToolErrorResult;
|
|
7
|
-
export declare function buildWeChatReadMarkdown(result: WeChatReadLatestResult): string;
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import y from"node:path";import{cleanInline as a,describeSendStatus as b,stringValue as o}from"./utils.js";const S=["SHENNIAN_WECHAT_CHANNEL_HELPER_DIR","SHENNIAN_HELPER_RUNTIME_DIR","packages/helper-runtime/wechat-channel","packages\\helper-runtime\\wechat-channel","packages/helper-runtime/dist","packages\\helper-runtime\\dist","wechat-rpa-windows-product-send-runner","PowerShell one-shot runner","activity.snapshot","automation.lease."],w=new Set(["wechat_not_running","wechat_window_not_found","permission_screen_recording_missing","permission_accessibility_missing","permission_input_monitoring_missing"]);function T(e,i){if(i){console.log(JSON.stringify(e,null,2));return}console.log(b(e.sendStatus))}function C(e,i){if(i==="json"){console.log(JSON.stringify(e,null,2));return}console.log(W(e).trimEnd())}function D(e,i,n,t){const r=k(e,i,n);t?console.log(JSON.stringify(r,null,2)):console.error(`${r.reasonCode}: ${r.message}`),process.exitCode=1}function k(e,i,n){const t=n instanceof Error?n.message:String(n||"wechat_tool_failed"),r=a(t)||"wechat_tool_failed",l=/^([a-z][a-z0-9_]*)(?::\s*(.*))?$/i.exec(r),s=o(n?.reasonCode)||l?.[1]||"wechat_tool_failed",c=q(s,r),_=a(l?.[2]||r),v=R(c,_,s),p=o(n?.outDir),d=o(n?.helperTracePath),h=o(n?.activityGuardPath),m=o(n?.traceId),f=E(c,s);return{ok:!1,operation:e,...i?.trim()?{conversation:i.trim()}:{},reasonCode:c,...P(s,c,_)?{rawReasonCode:s}:{},message:v,...m?{traceId:m}:{},...p?{outDir:p}:{},...d?{helperTracePath:d}:{},...h?{activityGuardPath:h}:{},...f?{userAction:f}:{}}}function W(e){const i=[];if(e.messages.length===0)return`\uFF08\u6CA1\u6709\u8BFB\u5230\uFF09
|
|
2
|
-
`;for(const n of e.messages)i.push(`${L(n)}: ${A(n)}`);return`${i.join(`
|
|
3
|
-
`)}
|
|
4
|
-
`}function q(e,i=""){const n=e.trim().toLowerCase(),t=`${n} ${i}`.toLowerCase();return n?n==="insufficient_credits"?"insufficient_credits":n==="entitlement_required"||n==="enterprise_required"||n.includes("entitlement")?"entitlement_required":n==="manual_review_required"||n.includes("manual_review")?"manual_review_required":n==="attachment_pending"||/attachment.*pending|media_original_pending/.test(t)?"attachment_pending":/helper_runtime_required|helper_runtime_source_missing|helper_runtime_package_manifest_missing|manifest_missing|helper_missing|helper_not_executable/.test(n)?"helper_missing":/helper_runtime_cli_too_old|helper_runtime_version_mismatch|helper_runtime_protocol_mismatch|helper_runtime_platform_mismatch|helper_runtime_package_manifest_invalid|integrity_mismatch/.test(n)?"helper_version_incompatible":/^user_active|recent_(keyboard|mouse|scroll)|frontmost_app_changed|user_takeover|activity|automation_busy/.test(n)?"user_active_retry_later":/^manager_ipc_(timeout|network_failed)$/.test(n)?n:/helper_command_timeout/.test(n)?"wechat_window_unavailable":u(t)?"wechat_tool_failed":/permission|accessibility|screen_recording|automation|mac_input|input-monitoring/.test(t)?"permission_required":/wechat_login_required|login_required|安全验证|扫码登录|重新登录/.test(t)?"wechat_login_required":/wechat_single_main_window_required|wechat_duplicate_instance|duplicate_main_window/.test(n)?"wechat_window_unavailable":/visible_desktop|desktop_session|screen_locked|session_locked|rdp_disconnected|rdp.*visible|rdp.*desktop/.test(t)?"windows_visible_desktop_unavailable":/dpi_mapping_failed|display_topology|monitor_topology|multi_?monitor|multi_?screen/.test(t)?"dpi_mapping_failed":/conversation_not|conversation_title_not_confirmed|conversation_not_visible|open_read_required|search_result_not_visible/.test(n)?"conversation_not_found":/wechat_window|wechat_not_running|window_not|window_unavailable|window_unresponsive/.test(n)?"wechat_window_unavailable":n:"wechat_tool_failed"}function E(e,i=""){if(e==="wechat_login_required")return"Open WeChat on this machine, complete login or security verification, then retry.";if(e==="wechat_window_unavailable")return"Open Shennian Desktop and the main WeChat window on the active desktop, then retry. If running this command over SSH on Windows, retry with the local daemon available.";if(e==="wechat_single_main_window_required")return"Keep WeChat open and visible. If the window state is unclear, let Shennian re-check it with visual classification.";if(e==="windows_visible_desktop_unavailable")return"Unlock or reconnect the Windows visible desktop session, keep WeChat visible, then retry.";if(e==="dpi_mapping_failed")return"Move WeChat fully onto one visible display or use a supported display scaling setup, then retry.";if(e==="conversation_not_found")return"Check the WeChat conversation name and make sure the conversation can be searched.";if(e==="helper_missing")return"Open the \u4F7F\u7528\u5FAE\u4FE1 page in Shennian and click Install Helper, or open Shennian Desktop, then retry.";if(e==="helper_version_incompatible")return"Use Repair Helper on the \u4F7F\u7528\u5FAE\u4FE1 page, or upgrade Shennian CLI, then retry.";if(e==="permission_required")return $(i);if(e==="entitlement_required")return"Enable the WeChat capability for this account in Shennian.";if(e==="insufficient_credits")return"Add credits or adjust the account plan in Shennian.";if(e==="user_active_retry_later")return"Wait until the user is idle, then retry.";if(e==="attachment_pending")return"Open WeChat and let the attachment finish downloading, then retry.";if(e==="manual_review_required")return"Review the current WeChat window before retrying.";if(e==="manager_ipc_timeout"||e==="manager_ipc_network_failed")return"Restart Shennian Desktop or run this command with --transport direct, then retry."}function R(e,i,n){const t=n.trim().toLowerCase();return e==="permission_required"?H(t):!i||i===e||u(i)||w.has(t)?I(e):i}function H(e){return e.includes("screen_recording")?"Shennian Helper.app needs Screen Recording permission.":e.includes("accessibility")?"Shennian Helper.app needs Accessibility permission.":e.includes("input_monitoring")||e.includes("input-monitoring")?"Shennian Helper.app needs Input Monitoring permission.":"Shennian Helper.app needs macOS privacy permissions."}function $(e){const i=e.trim().toLowerCase();return i.includes("screen_recording")?"Grant Shennian Helper.app Screen Recording in Privacy & Security, then retry.":i.includes("accessibility")?"Grant Shennian Helper.app Accessibility in Privacy & Security, then retry.":i.includes("input_monitoring")||i.includes("input-monitoring")?"Grant Shennian Helper.app Input Monitoring in Privacy & Security, then retry.":"Grant Shennian Helper.app the required macOS permissions in Privacy & Security, then retry."}function P(e,i,n){const t=e.trim().toLowerCase();return!(e===i||w.has(t)||u(`${e} ${n}`))}function u(e){const i=e.replace(/\\/g,"/").toLowerCase();return S.some(n=>{const t=n.replace(/\\/g,"/").toLowerCase();return i.includes(t)})}function I(e){return e==="wechat_login_required"?"WeChat needs login or security verification on this machine.":e==="wechat_window_unavailable"?"WeChat window is not available on the active desktop.":e==="wechat_single_main_window_required"?"WeChat window state needs visual confirmation.":e==="windows_visible_desktop_unavailable"?"Windows visible desktop session is unavailable.":e==="dpi_mapping_failed"?"Windows display scaling or monitor geometry cannot be mapped safely.":e==="conversation_not_found"?"WeChat conversation was not found.":e==="helper_missing"?"Shennian Helper runtime is not installed or cannot be found.":e==="helper_version_incompatible"?"Shennian Helper runtime is incompatible with this CLI.":e==="permission_required"?"Shennian Helper.app needs macOS privacy permissions.":e==="entitlement_required"?"WeChat capability is not enabled for this account.":e==="insufficient_credits"?"Insufficient credits.":e==="user_active_retry_later"?"User activity is in progress; retry later.":e==="attachment_pending"?"WeChat attachment is still pending.":e==="manual_review_required"?"Manual review is required before retrying.":e==="manager_ipc_timeout"?"Local Shennian daemon did not respond before the request timed out.":e==="manager_ipc_network_failed"?"Local Shennian daemon connection failed during the request.":e}function A(e){const i=e.attachments||[],n=a(e.text);return n&&i.length===0?n:n&&i.length>0?`${n} ${i.map(g).join("\u3001")}`:i.length>0?i.map(g).join("\u3001"):"\uFF08\u6D88\u606F\uFF09"}function L(e){return a(e.sender.name||e.sender.id||"\u5BF9\u65B9")}function g(e){const i=a(e.name||y.basename(e.localPath||"")||e.type||"\u9644\u4EF6"),n=e.localPath||e.url||"",t=e.availability&&e.availability!=="edge-local"?` (${e.availability})`:"";return n?`[${N(i)}](${M(n)})${t}`:`${i}${t}`}function M(e){const i=e.replace(/\\/g,"/");return/[\s()<>]/.test(i)?`<${i.replace(/[<>]/g,"")}>`:i}function N(e){return a(e).replace(/([\\\]])/g,"\\$1")}export{W as buildWeChatReadMarkdown,k as buildWeChatToolErrorResult,C as printReadLatestResult,D as printToolError,T as printToolResult};
|
|
@@ -1,142 +0,0 @@
|
|
|
1
|
-
import type { ExternalMessageAttachment, ExternalMessageEvent, ExternalReplyAttachment } from '../../channels/base.js';
|
|
2
|
-
export type WeChatDoctorCheck = {
|
|
3
|
-
id: string;
|
|
4
|
-
ok: boolean;
|
|
5
|
-
status: 'ready' | 'blocked' | 'warning';
|
|
6
|
-
reasonCode?: string;
|
|
7
|
-
message: string;
|
|
8
|
-
};
|
|
9
|
-
export type WeChatDoctorResult = {
|
|
10
|
-
ok: boolean;
|
|
11
|
-
checks: WeChatDoctorCheck[];
|
|
12
|
-
serverUrl?: string;
|
|
13
|
-
machineId?: string;
|
|
14
|
-
};
|
|
15
|
-
export type WeChatDoctorOptions = {
|
|
16
|
-
serverUrl?: string;
|
|
17
|
-
machineToken?: string;
|
|
18
|
-
machineId?: string;
|
|
19
|
-
fetchImpl?: typeof fetch;
|
|
20
|
-
};
|
|
21
|
-
export type IpcContext = {
|
|
22
|
-
url: string;
|
|
23
|
-
token: string;
|
|
24
|
-
};
|
|
25
|
-
export type IpcResponse = {
|
|
26
|
-
ok: boolean;
|
|
27
|
-
error?: string;
|
|
28
|
-
channel?: unknown;
|
|
29
|
-
messages?: unknown;
|
|
30
|
-
[key: string]: unknown;
|
|
31
|
-
};
|
|
32
|
-
export type WeChatToolBinding = {
|
|
33
|
-
sessionId: string;
|
|
34
|
-
channelId: string;
|
|
35
|
-
conversationId: string;
|
|
36
|
-
conversationName: string;
|
|
37
|
-
workDir: string;
|
|
38
|
-
};
|
|
39
|
-
export type WeChatManagerIpcResolution = {
|
|
40
|
-
ctx: IpcContext;
|
|
41
|
-
mode: 'session' | 'tool';
|
|
42
|
-
};
|
|
43
|
-
export type WeChatToolTransport = 'auto' | 'daemon' | 'direct';
|
|
44
|
-
export type WeChatToolOptions = {
|
|
45
|
-
conversation: string;
|
|
46
|
-
sessionId?: string;
|
|
47
|
-
workDir?: string;
|
|
48
|
-
source?: string;
|
|
49
|
-
download?: 'auto' | 'never';
|
|
50
|
-
transport?: WeChatToolTransport;
|
|
51
|
-
traceId?: string;
|
|
52
|
-
timeoutMs?: number;
|
|
53
|
-
recentLimit?: number;
|
|
54
|
-
pollIntervalMs?: number;
|
|
55
|
-
platform?: NodeJS.Platform | string;
|
|
56
|
-
fetchImpl?: typeof fetch;
|
|
57
|
-
ipc?: IpcContext;
|
|
58
|
-
directRuntime?: WeChatDirectToolRuntime;
|
|
59
|
-
};
|
|
60
|
-
export type WeChatDirectToolRuntime = {
|
|
61
|
-
readLatest(binding: WeChatToolBinding, options: WeChatReadLatestOptions): Promise<ExternalMessageEvent[]>;
|
|
62
|
-
send(binding: WeChatToolBinding, options: WeChatSendOptions): Promise<{
|
|
63
|
-
pending?: boolean;
|
|
64
|
-
sendStatus?: WeChatSendResult['sendStatus'];
|
|
65
|
-
outDir?: string;
|
|
66
|
-
helperTracePath?: string | null;
|
|
67
|
-
}>;
|
|
68
|
-
};
|
|
69
|
-
export type WeChatSendOptions = WeChatToolOptions & {
|
|
70
|
-
text: string;
|
|
71
|
-
attachment?: ExternalReplyAttachment;
|
|
72
|
-
idempotencyKey?: string;
|
|
73
|
-
dryRun?: boolean;
|
|
74
|
-
};
|
|
75
|
-
export type WeChatReadLatestOptions = WeChatToolOptions & {
|
|
76
|
-
limit?: number;
|
|
77
|
-
};
|
|
78
|
-
export type WeChatSendResult = {
|
|
79
|
-
ok: true;
|
|
80
|
-
operation: 'write';
|
|
81
|
-
conversation: string;
|
|
82
|
-
conversationName: string;
|
|
83
|
-
conversationId: string;
|
|
84
|
-
sessionId: string;
|
|
85
|
-
channelId: string;
|
|
86
|
-
traceId?: string;
|
|
87
|
-
outDir: string;
|
|
88
|
-
helperTracePath?: string | null;
|
|
89
|
-
sendStatus: 'dry_run' | 'queued' | 'sent' | 'sent_unconfirmed' | 'confirmed_echo' | 'manual_review' | 'pending' | 'ok';
|
|
90
|
-
pending?: boolean;
|
|
91
|
-
attachment?: Pick<ExternalReplyAttachment, 'kind' | 'name' | 'mimeType' | 'size' | 'localPath'>;
|
|
92
|
-
attachments: Array<Pick<ExternalReplyAttachment, 'kind' | 'name' | 'mimeType' | 'size' | 'localPath'>>;
|
|
93
|
-
dryRun?: boolean;
|
|
94
|
-
reasonCode?: null;
|
|
95
|
-
message?: string;
|
|
96
|
-
};
|
|
97
|
-
export type WeChatReadLatestResult = {
|
|
98
|
-
ok: true;
|
|
99
|
-
operation: 'read';
|
|
100
|
-
conversation: string;
|
|
101
|
-
conversationName: string;
|
|
102
|
-
conversationId: string;
|
|
103
|
-
sessionId: string;
|
|
104
|
-
channelId: string;
|
|
105
|
-
traceId?: string;
|
|
106
|
-
outDir: string;
|
|
107
|
-
helperTracePath?: string | null;
|
|
108
|
-
activityGuardPath?: string | null;
|
|
109
|
-
messages: ExternalMessageEvent[];
|
|
110
|
-
attachments: ExternalMessageAttachment[];
|
|
111
|
-
count: number;
|
|
112
|
-
reasonCode?: null;
|
|
113
|
-
message?: string;
|
|
114
|
-
};
|
|
115
|
-
export type WeChatToolErrorResult = {
|
|
116
|
-
ok: false;
|
|
117
|
-
operation: 'read' | 'write';
|
|
118
|
-
conversation?: string;
|
|
119
|
-
reasonCode: string;
|
|
120
|
-
rawReasonCode?: string;
|
|
121
|
-
message: string;
|
|
122
|
-
traceId?: string;
|
|
123
|
-
outDir?: string;
|
|
124
|
-
helperTracePath?: string | null;
|
|
125
|
-
activityGuardPath?: string | null;
|
|
126
|
-
userAction?: string;
|
|
127
|
-
};
|
|
128
|
-
export declare class WeChatToolOperationError extends Error {
|
|
129
|
-
readonly reasonCode: string;
|
|
130
|
-
readonly outDir?: string;
|
|
131
|
-
readonly helperTracePath?: string | null;
|
|
132
|
-
readonly activityGuardPath?: string | null;
|
|
133
|
-
readonly traceId?: string;
|
|
134
|
-
constructor(input: {
|
|
135
|
-
reasonCode: string;
|
|
136
|
-
message?: string;
|
|
137
|
-
outDir?: string;
|
|
138
|
-
helperTracePath?: string | null;
|
|
139
|
-
activityGuardPath?: string | null;
|
|
140
|
-
traceId?: string;
|
|
141
|
-
});
|
|
142
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
class t extends Error{reasonCode;outDir;helperTracePath;activityGuardPath;traceId;constructor(e){const r=o(e.message||e.reasonCode);super(r&&r!==e.reasonCode?`${e.reasonCode}: ${r}`:e.reasonCode),this.name="WeChatToolOperationError",this.reasonCode=e.reasonCode,this.outDir=e.outDir,this.helperTracePath=e.helperTracePath,this.activityGuardPath=e.activityGuardPath,this.traceId=e.traceId}}function o(a){return String(a||"").replace(/\s+/g," ").trim()}export{t as WeChatToolOperationError};
|