shennian 0.3.1 → 0.3.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -1
- package/dist/publish-build-manifest.json +291 -341
- package/dist/src/agents/codex.js +1 -1
- 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/model-registry/service.js +1 -1
- 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/runtime-compatibility.d.ts +11 -0
- package/dist/src/agents/runtime-compatibility.js +1 -0
- 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 +24 -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/agent-tool.d.ts +62 -0
- package/dist/src/room/agent-tool.js +1 -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-binding.d.ts +42 -0
- package/dist/src/room/managed-room-binding.js +1 -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 +210 -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 +118 -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/handlers/room-managed.d.ts +4 -0
- package/dist/src/session/handlers/room-managed.js +1 -0
- package/dist/src/session/manager.d.ts +18 -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/agent-workspace.d.ts +41 -0
- package/node_modules/@shennian/wire/dist/agent-workspace.d.ts.map +1 -0
- package/node_modules/@shennian/wire/dist/agent-workspace.js +3 -0
- package/node_modules/@shennian/wire/dist/agent-workspace.js.map +1 -0
- package/node_modules/@shennian/wire/dist/index.d.ts +3 -1
- package/node_modules/@shennian/wire/dist/index.d.ts.map +1 -1
- package/node_modules/@shennian/wire/dist/index.js +3 -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 +15 -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
package/dist/src/agents/pi.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{randomUUID as _}from"node:crypto";import l from"node:fs";import g from"node:path";import{execFile as A}from"node:child_process";import{promisify as T}from"node:util";import{Agent as I,streamProxy as j}from"@mariozechner/pi-agent-core";import{streamOpenAICompletions as D}from"@mariozechner/pi-ai/openai-completions";import{Type as p}from"@sinclair/typebox";import{AgentAdapter as $,registerAgent as F}from"./adapter.js";import{buildExternalChannelInstructions as L}from"./external-channel-instructions.js";import{loadConfig as N}from"../config/index.js";import{getManagedAgentProviderConfig as O}from"./config-status.js";import{SERVERS as z}from"../region.js";import{buildAgentProcessEnv as R}from"../agent-env.js";import{buildRollingSummary as E,buildShellCommandSpec as P,cloneMessages as f,CONTEXT_TOKEN_THRESHOLD as v,createPiModel as M,estimateTokens as w,getSessionDir as q,KEEP_RECENT_MESSAGES as k,LEGACY_SUMMARY_FILENAME as U,loadAgentsMdInstructions as B,longestCommonPrefixLength as K,MESSAGES_FILENAME as G,messagesToText as J,PI_DEFAULT_MODEL_ID as H,requestProxySummary as Y,SNAPSHOT_FILENAME as W,SYSTEM_PROMPT as V,SUMMARY_FILENAME as X}from"./pi-context.js";import{buildShellCommandSpec as Et}from"./pi-context.js";const Q=T(A),Z="https://dashscope.aliyuncs.com/compatible-mode/v1";function C(r){return r.includes("entitlement_required")?"\u5F53\u524D\u8D26\u53F7\u5C1A\u672A\u5F00\u901A Nian \u6258\u7BA1\u6A21\u578B\u3002\u8BF7\u524D\u5F80\u795E\u5FF5\u300C\u5957\u9910\u4E0E\u652F\u4ED8\u300D\u5F00\u901A Pro \u6216 Team\uFF0C\u83B7\u5F97\u79EF\u5206\u540E\u91CD\u8BD5\u3002":r.includes("insufficient_credits")?"\u79EF\u5206\u4E0D\u8DB3\uFF0CNian \u6682\u65F6\u65E0\u6CD5\u56DE\u590D\u3002\u8BF7\u524D\u5F80\u795E\u5FF5\u300C\u5957\u9910\u4E0E\u652F\u4ED8\u300D\u8D2D\u4E70\u79EF\u5206\u5305\u540E\u91CD\u8BD5\u3002":r.includes("429")||r.includes("daily_quota_exceeded")||r.includes("nian_quota_exceeded")?r.includes("too quickly")||r.includes("per minute")?"Nian \u8BF7\u6C42\u8FC7\u4E8E\u9891\u7E41\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002":"Nian \u4ECA\u65E5\u989D\u5EA6\u5DF2\u7528\u5B8C\uFF0C\u6B21\u65E5\u81EA\u52A8\u6062\u590D\u3002":r}function y(r,t){return g.resolve(r,t)}async function tt(r,t,e,s){const n=P(t),{stdout:i,stderr:o}=await Q(n.file,n.args,{cwd:r,env:R(e),timeout:3e4,signal:s,maxBuffer:1024*1024,windowsHide:!0});return{stdout:i,stderr:o,shell:n.shell}}function b(r){return typeof r=="string"?r:Buffer.isBuffer(r)?r.toString("utf8"):""}function et(r){if(!r||typeof r!="object")return String(r);const t=r,e=[t.message||String(r)],s=b(t.stdout).trim(),n=b(t.stderr).trim();return s&&e.push(`---stdout---
|
|
2
|
-
${s}`),n&&e.push(`---stderr---
|
|
3
|
-
${n}`),t.code!==void 0&&e.push(`exitCode: ${String(t.code)}`),t.signal&&e.push(`signal: ${t.signal}`),e.join(`
|
|
4
|
-
`)}function st(r,t={}){return[{name:"read_file",label:"\u8BFB\u53D6\u6587\u4EF6",description:"Read the full content of a file at the given path.",parameters:p.Object({path:p.String({description:"Absolute or relative file path"})}),async execute(e,{path:s}){let n="";try{return n=y(r,s),{content:[{type:"text",text:l.readFileSync(n,"utf-8")}],details:{path:n}}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:String(i)}`}],details:{path:n}}}}},{name:"write_file",label:"\u5199\u5165\u6587\u4EF6",description:"Write content to a file, creating it or overwriting if it exists.",parameters:p.Object({path:p.String({description:"Absolute or relative file path"}),content:p.String({description:"File content to write"})}),async execute(e,{path:s,content:n}){let i="";try{return i=y(r,s),l.mkdirSync(g.dirname(i),{recursive:!0}),l.writeFileSync(i,n,"utf-8"),{content:[{type:"text",text:`Written ${n.length} bytes to ${i}`}],details:{path:i}}}catch(o){return{content:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}],details:{path:i}}}}},{name:"list_directory",label:"\u5217\u51FA\u76EE\u5F55",description:"List files and directories at the given path.",parameters:p.Object({path:p.String({description:"Directory path to list",default:"."})}),async execute(e,{path:s}){let n="";try{return n=y(r,s),{content:[{type:"text",text:l.readdirSync(n,{withFileTypes:!0}).map(h=>`${h.isDirectory()?"d":"f"} ${h.name}`).join(`
|
|
5
|
-
`)||"(empty)"}],details:{path:n}}}catch(i){return{content:[{type:"text",text:`Error: ${i instanceof Error?i.message:String(i)}`}],details:{path:n}}}}},{name:"bash",label:"\u6267\u884C\u547D\u4EE4",description:"Execute a shell command in the working directory. Uses PowerShell on Windows and bash on macOS/Linux. Timeout: 30s.",parameters:p.Object({command:p.String({description:"Shell command to execute"})}),async execute(e,{command:s},n){try{const{stdout:i,stderr:o,shell:h}=await tt(r,s,t,n);return{content:[{type:"text",text:[i,o].filter(Boolean).join(`
|
|
6
|
-
---stderr---
|
|
7
|
-
`)||"(no output)"}],details:{command:s,shell:h}}}catch(i){return{content:[{type:"text",text:`Error: ${et(i)}`}],details:{command:s,shell:P(s).shell}}}}},{name:"read_image",label:"\u8BFB\u53D6\u56FE\u7247",description:"Read an image file and return its content for visual analysis. Supports png, jpg, jpeg, gif, webp. Max 10 MB.",parameters:p.Object({path:p.String({description:"Absolute or relative path to the image file"})}),async execute(e,{path:s}){let n;try{n=y(r,s)}catch(a){return{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],details:{path:s}}}const i=g.extname(n).toLowerCase().slice(1),h={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp"}[i];if(!h)return{content:[{type:"text",text:`Error: unsupported image type ".${i}". Supported: png, jpg, jpeg, gif, webp`}],details:{path:n}};try{const a=l.statSync(n);return a.size>10*1024*1024?{content:[{type:"text",text:`Error: image too large (${(a.size/1024/1024).toFixed(1)} MB, max 10 MB)`}],details:{path:n}}:{content:[{type:"image",data:l.readFileSync(n).toString("base64"),mimeType:h}],details:{path:n,mimeType:h,size:a.size}}}catch(a){return{content:[{type:"text",text:`Error: ${a instanceof Error?a.message:String(a)}`}],details:{path:n}}}}}]}class nt extends ${type="pi";agent=null;sessionId=null;workDir=null;seq=0;runId="";emittedLengths=new Map;terminalState="open";authToken=null;proxyUrl=null;providerConfig;sessionDir=null;messagesPath=null;snapshotPath=null;summaryPath=null;cachedSummary=null;restoredMessages=[];compressing=!1;lastSummaryMsgCount=0;pendingBaseMessages=[];finalizePromise=Promise.resolve();sendGeneration=0;externalChannel=null;shennianSessionId=null;extraEnv={};pendingSendStart=null;configure(t){this.shennianSessionId=t.sessionId??null,this.externalChannel=t.externalChannel??null,this.extraEnv=t.env??{}}async start(t,e,s){this.sessionId=t,this.workDir=e,this.seq=0,this.sessionDir=q(t),this.messagesPath=g.join(this.sessionDir,G),this.snapshotPath=g.join(this.sessionDir,W),this.summaryPath=g.join(this.sessionDir,X),this.loadSnapshot(),this.loadSummary()}async send(t,e){const s=++this.sendGeneration,n=this.agent&&this.terminalState==="open"?f(this.pendingBaseMessages):null;n&&(this.agent?.abort(),this.agent=null,this.restoredMessages=n,this.finalizePromise=Promise.resolve());const i=N(),o=i.machineToken??i.accessToken;if(!o){this.emit("agentEvent",{state:"error",runId:this.runId,seq:++this.seq,message:"\u672A\u914D\u5BF9\uFF0C\u8BF7\u5148\u8FD0\u884C shennian \u5B8C\u6210\u673A\u5668\u914D\u5BF9"});return}this.authToken=o,this.proxyUrl=(i.serverUrl??z.cn.url).replace(/\/$/,"");const h=O("pi"),a=i.apiKeys?.dashscope?.trim();this.providerConfig=h??(a?{agent:"pi",token:a,updatedAt:""}:void 0),this.runId=_(),this.seq=0,this.emittedLengths.clear(),this.terminalState="open",this.agent||this.initAgent(),await this.finalizePromise.catch(()=>{}),this.agent?.setModel(M(e??H)),this.pendingBaseMessages=f(this.agent?.state.messages??[]);const u=this.runId,m=new Promise((c,d)=>{this.pendingSendStart={runId:u,resolve:c,reject:d}});this.emit("agentEvent",{state:"init",runId:u,seq:++this.seq}),this.agent.prompt(t).then(async()=>{s===this.sendGeneration&&(this.resolvePendingSendStart(u),await this.finalizePromise.catch(()=>{}))}).catch(c=>{if(s!==this.sendGeneration||(this.rejectPendingSendStart(u,c),this.terminalState!=="open"))return;this.terminalState="error";const d=c instanceof Error?c.message:String(c);this.emit("agentEvent",{state:"error",runId:u,seq:++this.seq,message:C(d)})}),await m}async getStatus(){const t=!!(this.runId&&this.terminalState==="open");return{active:t,runId:this.runId||null,runPhase:null,canStop:t}}initAgent(){const t=this.workDir??process.cwd(),e=st(t,this.extraEnv),s=B(t),n=new I({initialState:{systemPrompt:[V,s,`\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\uFF1A${t}`,L(this.externalChannel,t,this.shennianSessionId??void 0)].filter(Boolean).join(`
|
|
8
|
-
|
|
9
|
-
`),model:M(),tools:e},streamFn:(i,o,h)=>{const a=this.providerConfig;return a?.token?D(M(i.id,{provider:"dashscope",baseUrl:a.baseUrl||Z,compat:{supportsDeveloperRole:!1,supportsStore:!1,supportsReasoningEffort:!1,maxTokensField:"max_tokens",thinkingFormat:"qwen"}}),o,{...h,apiKey:a.token}):j(i,o,{...h,authToken:this.authToken,proxyUrl:this.proxyUrl})},transformContext:i=>this.compressContext(i)});this.agent=n,this.restoredMessages.length>0?n.replaceMessages(f(this.restoredMessages)):this.cachedSummary&&(n.appendMessage({role:"user",content:[{type:"text",text:`[\u4E4B\u524D\u7684\u5BF9\u8BDD\u6458\u8981]
|
|
10
|
-
${this.cachedSummary}`}],timestamp:Date.now()}),n.appendMessage({role:"assistant",content:[{type:"text",text:"\u597D\u7684\uFF0C\u6211\u5DF2\u4E86\u89E3\u4E4B\u524D\u7684\u5BF9\u8BDD\u4E0A\u4E0B\u6587\uFF0C\u8BF7\u7EE7\u7EED\u3002"}],timestamp:Date.now()})),n.subscribe(i=>{if(this.agent!==n||this.terminalState!=="open")return;const o=++this.seq,h=this.runId;switch(i.type){case"agent_start":this.resolvePendingSendStart(h),this.emit("agentEvent",{state:"start",runId:h,seq:o});break;case"message_update":{const a=i.message;if(a.role!=="assistant")break;const u=a.content??[];for(let m=0;m<u.length;m++){const c=u[m];if(c.type==="text"&&c.text){const d=`text:${m}`,S=this.emittedLengths.get(d)??0;if(c.text.length>S){const x=c.text.slice(S);this.emittedLengths.set(d,c.text.length),this.emit("agentEvent",{state:"delta",runId:h,seq:o,text:x})}}else if(c.type==="thinking"&&c.thinking){const d=`thinking:${m}`,S=this.emittedLengths.get(d)??0;if(c.thinking.length>S){const x=c.thinking.slice(S);this.emittedLengths.set(d,c.thinking.length),this.emit("agentEvent",{state:"delta",runId:h,seq:o,text:x,thinking:!0})}}}break}case"tool_execution_start":this.emit("agentEvent",{state:"tool-call",runId:h,seq:o,name:i.toolName,args:i.args});break;case"tool_execution_end":this.emit("agentEvent",{state:"tool-result",runId:h,seq:o,name:i.toolName,result:typeof i.result=="string"?i.result:JSON.stringify(i.result)});break;case"agent_end":{const a=i.messages,u=[...a].reverse().find(d=>d.role==="assistant"),m=u;if(m?.stopReason==="error"){this.terminalState="error",this.emit("agentEvent",{state:"error",runId:h,seq:o,message:C(m.errorMessage||"Nian \u8BF7\u6C42\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5\u3002")}),this.finalizePromise=this.finalizeTurn(a);break}this.terminalState="final";const c=u?.usage;this.emit("agentEvent",{state:"final",runId:h,seq:o,usage:c?{inputTokens:c.input??0,outputTokens:c.output??0}:void 0}),this.finalizePromise=this.finalizeTurn(a);break}}})}async compressAndReplace(){if(!this.agent||this.compressing)return;const t=this.agent.state.messages;if(w(t)<v)return;const s=this.splitMessages(t);if(!s)return;const n=await this.generateSummary(s.toCompress);if(!n)return;this.cachedSummary=n,this.lastSummaryMsgCount+=s.toCompress.length;const i=[{role:"user",content:[{type:"text",text:`[\u5386\u53F2\u5BF9\u8BDD\u6458\u8981]
|
|
11
|
-
${n}`}],timestamp:Date.now()},{role:"assistant",content:[{type:"text",text:"\u597D\u7684\uFF0C\u6211\u5DF2\u4E86\u89E3\u4E0A\u4E0B\u6587\u3002"}],timestamp:Date.now()},...s.toKeep];this.agent.replaceMessages(i)}async compressContext(t){if(w(t)<v||!this.cachedSummary)return t;const s=this.splitMessages(t);return s?[{role:"user",content:[{type:"text",text:`[\u5386\u53F2\u5BF9\u8BDD\u6458\u8981]
|
|
12
|
-
${this.cachedSummary}`}],timestamp:Date.now()},...s.toKeep]:t}splitMessages(t){const e=t.filter(n=>n.role!=="system");if(e.length<=k)return null;let s=e.length-k;for(;s>0&&e[s].role==="toolResult";)s--;return s<=0?null:{toCompress:e.slice(0,s),toKeep:e.slice(s)}}async generateSummary(t){if(!this.authToken||!this.proxyUrl||this.compressing)return this.cachedSummary;this.compressing=!0;try{const e=J(t);if(e.length<100)return null;const s=e.length>1e4?e.slice(0,1e4)+`
|
|
13
|
-
...(\u5DF2\u622A\u65AD)`:e;return await Y(this.proxyUrl,this.authToken,`\u8BF7\u5C06\u4EE5\u4E0B\u5BF9\u8BDD\u5386\u53F2\u538B\u7F29\u4E3A\u7B80\u6D01\u6458\u8981\uFF0C\u4FDD\u7559\u5173\u952E\u4FE1\u606F\uFF1A\u8BA8\u8BBA\u7684\u6587\u4EF6\u548C\u76EE\u5F55\u3001\u505A\u51FA\u7684\u6280\u672F\u51B3\u5B9A\u3001\u5F53\u524D\u4EFB\u52A1\u8FDB\u5EA6\u3001\u672A\u5B8C\u6210\u7684\u5DE5\u4F5C\u3002\u6458\u8981\u63A7\u5236\u5728 300 \u5B57\u4EE5\u5185\u3002
|
|
14
|
-
|
|
15
|
-
${s}`)}catch{return this.cachedSummary}finally{this.compressing=!1}}loadSnapshot(){if(this.snapshotPath)try{const t=l.readFileSync(this.snapshotPath,"utf-8"),e=JSON.parse(t);this.restoredMessages=Array.isArray(e.messages)?e.messages:[],this.cachedSummary=e.summary??this.cachedSummary,this.lastSummaryMsgCount=e.summarizedCount??this.lastSummaryMsgCount}catch{this.restoredMessages=[]}}loadSummary(){if(this.summaryPath)try{const t=l.readFileSync(this.summaryPath,"utf-8"),e=JSON.parse(t);this.cachedSummary=e.summary??null,this.lastSummaryMsgCount=e.summarizedCount??0}catch{if(!this.sessionDir)return;try{const t=g.join(this.sessionDir,U),e=l.readFileSync(t,"utf-8"),s=JSON.parse(e);this.cachedSummary=s.summary??null,this.lastSummaryMsgCount=s.summarizedCount??0}catch{}}}saveSummary(t){if(this.summaryPath)try{l.mkdirSync(g.dirname(this.summaryPath),{recursive:!0});const e=E(this.cachedSummary,t);this.cachedSummary=e,l.writeFileSync(this.summaryPath,JSON.stringify({version:1,summary:e,summarizedCount:this.lastSummaryMsgCount,updatedAt:Date.now()},null,2))}catch{}}saveSnapshot(t){if(!(!this.snapshotPath||!this.sessionId||!this.workDir))try{l.mkdirSync(g.dirname(this.snapshotPath),{recursive:!0}),l.writeFileSync(this.snapshotPath,JSON.stringify({version:1,sessionId:this.sessionId,workDir:this.workDir,summary:this.cachedSummary,summarizedCount:this.lastSummaryMsgCount,messages:t,updatedAt:Date.now()},null,2)),this.restoredMessages=f(t)}catch{}}appendMessagesLog(t){if(!(!this.messagesPath||t.length===0))try{l.mkdirSync(g.dirname(this.messagesPath),{recursive:!0});const e=t.map(s=>JSON.stringify(s)).join(`
|
|
16
|
-
`)+`
|
|
17
|
-
`;l.appendFileSync(this.messagesPath,e,"utf-8")}catch{}}getTurnMessages(t){const e=K(this.pendingBaseMessages,t);return f(t.slice(e))}async finalizeTurn(t){const e=f(t),s=this.getTurnMessages(e);this.appendMessagesLog(s),await this.compressAndReplace();const n=this.agent?f(this.agent.state.messages):e;this.cachedSummary||(this.cachedSummary=E(null,e)),this.saveSummary(n),this.saveSnapshot(n)}async resume(t){this.loadSnapshot(),this.loadSummary(),this.agent&&this.restoredMessages.length>0&&this.agent.replaceMessages(f(this.restoredMessages))}async stop(){if(this.rejectPendingSendStart(this.runId,new Error("Pi run stopped before dispatch completed")),await this.finalizePromise.catch(()=>{}),this.agent){const t=f(this.agent.state.messages??[]);this.saveSummary(t),this.saveSnapshot(t)}this.agent?.abort(),this.agent=null}resolvePendingSendStart(t){if(!this.pendingSendStart||this.pendingSendStart.runId!==t)return;const{resolve:e}=this.pendingSendStart;this.pendingSendStart=null,e()}rejectPendingSendStart(t,e){if(!this.pendingSendStart||this.pendingSendStart.runId!==t)return;const{reject:s}=this.pendingSendStart;this.pendingSendStart=null,s(e)}}F("pi",()=>new nt);export{nt as PiAdapter,Et as buildShellCommandSpec,C as formatNianHostedModelError};
|
|
@@ -1,144 +0,0 @@
|
|
|
1
|
-
import type { ExternalChannelSessionStatus } from '@shennian/wire';
|
|
2
|
-
export type ExternalChannelRuntimeStatus = Pick<ExternalChannelSessionStatus, 'wechatRpaRuntimeState' | 'wechatRpaLastRunAt' | 'wechatRpaLastMessageAt' | 'wechatRpaLastInterruptedAt' | 'wechatRpaPendingReplyCount' | 'wechatRpaPendingReplies' | 'wechatRpaLastError' | 'wechatRpaLastRunId' | 'wechatRpaLastTracePath' | 'wechatRpaLastTraceSummary' | 'wechatRpaRecentTaskSummaries' | 'wechatRpaPreflightChecks' | 'wechatRpaServerDecisionAvailable' | 'wechatRpaPrivacyConsentAccepted'>;
|
|
3
|
-
export type ExternalChannelType = 'wecom' | 'websocket' | 'wechat-rpa';
|
|
4
|
-
export type ExternalChannelConfig = {
|
|
5
|
-
id: string;
|
|
6
|
-
type: ExternalChannelType;
|
|
7
|
-
name: string;
|
|
8
|
-
sessionId?: string;
|
|
9
|
-
managerSessionId: string;
|
|
10
|
-
workDir: string;
|
|
11
|
-
agentType?: string;
|
|
12
|
-
agentSessionId?: string | null;
|
|
13
|
-
modelId?: string | null;
|
|
14
|
-
enabled: boolean;
|
|
15
|
-
secretRef: string;
|
|
16
|
-
managedBy?: 'session-sync';
|
|
17
|
-
};
|
|
18
|
-
export type ExternalChannelView = {
|
|
19
|
-
id: string;
|
|
20
|
-
type: ExternalChannelType;
|
|
21
|
-
name: string;
|
|
22
|
-
sessionId?: string;
|
|
23
|
-
managerSessionId: string;
|
|
24
|
-
workDir: string;
|
|
25
|
-
agentType?: string;
|
|
26
|
-
agentSessionId?: string | null;
|
|
27
|
-
modelId?: string | null;
|
|
28
|
-
enabled: boolean;
|
|
29
|
-
wsUrl?: string;
|
|
30
|
-
token?: string;
|
|
31
|
-
tokenConfigured?: boolean;
|
|
32
|
-
canReply?: boolean;
|
|
33
|
-
systemPrompt?: string;
|
|
34
|
-
wechatRpaSource?: string;
|
|
35
|
-
wechatRpaGroups?: Array<{
|
|
36
|
-
name: string;
|
|
37
|
-
}>;
|
|
38
|
-
pollIntervalMs?: number;
|
|
39
|
-
recentLimit?: number;
|
|
40
|
-
idleSeconds?: number;
|
|
41
|
-
forceForeground?: boolean;
|
|
42
|
-
noRestore?: boolean;
|
|
43
|
-
downloadAttachments?: boolean;
|
|
44
|
-
downloadAttachmentsDir?: string;
|
|
45
|
-
selfNickname?: string | null;
|
|
46
|
-
wechatRpaRuntimeState?: ExternalChannelSessionStatus['wechatRpaRuntimeState'];
|
|
47
|
-
wechatRpaLastRunAt?: string | null;
|
|
48
|
-
wechatRpaLastMessageAt?: string | null;
|
|
49
|
-
wechatRpaLastInterruptedAt?: string | null;
|
|
50
|
-
wechatRpaPendingReplyCount?: ExternalChannelSessionStatus['wechatRpaPendingReplyCount'];
|
|
51
|
-
wechatRpaPendingReplies?: ExternalChannelSessionStatus['wechatRpaPendingReplies'];
|
|
52
|
-
wechatRpaLastError?: string | null;
|
|
53
|
-
wechatRpaLastRunId?: string | null;
|
|
54
|
-
wechatRpaLastTracePath?: string | null;
|
|
55
|
-
wechatRpaLastTraceSummary?: string | null;
|
|
56
|
-
wechatRpaRecentTaskSummaries?: ExternalChannelSessionStatus['wechatRpaRecentTaskSummaries'];
|
|
57
|
-
wechatRpaPreflightChecks?: ExternalChannelSessionStatus['wechatRpaPreflightChecks'];
|
|
58
|
-
wechatRpaServerDecisionAvailable?: boolean | null;
|
|
59
|
-
wechatRpaPrivacyConsentAccepted?: boolean | null;
|
|
60
|
-
managedBy?: 'session-sync';
|
|
61
|
-
};
|
|
62
|
-
export type ExternalMessageEvent = {
|
|
63
|
-
type: 'external.message';
|
|
64
|
-
channelId: string;
|
|
65
|
-
channelType: ExternalChannelType;
|
|
66
|
-
conversationId: string;
|
|
67
|
-
conversationName?: string | null;
|
|
68
|
-
messageId: string;
|
|
69
|
-
sender: {
|
|
70
|
-
id: string;
|
|
71
|
-
name?: string | null;
|
|
72
|
-
};
|
|
73
|
-
text: string;
|
|
74
|
-
attachments: ExternalMessageAttachment[];
|
|
75
|
-
receivedAt: string;
|
|
76
|
-
isMentioned?: boolean;
|
|
77
|
-
replyTarget: string;
|
|
78
|
-
rawRef?: string | null;
|
|
79
|
-
};
|
|
80
|
-
export type ExternalMessageAttachment = {
|
|
81
|
-
type: string;
|
|
82
|
-
name?: string;
|
|
83
|
-
url?: string;
|
|
84
|
-
mimeType?: string;
|
|
85
|
-
size?: number;
|
|
86
|
-
extension?: string;
|
|
87
|
-
localPath?: string;
|
|
88
|
-
thumbnailPath?: string;
|
|
89
|
-
hash?: string;
|
|
90
|
-
availability?: 'edge-local' | 'edge-preview' | 'server-url' | 'pending-download' | 'metadata-only' | 'unavailable-large' | 'failed';
|
|
91
|
-
machineId?: string;
|
|
92
|
-
expiresAt?: string;
|
|
93
|
-
providerError?: string;
|
|
94
|
-
sourceAction?: string;
|
|
95
|
-
materializationKind?: 'original-file' | 'clipboard-image' | 'preview-crop' | 'metadata';
|
|
96
|
-
isOriginal?: boolean;
|
|
97
|
-
mimeKindMatches?: boolean;
|
|
98
|
-
};
|
|
99
|
-
export type ExternalReplyAttachment = {
|
|
100
|
-
kind: 'image' | 'video' | 'file';
|
|
101
|
-
name: string;
|
|
102
|
-
mimeType: string;
|
|
103
|
-
size: number;
|
|
104
|
-
dataBase64?: string;
|
|
105
|
-
localPath?: string;
|
|
106
|
-
url?: string;
|
|
107
|
-
};
|
|
108
|
-
export type ExternalReply = {
|
|
109
|
-
channelId: string;
|
|
110
|
-
conversationId: string;
|
|
111
|
-
text: string;
|
|
112
|
-
attachment?: ExternalReplyAttachment;
|
|
113
|
-
messageId?: string;
|
|
114
|
-
idempotencyKey?: string;
|
|
115
|
-
};
|
|
116
|
-
export type ExternalChannelSendResult = void | {
|
|
117
|
-
status: 'sent' | 'queued' | 'manual-review';
|
|
118
|
-
reason?: string;
|
|
119
|
-
};
|
|
120
|
-
export interface ExternalChannelAdapter {
|
|
121
|
-
readonly type: ExternalChannelType;
|
|
122
|
-
connect(config: ExternalChannelConfig): Promise<void>;
|
|
123
|
-
disconnect(config: ExternalChannelConfig): Promise<void>;
|
|
124
|
-
send(config: ExternalChannelConfig, reply: ExternalReply): Promise<ExternalChannelSendResult>;
|
|
125
|
-
health(config: ExternalChannelConfig): Promise<{
|
|
126
|
-
ok: boolean;
|
|
127
|
-
message?: string;
|
|
128
|
-
}>;
|
|
129
|
-
defaultConversation?(config: ExternalChannelConfig): Promise<{
|
|
130
|
-
conversationId: string;
|
|
131
|
-
conversationName?: string;
|
|
132
|
-
}>;
|
|
133
|
-
runtimeStatus?(config: ExternalChannelConfig): Partial<ExternalChannelRuntimeStatus>;
|
|
134
|
-
syncNow?(config: ExternalChannelConfig): Promise<ExternalMessageEvent[] | void>;
|
|
135
|
-
cancelOutbound?(config: ExternalChannelConfig, input: {
|
|
136
|
-
idempotencyKey?: string | null;
|
|
137
|
-
replyId?: string | null;
|
|
138
|
-
reason?: string;
|
|
139
|
-
}): Promise<{
|
|
140
|
-
cancelled: boolean;
|
|
141
|
-
status?: string;
|
|
142
|
-
record?: unknown;
|
|
143
|
-
}>;
|
|
144
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import type { ExternalChannelConfig } from './base.js';
|
|
2
|
-
export declare class ChannelConfigRegistry {
|
|
3
|
-
list(): ExternalChannelConfig[];
|
|
4
|
-
get(channelId: string): ExternalChannelConfig | undefined;
|
|
5
|
-
upsert(config: ExternalChannelConfig): void;
|
|
6
|
-
replaceAll(channels: ExternalChannelConfig[]): void;
|
|
7
|
-
remove(channelId: string): boolean;
|
|
8
|
-
}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import t from"node:fs";import s from"node:path";import{resolveShennianPath as a}from"../config/index.js";function n(){return a("channels.json")}class f{list(){try{return JSON.parse(t.readFileSync(n(),"utf-8")).channels??[]}catch{return[]}}get(e){return this.list().find(r=>r.id===e)}upsert(e){const r=this.list().filter(i=>i.id!==e.id);r.push(e),t.mkdirSync(s.dirname(n()),{recursive:!0}),t.writeFileSync(n(),JSON.stringify({channels:r},null,2))}replaceAll(e){t.mkdirSync(s.dirname(n()),{recursive:!0}),t.writeFileSync(n(),JSON.stringify({channels:e},null,2))}remove(e){const r=this.list(),i=r.filter(l=>l.id!==e);return i.length===r.length?!1:(this.replaceAll(i),!0)}}export{f as ChannelConfigRegistry};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare function splitExternalReplyText(text: string): string[];
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
const _=500,p=360,P=6;function s(t){return Array.from(t).length}function f(t,e){return Array.from(t).slice(0,e).join("")}function u(t){return t.replace(/\r\n/g,`
|
|
2
|
-
`).replace(/[ \t]+\n/g,`
|
|
3
|
-
`).replace(/\n[ \t]+/g,`
|
|
4
|
-
`).trim()}function R(t){const e=[],r=t.split(/(?<=[。!?!?;;])\s*/).map(n=>n.trim()).filter(Boolean),i=r.length>1?r:Array.from(t);let l="";for(const n of i){const o=l?`${l}${r.length>1,""}${n}`:n;l&&s(o)>360?(e.push(l),l=n):l=o}return l&&e.push(l),e.flatMap(n=>{if(s(n)<=500)return[n];const o=Array.from(n),c=[];for(let a=0;a<o.length;a+=360)c.push(o.slice(a,a+360).join("").trim());return c.filter(Boolean)})}function A(t){if(t.length<=6)return t;const e=t.slice(0,5),r=t.slice(5).join(`
|
|
5
|
-
|
|
6
|
-
`),i=s(r)>500?`${f(r,499)}\u2026`:r;return[...e,i].filter(Boolean)}function E(t){const e=u(t);if(!e)return[];if(s(e)<=500&&!e.includes(`
|
|
7
|
-
|
|
8
|
-
`))return[e];const r=e.split(/\n{2,}/).map(o=>o.replace(/\n/g," ").replace(/\s+/g," ").trim()).filter(Boolean);if(r.length>1&&s(e)>360)return A(r.flatMap(R));const i=r.length>1?r:[e.replace(/\n/g," ").replace(/\s+/g," ").trim()],l=[];let n="";for(const o of i.flatMap(R)){const c=n?`${n}
|
|
9
|
-
|
|
10
|
-
${o}`:o;n&&s(c)>500?(l.push(n),n=o):n=c}return n&&l.push(n),A(l)}export{E as splitExternalReplyText};
|
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
import type { ExternalChannelConfig, ExternalChannelView, ExternalMessageEvent, ExternalReply } from './base.js';
|
|
2
|
-
import type { ExternalChannelSessionStatus } from '@shennian/wire';
|
|
3
|
-
import type { WeChatRpaProductRunnerFactory } from './wechat-rpa/product-channel.js';
|
|
4
|
-
import type { WeChatAutomationLane } from './wechat-channel/automation-lane.js';
|
|
5
|
-
export type ChannelRuntimeOptions = {
|
|
6
|
-
createWeChatRpaProductRunner?: WeChatRpaProductRunnerFactory;
|
|
7
|
-
weChatAutomationLane?: WeChatAutomationLane;
|
|
8
|
-
};
|
|
9
|
-
export declare class ChannelRuntime {
|
|
10
|
-
private onExternalMessage;
|
|
11
|
-
private createReplyTarget;
|
|
12
|
-
private configs;
|
|
13
|
-
private secrets;
|
|
14
|
-
private adapters;
|
|
15
|
-
private completedReplyKeys;
|
|
16
|
-
private recentMessages;
|
|
17
|
-
constructor(onExternalMessage: (sessionId: string, event: ExternalMessageEvent) => void, createReplyTarget: (input: {
|
|
18
|
-
managerSessionId: string;
|
|
19
|
-
channelId: string;
|
|
20
|
-
conversationId: string;
|
|
21
|
-
messageId?: string | null;
|
|
22
|
-
}) => string, options?: ChannelRuntimeOptions);
|
|
23
|
-
start(): Promise<void>;
|
|
24
|
-
stop(): Promise<void>;
|
|
25
|
-
ingest(event: ExternalMessageEvent & {
|
|
26
|
-
managerSessionId?: string;
|
|
27
|
-
}): ExternalMessageEvent;
|
|
28
|
-
reply(input: ExternalReply & {
|
|
29
|
-
managerSessionId: string;
|
|
30
|
-
}): Promise<{
|
|
31
|
-
ok: true;
|
|
32
|
-
pending?: boolean;
|
|
33
|
-
} | {
|
|
34
|
-
ok: false;
|
|
35
|
-
error: string;
|
|
36
|
-
}>;
|
|
37
|
-
private isReplyCompleted;
|
|
38
|
-
private markReplyCompleted;
|
|
39
|
-
private loadReplyCompletionSet;
|
|
40
|
-
getDefaultReplyTarget(sessionId: string): Promise<{
|
|
41
|
-
channelId: string;
|
|
42
|
-
conversationId: string;
|
|
43
|
-
}>;
|
|
44
|
-
getManagerChannel(managerSessionId: string, type: ExternalChannelConfig['type'], opts?: {
|
|
45
|
-
includeSecret?: boolean;
|
|
46
|
-
}): ExternalChannelView | null;
|
|
47
|
-
getChannelById(channelId: string, opts?: {
|
|
48
|
-
includeSecret?: boolean;
|
|
49
|
-
}): ExternalChannelView | null;
|
|
50
|
-
getChannelStatusById(channelId: string): ExternalChannelSessionStatus | null;
|
|
51
|
-
getManagerChannelStatus(managerSessionId: string): ExternalChannelSessionStatus | null;
|
|
52
|
-
listManagerChannelStatuses(): Array<{
|
|
53
|
-
managerSessionId: string;
|
|
54
|
-
status: {
|
|
55
|
-
configured: boolean;
|
|
56
|
-
connected: boolean;
|
|
57
|
-
type?: string;
|
|
58
|
-
channelId?: string;
|
|
59
|
-
name?: string;
|
|
60
|
-
};
|
|
61
|
-
}>;
|
|
62
|
-
listManagerExternalChannels(managerSessionId: string): ExternalChannelSessionStatus[];
|
|
63
|
-
syncManagerWeChatRpaChannel(managerSessionId: string): Promise<{
|
|
64
|
-
channel: ExternalChannelView;
|
|
65
|
-
messages: ExternalMessageEvent[];
|
|
66
|
-
recentMessages: ExternalMessageEvent[];
|
|
67
|
-
}>;
|
|
68
|
-
cancelManagerWeChatRpaOutbound(input: {
|
|
69
|
-
managerSessionId: string;
|
|
70
|
-
idempotencyKey?: string | null;
|
|
71
|
-
replyId?: string | null;
|
|
72
|
-
reason?: string;
|
|
73
|
-
}): Promise<{
|
|
74
|
-
cancelled: boolean;
|
|
75
|
-
status?: string;
|
|
76
|
-
channel: ExternalChannelView;
|
|
77
|
-
}>;
|
|
78
|
-
private recordRecentMessage;
|
|
79
|
-
private findRecentMessageDuplicate;
|
|
80
|
-
private getRecentMessages;
|
|
81
|
-
upsertManagerChannel(input: {
|
|
82
|
-
id: string;
|
|
83
|
-
managerSessionId: string;
|
|
84
|
-
sessionId?: string;
|
|
85
|
-
workDir: string;
|
|
86
|
-
type: 'websocket';
|
|
87
|
-
name?: string;
|
|
88
|
-
agentType?: string;
|
|
89
|
-
agentSessionId?: string | null;
|
|
90
|
-
modelId?: string | null;
|
|
91
|
-
enabled: boolean;
|
|
92
|
-
wsUrl?: string;
|
|
93
|
-
token?: string;
|
|
94
|
-
canReply?: boolean;
|
|
95
|
-
systemPrompt?: string;
|
|
96
|
-
}): Promise<ExternalChannelView>;
|
|
97
|
-
upsertManagerWeChatRpaChannel(input: {
|
|
98
|
-
id: string;
|
|
99
|
-
managerSessionId: string;
|
|
100
|
-
sessionId?: string;
|
|
101
|
-
workDir: string;
|
|
102
|
-
name?: string;
|
|
103
|
-
agentType?: string;
|
|
104
|
-
agentSessionId?: string | null;
|
|
105
|
-
modelId?: string | null;
|
|
106
|
-
enabled: boolean;
|
|
107
|
-
groups: Array<{
|
|
108
|
-
name: string;
|
|
109
|
-
}>;
|
|
110
|
-
canReply?: boolean;
|
|
111
|
-
systemPrompt?: string;
|
|
112
|
-
source?: 'wechat-channel' | 'macos-flow' | 'macos-probe' | 'windows-visual-flow' | 'wechat-rpa-lab' | 'fixture-jsonl';
|
|
113
|
-
pollIntervalMs?: number;
|
|
114
|
-
recentLimit?: number;
|
|
115
|
-
idleSeconds?: number;
|
|
116
|
-
forceForeground?: boolean;
|
|
117
|
-
noRestore?: boolean;
|
|
118
|
-
downloadAttachments?: boolean;
|
|
119
|
-
downloadAttachmentsDir?: string;
|
|
120
|
-
selfNickname?: string;
|
|
121
|
-
selfTriggerMarker?: string;
|
|
122
|
-
deferInitialPoll?: boolean;
|
|
123
|
-
privacyConsentAccepted?: boolean;
|
|
124
|
-
flowScriptPath?: string;
|
|
125
|
-
managedBy?: 'session-sync';
|
|
126
|
-
}): Promise<ExternalChannelView>;
|
|
127
|
-
listChannelIdsManagedBy(managedBy: 'session-sync'): string[];
|
|
128
|
-
deleteManagerWeChatRpaChannel(channelId: string): Promise<{
|
|
129
|
-
removed: boolean;
|
|
130
|
-
}>;
|
|
131
|
-
private findConflictingWeChatRpaBinding;
|
|
132
|
-
}
|
|
133
|
-
export type ExternalReplySendPlanItem = {
|
|
134
|
-
text: string;
|
|
135
|
-
attachment?: ExternalReply['attachment'];
|
|
136
|
-
idempotencyKey?: string;
|
|
137
|
-
};
|
|
138
|
-
export declare function planExternalReplySends(channelType: ExternalChannelConfig['type'], input: Pick<ExternalReply, 'text' | 'attachment' | 'idempotencyKey'>): ExternalReplySendPlanItem[];
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import M from"node:crypto";import h from"node:fs";import u from"node:path";import{ChannelConfigRegistry as P}from"./registry.js";import{ChannelSecretRegistry as N}from"./secret-registry.js";import{WeComChannelAdapter as B}from"./wecom.js";import{WeChatRpaChannelAdapter as D}from"./wechat-rpa.js";import{ExternalWebSocketChannelAdapter as x}from"./websocket.js";import{splitExternalReplyText as W}from"./reply-split.js";class J{onExternalMessage;createReplyTarget;configs=new P;secrets=new N;adapters=new Map;completedReplyKeys=new Map;recentMessages=new Map;constructor(e,t,n={}){this.onExternalMessage=e,this.createReplyTarget=t;const o=new B(r=>this.ingest({...r,type:"external.message"}));this.adapters.set(o.type,o);const a=new x(r=>this.ingest({...r,type:"external.message"}));this.adapters.set(a.type,a);const i=new D(r=>this.ingest(r),{createProductRunner:n.createWeChatRpaProductRunner,automationLane:n.weChatAutomationLane});this.adapters.set(i.type,i)}async start(){for(const e of this.configs.list().filter(t=>t.enabled))await this.adapters.get(e.type)?.connect(e).catch(()=>{})}async stop(){for(const e of this.configs.list())await this.adapters.get(e.type)?.disconnect(e).catch(()=>{})}ingest(e){const t=this.findRecentMessageDuplicate(e);if(t)return t;const n=this.configs.get(e.channelId),o=e.managerSessionId??n?.sessionId??n?.managerSessionId;if(!o)throw new Error(`No session bound for channel ${e.channelId}`);const a=e.replyTarget||this.createReplyTarget({managerSessionId:o,channelId:e.channelId,conversationId:e.conversationId,messageId:e.messageId}),i={...e,replyTarget:a};return this.onExternalMessage(o,i),this.recordRecentMessage(i),i}async reply(e){const t=this.configs.get(e.channelId);if(!t)return{ok:!1,error:`Unknown channel: ${e.channelId}`};if((t.sessionId??t.managerSessionId)!==e.managerSessionId)return{ok:!1,error:"Channel is not bound to this session"};const n=this.adapters.get(t.type);if(!n)return{ok:!1,error:`Unsupported channel type: ${t.type}`};try{const o=F(t.type,e);if(!o.length)return{ok:!1,error:"Reply text or attachment is required"};let a=!1;for(const i of o){const r=i.idempotencyKey;if(r&&this.isReplyCompleted(t,e.conversationId,r))continue;const l=await n.send(t,{...e,...i});if(l?.status==="queued"){a=!0;continue}if(l?.status==="manual-review")return{ok:!1,error:l.reason||"Reply requires manual review before retry"};r&&this.markReplyCompleted(t,e.conversationId,r)}return a?{ok:!0,pending:!0}:{ok:!0}}catch(o){return{ok:!1,error:o instanceof Error?o.message:String(o)}}}isReplyCompleted(e,t,n){return this.loadReplyCompletionSet(e).has(A(e.id,t,n))}markReplyCompleted(e,t,n){const o=this.loadReplyCompletionSet(e);o.add(A(e.id,t,n));try{$(e.workDir,o)}catch{}}loadReplyCompletionSet(e){const t=u.resolve(e.workDir),n=this.completedReplyKeys.get(t);if(n)return n;const o=T(e.workDir);return this.completedReplyKeys.set(t,o),o}async getDefaultReplyTarget(e){const t=this.configs.list().find(a=>(a.sessionId??a.managerSessionId)===e&&a.enabled);if(!t)throw new Error("No enabled external channel is bound to this session");const n=this.adapters.get(t.type);if(!n?.defaultConversation)throw new Error(`External channel ${t.type} has no default conversation`);const o=await n.defaultConversation(t);return{channelId:t.id,conversationId:o.conversationId}}getManagerChannel(e,t,n={}){const o=this.configs.list().filter(l=>(l.sessionId??l.managerSessionId)===e&&l.type===t),a=o.find(l=>l.enabled)??o.at(-1);if(!a)return null;const i=this.secrets.get(a.secretRef),r=this.adapters.get(a.type)?.runtimeStatus?.(a)??{};return{id:a.id,type:a.type,name:a.name,sessionId:a.sessionId??a.managerSessionId,managerSessionId:a.managerSessionId,workDir:a.workDir,agentType:a.agentType,agentSessionId:a.agentSessionId,modelId:a.modelId,enabled:a.enabled,wsUrl:i?.wsUrl??"",token:n.includeSecret?i?.token??"":"",tokenConfigured:!!i?.token,canReply:!!i?.canReply,systemPrompt:typeof i?.systemPrompt=="string"?i.systemPrompt:"",...C(i),...r}}getChannelById(e,t={}){const n=this.configs.get(e);if(!n)return null;const o=this.secrets.get(n.secretRef),a=this.adapters.get(n.type)?.runtimeStatus?.(n)??{};return{id:n.id,type:n.type,name:n.name,sessionId:n.sessionId??n.managerSessionId,managerSessionId:n.managerSessionId,workDir:n.workDir,agentType:n.agentType,agentSessionId:n.agentSessionId,modelId:n.modelId,enabled:n.enabled,wsUrl:o?.wsUrl??"",token:t.includeSecret?o?.token??"":"",tokenConfigured:!!o?.token,canReply:!!o?.canReply,systemPrompt:typeof o?.systemPrompt=="string"?o.systemPrompt:"",...C(o),...a,managedBy:n.managedBy}}getChannelStatusById(e){const t=this.configs.get(e);if(!t)return null;const n=this.secrets.get(t.secretRef),o=this.adapters.get(t.type)?.runtimeStatus?.(t)??{};return{configured:!0,connected:y(t,n),type:t.type,channelId:t.id,name:t.name,canReply:!!n?.canReply,systemPrompt:typeof n?.systemPrompt=="string"?n.systemPrompt:"",...w(n),...o}}getManagerChannelStatus(e){const t=this.configs.list().find(a=>(a.sessionId??a.managerSessionId)===e&&a.enabled);if(!t)return null;const n=this.secrets.get(t.secretRef),o=this.adapters.get(t.type)?.runtimeStatus?.(t)??{};return{configured:!0,connected:y(t,n),type:t.type,channelId:t.id,name:t.name,canReply:!!n?.canReply,systemPrompt:typeof n?.systemPrompt=="string"?n.systemPrompt:"",...w(n),...o}}listManagerChannelStatuses(){return this.configs.list().filter(e=>e.enabled).map(e=>({managerSessionId:e.sessionId??e.managerSessionId,status:this.getManagerChannelStatus(e.sessionId??e.managerSessionId)})).filter(e=>!!e.status)}listManagerExternalChannels(e){return this.configs.list().filter(t=>t.enabled&&(t.sessionId??t.managerSessionId)===e).map(t=>{const n=this.secrets.get(t.secretRef),o=this.adapters.get(t.type)?.runtimeStatus?.(t)??{};return{configured:!0,connected:y(t,n),type:t.type,channelId:t.id,name:t.name,canReply:!!n?.canReply,systemPrompt:typeof n?.systemPrompt=="string"?n.systemPrompt:"",...w(n),...o}})}async syncManagerWeChatRpaChannel(e){const t=this.configs.list().find(r=>r.enabled&&r.type==="wechat-rpa"&&(r.sessionId??r.managerSessionId)===e);if(!t)throw new Error("No enabled WeChat RPA channel is bound to this session");const n=this.adapters.get(t.type);if(!n?.syncNow)throw new Error("WeChat RPA channel does not support manual sync");const o=Date.now()-120*1e3,a=await n.syncNow(t)??[],i=K(a,this.getRecentMessages(t.id,o));return{channel:this.getManagerChannel(e,"wechat-rpa",{includeSecret:!0}),messages:a,recentMessages:i}}async cancelManagerWeChatRpaOutbound(e){const t=this.configs.list().find(a=>a.enabled&&a.type==="wechat-rpa"&&(a.sessionId??a.managerSessionId)===e.managerSessionId);if(!t)throw new Error("No enabled WeChat RPA channel is bound to this session");const n=this.adapters.get(t.type);if(!n?.cancelOutbound)throw new Error("WeChat RPA channel does not support outbound cancellation");const o=await n.cancelOutbound(t,{idempotencyKey:e.idempotencyKey,replyId:e.replyId,reason:e.reason});return{cancelled:o.cancelled,status:o.status,channel:this.getManagerChannel(e.managerSessionId,"wechat-rpa",{includeSecret:!0})}}recordRecentMessage(e){const t=this.recentMessages.get(e.channelId)??[];this.findRecentMessageDuplicate(e)||(t.push(e),this.recentMessages.set(e.channelId,t.slice(-50)))}findRecentMessageDuplicate(e){const t=I(e);return t?(this.recentMessages.get(e.channelId)??[]).find(o=>I(o)===t)??null:null}getRecentMessages(e,t){return(this.recentMessages.get(e)??[]).filter(o=>{const a=Date.parse(o.receivedAt);return!Number.isFinite(a)||a>=t})}async upsertManagerChannel(e){const t=this.configs.get(e.id),n=this.configs.list(),o=e.sessionId||e.managerSessionId,a={id:e.id,type:e.type,name:e.name?.trim()||t?.name||"\u5916\u90E8\u6D88\u606F\u901A\u9053",sessionId:o,managerSessionId:o,workDir:e.workDir,agentType:e.agentType||t?.agentType,agentSessionId:e.agentSessionId??t?.agentSessionId??null,modelId:e.modelId??t?.modelId??null,enabled:e.enabled,secretRef:t?.secretRef||`channel:${e.id}`},i=this.secrets.get(a.secretRef),r=e.wsUrl?.trim()||i?.wsUrl||"",l=e.token?.trim()||i?.token||"",p=e.canReply??i?.canReply??!1,m=e.systemPrompt??(typeof i?.systemPrompt=="string"?i.systemPrompt:"");if(a.enabled&&(!r||!l))throw new Error("WebSocket \u5730\u5740\u548C Token \u5FC5\u586B");const f=n.filter(d=>d.id!==a.id).map(d=>(d.sessionId??d.managerSessionId)===o&&d.type===e.type?{...d,enabled:!1}:d);f.push(a),this.configs.replaceAll(f),(r||l)&&this.secrets.upsert(a.secretRef,{type:"websocket",wsUrl:r,token:l,canReply:p,systemPrompt:m});const c=this.adapters.get(a.type);for(const d of n)(d.sessionId??d.managerSessionId)===o&&d.type===e.type&&d.enabled&&await this.adapters.get(d.type)?.disconnect(d).catch(()=>{});return a.enabled&&c?.connect(a).catch(()=>{}),this.getManagerChannel(o,e.type,{includeSecret:!0})}async upsertManagerWeChatRpaChannel(e){const t=this.configs.get(e.id),n=e.sessionId||e.managerSessionId,o=g(e.groups);if(e.enabled&&!o.length)throw new Error("WeChat RPA \u81F3\u5C11\u9700\u8981\u914D\u7F6E\u4E00\u4E2A\u7FA4");if(e.enabled&&o.length>1)throw new Error("WeChat RPA \u6BCF\u4E2A\u5BF9\u8BDD\u53EA\u80FD\u7ED1\u5B9A\u4E00\u4E2A\u7FA4");if(e.enabled){const c=this.findConflictingWeChatRpaBinding({excludeChannelId:e.id,boundSessionId:n,groupNames:o.map(d=>d.name)});if(c){const d=this.configs.get(c.channelId);if(e.managedBy==="session-sync"&&d?.managedBy==="session-sync")await this.deleteManagerWeChatRpaChannel(c.channelId);else throw new Error(`\u5FAE\u4FE1\u5BF9\u8BDD\u300C${c.groupName}\u300D\u5DF2\u88AB\u53E6\u4E00\u4E2A\u667A\u80FD\u4F53\u7ED1\u5B9A(\u901A\u9053 ${c.channelName}),\u540C\u4E00\u4E2A\u5BF9\u8BDD\u53EA\u80FD\u7ED1\u5B9A\u4E00\u6B21\u3002\u8BF7\u5148\u5728\u539F\u667A\u80FD\u4F53\u89E3\u7ED1,\u518D\u91CD\u65B0\u7ED1\u5B9A\u3002`)}}const a=this.configs.list(),i={id:e.id,type:"wechat-rpa",name:e.name?.trim()||t?.name||"\u672C\u673A\u5FAE\u4FE1 RPA",sessionId:n,managerSessionId:n,workDir:e.workDir,agentType:e.agentType||t?.agentType,agentSessionId:e.agentSessionId??t?.agentSessionId??null,modelId:e.modelId??t?.modelId??null,enabled:e.enabled,secretRef:t?.secretRef||`channel:${e.id}`,managedBy:e.managedBy??t?.managedBy},r=this.secrets.get(i.secretRef),l=e.source||(r?.source==="wechat-channel"||r?.source==="macos-probe"||r?.source==="fixture-jsonl"||r?.source==="macos-flow"||r?.source==="windows-visual-flow"||r?.source==="wechat-rpa-lab"?r.source:E());if(e.enabled&&l==="windows-visual-flow")throw new Error("\u65E7 Windows visual flow \u5DF2\u5F52\u6863\uFF1BmacOS \u548C Windows \u6B63\u5F0F\u901A\u9053\u90FD\u4F7F\u7528 wechat-channel");const p=e.privacyConsentAccepted??!!r?.privacyConsentAccepted;if(e.enabled&&!p)throw new Error("\u542F\u7528\u524D\u9700\u8981\u786E\u8BA4\u5FAE\u4FE1\u901A\u9053\u6570\u636E\u4E0E\u9690\u79C1\u6388\u6743");const m=a.filter(c=>c.id!==i.id).map(c=>(c.sessionId??c.managerSessionId)===n&&c.type==="wechat-rpa"?{...c,enabled:!1}:c);m.push(i),this.configs.replaceAll(m),this.secrets.upsert(i.secretRef,{type:"wechat-rpa",source:l,groups:o,pollIntervalMs:R(e.pollIntervalMs,r?.pollIntervalMs),recentLimit:R(e.recentLimit,r?.recentLimit),idleSeconds:R(e.idleSeconds,r?.idleSeconds),forceForeground:e.forceForeground??(r?.forceForeground===void 0?!0:!!r.forceForeground),noRestore:e.noRestore??(r?.noRestore===void 0?!0:!!r.noRestore),downloadAttachments:e.downloadAttachments??(r?.downloadAttachments===void 0?!0:!!r.downloadAttachments),downloadAttachmentsDir:e.downloadAttachmentsDir?.trim()||b(r?.downloadAttachmentsDir),selfNickname:e.selfNickname?.trim()||b(r?.selfNickname),selfTriggerMarker:e.selfTriggerMarker?.trim()||void 0,deferInitialPoll:e.deferInitialPoll===!0?!0:void 0,privacyConsentAccepted:p,flowScriptPath:e.flowScriptPath?.trim()||b(r?.flowScriptPath),canReply:e.canReply??r?.canReply??!1,systemPrompt:e.systemPrompt??(typeof r?.systemPrompt=="string"?r.systemPrompt:"")});const f=this.adapters.get(i.type);for(const c of a)(c.sessionId??c.managerSessionId)===n&&c.type==="wechat-rpa"&&c.enabled&&await this.adapters.get(c.type)?.disconnect(c).catch(()=>{});return i.enabled&&f?.connect(i).catch(c=>{console.error(`[wechat-rpa] connect failed id=${i.id}: ${c instanceof Error?c.message:String(c)}`)}),this.getManagerChannel(n,"wechat-rpa",{includeSecret:!0})}listChannelIdsManagedBy(e){return this.configs.list().filter(t=>t.managedBy===e).map(t=>t.id)}async deleteManagerWeChatRpaChannel(e){const t=this.configs.get(e);if(!t)return{removed:!1};t.enabled&&await this.adapters.get(t.type)?.disconnect(t).catch(()=>{});const n=this.configs.remove(e);return t.secretRef&&this.secrets.remove(t.secretRef),{removed:n}}findConflictingWeChatRpaBinding(e){const t=new Set(e.groupNames);if(!t.size)return null;for(const n of this.configs.list()){if(n.type!=="wechat-rpa"||!n.enabled||n.id===e.excludeChannelId||(n.sessionId??n.managerSessionId)===e.boundSessionId)continue;const o=this.secrets.get(n.secretRef),a=g(Array.isArray(o?.groups)?o.groups:[]);for(const i of a)if(t.has(i.name))return{channelId:n.id,channelName:n.name||n.id,groupName:i.name}}return null}}function y(s,e){return!e||e.type!==s.type?!1:s.type==="wechat-rpa"?!0:s.type==="websocket"?!!(e.wsUrl&&e.token):s.type==="wecom"?!!(e.token||e.botId||e.secret):!!e.token}function C(s){return!s||s.type!=="wechat-rpa"?{}:{wechatRpaSource:typeof s.source=="string"?s.source:"",wechatRpaGroups:g(Array.isArray(s.groups)?s.groups:[]),pollIntervalMs:Number.isFinite(s.pollIntervalMs)?Number(s.pollIntervalMs):void 0,recentLimit:Number.isFinite(s.recentLimit)?Number(s.recentLimit):void 0,idleSeconds:Number.isFinite(s.idleSeconds)?Number(s.idleSeconds):void 0,forceForeground:s.forceForeground===void 0?!0:!!s.forceForeground,noRestore:s.noRestore===void 0?void 0:!!s.noRestore,downloadAttachments:s.downloadAttachments===void 0?!0:!!s.downloadAttachments,downloadAttachmentsDir:typeof s.downloadAttachmentsDir=="string"?s.downloadAttachmentsDir:"",selfNickname:typeof s.selfNickname=="string"?s.selfNickname:"",wechatRpaPrivacyConsentAccepted:!!s.privacyConsentAccepted,wechatRpaServerDecisionAvailable:!0,wechatRpaPreflightChecks:k(s)}}function w(s){return!s||s.type!=="wechat-rpa"?{}:{wechatRpaSource:typeof s.source=="string"?s.source:null,wechatRpaGroups:g(Array.isArray(s.groups)?s.groups:[]),pollIntervalMs:Number.isFinite(s.pollIntervalMs)?Number(s.pollIntervalMs):null,recentLimit:Number.isFinite(s.recentLimit)?Number(s.recentLimit):null,idleSeconds:Number.isFinite(s.idleSeconds)?Number(s.idleSeconds):null,forceForeground:s.forceForeground===void 0?!0:!!s.forceForeground,noRestore:s.noRestore===void 0?null:!!s.noRestore,downloadAttachments:s.downloadAttachments===void 0?!0:!!s.downloadAttachments,downloadAttachmentsDir:typeof s.downloadAttachmentsDir=="string"?s.downloadAttachmentsDir:null,selfNickname:typeof s.selfNickname=="string"?s.selfNickname:null,wechatRpaPrivacyConsentAccepted:!!s.privacyConsentAccepted,wechatRpaServerDecisionAvailable:!0,wechatRpaPreflightChecks:k(s)}}function g(s){const e=new Set,t=[];for(const n of s){const o=String(n?.name||"").replace(/\s+/g," ").trim();!o||e.has(o)||(e.add(o),t.push({name:o}))}return t}function E(){return"wechat-channel"}function k(s){const e=[];if(s.lastHelperPermissions&&typeof s.lastHelperPermissions=="object"){const t=s.lastHelperPermissions;e.push({code:"wechat_window_unavailable",ok:t.wechatWindowAvailable!==!1,severity:"blocking",message:t.wechatWindowAvailable===!1?"\u5FAE\u4FE1\u7A97\u53E3\u4E0D\u53EF\u7528\uFF0C\u8BF7\u6253\u5F00\u5E76\u767B\u5F55\u5FAE\u4FE1\u540E\u518D\u8BD5\u3002":"\u5FAE\u4FE1\u7A97\u53E3\u53EF\u7528\u3002"})}return e.push({code:"platform_unsupported",ok:s.source!=="windows-visual-flow",severity:"blocking",message:s.source==="windows-visual-flow"?"\u65E7 Windows visual flow \u5DF2\u5F52\u6863\uFF0C\u8BF7\u6539\u7528 wechat-channel\u3002":"\u5F53\u524D\u914D\u7F6E\u4F7F\u7528\u8DE8\u5E73\u53F0\u5FAE\u4FE1\u901A\u9053\u3002"}),e.push({code:"privacy_consent_required",ok:!!s.privacyConsentAccepted,severity:"blocking",message:s.privacyConsentAccepted?"\u5DF2\u786E\u8BA4\u5FAE\u4FE1\u901A\u9053\u6570\u636E\u4E0E\u9690\u79C1\u6388\u6743\u3002":"\u542F\u7528\u524D\u9700\u8981\u786E\u8BA4\u5FAE\u4FE1\u901A\u9053\u6570\u636E\u4E0E\u9690\u79C1\u6388\u6743\u3002"}),e.push({code:"server_decision_unavailable",ok:!0,severity:"blocking",message:"\u670D\u52A1\u7AEF\u5224\u65AD\u80FD\u529B\u53EF\u7528\u3002"}),e}function F(s,e){const t=W(e.text);if(!t.length&&!e.attachment)return[];if(s==="wechat-rpa"&&e.attachment&&t.length<=1)return[{text:t[0]??"",attachment:e.attachment,idempotencyKey:e.idempotencyKey}];const n=t.map((o,a)=>({text:o,attachment:void 0,idempotencyKey:t.length>1&&e.idempotencyKey?`${e.idempotencyKey}:${a+1}`:e.idempotencyKey}));return e.attachment&&n.push({text:"",attachment:e.attachment,idempotencyKey:t.length&&e.idempotencyKey?`${e.idempotencyKey}:attachment`:e.idempotencyKey}),n}function K(...s){const e=new Set,t=[];for(const n of s.flat()){const o=I(n);if(!o){t.push(n);continue}e.has(o)||(e.add(o),t.push(n))}return t}function I(s){const e=S(s.channelId),t=S(s.conversationId),n=S(s.messageId);return!e||!t||!n?null:`${e}
|
|
2
|
-
${t}
|
|
3
|
-
${n}`}function S(s){return typeof s=="string"?s.trim():""}function A(s,e,t){return M.createHash("sha256").update(`${s}
|
|
4
|
-
${e}
|
|
5
|
-
${t}`).digest("hex").slice(0,32)}function v(s){return u.join(s,".shennian","external-reply-idempotency.json")}function T(s){try{const e=JSON.parse(h.readFileSync(v(s),"utf8")),t=Array.isArray(e.completed)?e.completed:[];return new Set(t.map(n=>typeof n=="string"?n:n&&typeof n=="object"&&typeof n.key=="string"?n.key:"").filter(Boolean))}catch{return new Set}}function $(s,e){const t=v(s);h.mkdirSync(u.dirname(t),{recursive:!0});const n=Array.from(e).slice(-500);h.writeFileSync(t,JSON.stringify({updatedAt:new Date().toISOString(),completed:n.map(o=>({key:o}))},null,2)),e.clear();for(const o of n)e.add(o)}function R(s,e){const t=Number(s??e);return Number.isFinite(t)&&t>=0?t:void 0}function b(s){return typeof s=="string"&&s.trim()?s.trim():void 0}export{J as ChannelRuntime,F as planExternalReplySends};
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
type ChannelSecretRecord = {
|
|
2
|
-
type: 'wecom' | 'websocket' | 'wechat-rpa';
|
|
3
|
-
botId?: string;
|
|
4
|
-
secret?: string;
|
|
5
|
-
wsUrl?: string;
|
|
6
|
-
token?: string;
|
|
7
|
-
canReply?: boolean;
|
|
8
|
-
systemPrompt?: string;
|
|
9
|
-
source?: 'wechat-channel' | 'macos-probe' | 'macos-flow' | 'windows-visual-flow' | 'wechat-rpa-lab' | 'fixture-jsonl';
|
|
10
|
-
fixturePath?: string;
|
|
11
|
-
pollIntervalMs?: number;
|
|
12
|
-
groups?: Array<{
|
|
13
|
-
name: string;
|
|
14
|
-
}>;
|
|
15
|
-
forceForeground?: boolean;
|
|
16
|
-
noRestore?: boolean;
|
|
17
|
-
downloadAttachments?: boolean;
|
|
18
|
-
downloadAttachmentsDir?: string;
|
|
19
|
-
selfNickname?: string;
|
|
20
|
-
selfTriggerMarker?: string;
|
|
21
|
-
deferInitialPoll?: boolean;
|
|
22
|
-
privacyConsentAccepted?: boolean;
|
|
23
|
-
idleSeconds?: number;
|
|
24
|
-
recentLimit?: number;
|
|
25
|
-
flowScriptPath?: string;
|
|
26
|
-
updatedAt: string;
|
|
27
|
-
};
|
|
28
|
-
export declare class ChannelSecretRegistry {
|
|
29
|
-
private load;
|
|
30
|
-
private save;
|
|
31
|
-
get(secretRef: string): ChannelSecretRecord | undefined;
|
|
32
|
-
upsert(secretRef: string, value: Omit<ChannelSecretRecord, 'updatedAt'>): ChannelSecretRecord;
|
|
33
|
-
remove(secretRef: string): void;
|
|
34
|
-
}
|
|
35
|
-
export {};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import r from"node:fs";import o from"node:path";import{resolveShennianPath as i}from"../config/index.js";function s(){return i("channels.secrets.json")}function a(){return new Date().toISOString()}function u(){return{secrets:{}}}class f{load(){try{return{secrets:JSON.parse(r.readFileSync(s(),"utf-8")).secrets??{}}}catch{return u()}}save(e){r.mkdirSync(o.dirname(s()),{recursive:!0}),r.writeFileSync(s(),JSON.stringify(e,null,2),{mode:384});try{r.chmodSync(s(),384)}catch{}}get(e){return this.load().secrets[e]}upsert(e,t){const n=this.load(),c={...t,updatedAt:a()};return n.secrets[e]=c,this.save(n),c}remove(e){const t=this.load();e in t.secrets&&(delete t.secrets[e],this.save(t))}}export{f as ChannelSecretRegistry};
|
|
@@ -1,55 +0,0 @@
|
|
|
1
|
-
import type { ExternalChannelAdapter, ExternalChannelConfig, ExternalReply } from './base.js';
|
|
2
|
-
export declare class ExternalWebSocketChannelAdapter implements ExternalChannelAdapter {
|
|
3
|
-
private onMessage?;
|
|
4
|
-
readonly type: "websocket";
|
|
5
|
-
private secrets;
|
|
6
|
-
private connections;
|
|
7
|
-
constructor(onMessage?: ((event: {
|
|
8
|
-
managerSessionId: string;
|
|
9
|
-
channelId: string;
|
|
10
|
-
channelType: "websocket";
|
|
11
|
-
conversationId: string;
|
|
12
|
-
messageId: string;
|
|
13
|
-
sender: {
|
|
14
|
-
id: string;
|
|
15
|
-
name?: string | null;
|
|
16
|
-
};
|
|
17
|
-
text: string;
|
|
18
|
-
attachments: Array<{
|
|
19
|
-
type: string;
|
|
20
|
-
name?: string;
|
|
21
|
-
url?: string;
|
|
22
|
-
mimeType?: string;
|
|
23
|
-
size?: number;
|
|
24
|
-
}>;
|
|
25
|
-
receivedAt: string;
|
|
26
|
-
replyTarget: string;
|
|
27
|
-
}) => void) | undefined);
|
|
28
|
-
connect(config: ExternalChannelConfig): Promise<void>;
|
|
29
|
-
disconnect(config: ExternalChannelConfig): Promise<void>;
|
|
30
|
-
send(config: ExternalChannelConfig, reply: ExternalReply): Promise<void>;
|
|
31
|
-
health(config: ExternalChannelConfig): Promise<{
|
|
32
|
-
ok: boolean;
|
|
33
|
-
message?: string;
|
|
34
|
-
}>;
|
|
35
|
-
defaultConversation(config: ExternalChannelConfig): Promise<{
|
|
36
|
-
conversationId: string;
|
|
37
|
-
conversationName?: string;
|
|
38
|
-
}>;
|
|
39
|
-
private ensureConnection;
|
|
40
|
-
private readSecret;
|
|
41
|
-
private openConnection;
|
|
42
|
-
private scheduleReconnect;
|
|
43
|
-
private sendJson;
|
|
44
|
-
private sendAwaitAck;
|
|
45
|
-
private handlePayload;
|
|
46
|
-
private buildVisibleText;
|
|
47
|
-
private batchMessageKey;
|
|
48
|
-
private hasSeenBatchMessage;
|
|
49
|
-
private rememberBatchMessage;
|
|
50
|
-
private normalizeAttachments;
|
|
51
|
-
private formatAttachment;
|
|
52
|
-
private formatMessageTime;
|
|
53
|
-
private isDuplicate;
|
|
54
|
-
private parsePayload;
|
|
55
|
-
}
|
|
@@ -1,8 +0,0 @@
|
|
|
1
|
-
import{randomUUID as w}from"node:crypto";import u from"ws";import{ChannelSecretRegistry as S}from"./secret-registry.js";const l=[2e3,5e3,1e4,3e4],y=3e4,k=15e3;class M{onMessage;type="websocket";secrets=new S;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 n of t.pendingAcks.values())clearTimeout(n.timer),n.reject(new Error("External websocket adapter disconnected"));t.pendingAcks.clear();const s=t.socket;t.socket=null,s&&await new Promise(n=>{s.once("close",()=>n()),s.close(),setTimeout(n,500)}),this.connections.delete(e.id)}async send(e,t){const s=this.ensureConnection(e);if(this.readSecret(e).canReply===!1)throw new Error("External websocket channel does not allow replies");await this.connect(e);const r=t.idempotencyKey||`send_${w()}`;await this.sendAwaitAck(s,r,{type:"message.send",requestId:r,conversationId:t.conversationId,contentType:"text",text:t.text,replyToMessageId:t.messageId??void 0})}async health(e){const t=this.readSecret(e);return!t.wsUrl||!t.token?{ok:!1,message:"External websocket requires local wsUrl and token"}:this.connections.get(e.id)?.socket?.readyState===u.OPEN?{ok:!0}:{ok:!1,message:"External websocket disconnected"}}async defaultConversation(e){const t=this.readSecret(e),s=new URL(t.wsUrl);s.protocol=s.protocol==="wss:"?"https:":"http:",s.pathname=s.pathname.replace(/\/ws\/?$/,"/subscription/self"),s.search="";const n=await fetch(s,{headers:{Authorization:`Bearer ${t.token}`}}),r=await n.json().catch(()=>null);if(!n.ok||!r?.ok)throw new Error(r?.error||`External websocket metadata failed: ${n.status}`);if(r.subscription?.allowSend===!1)throw new Error("External websocket subscription does not allow send");const o=String(r.subscription?.defaultConversationId||"").trim();if(!o)throw new Error("External websocket subscription has no single default conversation");return{conversationId:o,conversationName:String(r.subscription?.defaultConversationName||"").trim()||void 0}}ensureConnection(e){let t=this.connections.get(e.id);return t||(t={config:e,socket:null,connecting:null,stopped:!1,reconnectAttempt:0,reconnectTimer:null,pingTimer:null,dedup:new Set,dedupQueue:[],seenBatchMessageKeys:new Set,seenBatchMessageQueue:[],pendingAcks:new Map},this.connections.set(e.id,t)),t.config=e,t}readSecret(e){const t=this.secrets.get(e.secretRef);if(!t||t.type!=="websocket"||!t.wsUrl||!t.token)throw new Error("External websocket channel is not configured on this daemon");return t}async openConnection(e){const t=this.readSecret(e.config),s=t.wsUrl,n=new u(s,{headers:{Authorization:`Bearer ${t.token}`}});e.socket=n,await new Promise((r,o)=>{const i=()=>{n.off("open",c),n.off("error",a)},c=()=>{i(),r()},a=d=>{i(),o(d)};n.once("open",c),n.once("error",a)}),n.on("message",r=>{const o=this.parsePayload(r.toString());o&&this.handlePayload(e,o)}),n.on("close",()=>this.scheduleReconnect(e)),n.on("error",()=>this.scheduleReconnect(e)),e.reconnectAttempt=0,e.pingTimer&&clearInterval(e.pingTimer),e.pingTimer=setInterval(()=>{this.sendJson(e,{type:"ping",timestamp:new Date().toISOString()}).catch(()=>{})},y),e.pingTimer.unref()}scheduleReconnect(e){if(e.stopped||e.reconnectTimer||e.connecting)return;const t=l[Math.min(e.reconnectAttempt,l.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("External websocket is not connected");e.socket.send(JSON.stringify(t))}async sendAwaitAck(e,t,s){await new Promise((n,r)=>{const o=setTimeout(()=>{e.pendingAcks.delete(t),r(new Error("External websocket send timed out"))},k);o.unref(),e.pendingAcks.set(t,{resolve:n,reject:r,timer:o}),this.sendJson(e,s).catch(i=>{clearTimeout(o),e.pendingAcks.delete(t),r(i instanceof Error?i:new Error(String(i)))})})}handlePayload(e,t){const s=String(t.type||"");if(s==="ack"||s==="error"){const c=String(t.requestId||""),a=c?e.pendingAcks.get(c):void 0;if(!a)return;clearTimeout(a.timer),e.pendingAcks.delete(c),s==="ack"&&t.ok!==!1?a.resolve():a.reject(new Error(String(t.error||"External websocket send failed")));return}if(s==="hello"||s==="pong"||s!=="message.inbound"&&s!=="message.inbound.batch")return;const n=String(t.messageId||t.batchId||t.id||"");if(!n||this.isDuplicate(e,n))return;const r=this.normalizeAttachments(t),o=this.buildVisibleText(e,t,r),i=String(t.conversationId||"").trim();Array.isArray(t.messages)&&!o||!o&&r.length===0||!i||this.onMessage?.({managerSessionId:e.config.managerSessionId,channelId:e.config.id,channelType:"websocket",conversationId:i,messageId:n,sender:{id:String(t.senderId||"unknown"),name:typeof t.senderName=="string"?t.senderName:null},text:o,attachments:r,receivedAt:typeof t.endedAt=="string"?t.endedAt:new Date().toISOString(),replyTarget:""})}buildVisibleText(e,t,s){const n=String(t.text||"").trim();return n||(Array.isArray(t.messages)?t.messages.map((r,o)=>{if(!r||typeof r!="object")return"";const i=r,c=this.batchMessageKey(i,t);if(c&&this.hasSeenBatchMessage(e,c))return"";const a=String(i.conversationType||t.conversationType||"")==="group",d=String(i.senderName||(a?"\u7FA4\u53CB":i.senderExternalId||i.senderId||"unknown")),m=this.formatMessageTime(i.timestampIso||i.timestamp),h=String(i.text||"").trim(),g=this.normalizeAttachments(i).map(f=>this.formatAttachment(f)).join(" "),p=[h,g].filter(Boolean).join(" ").trim()||`[${String(i.contentType||"message")}]`;return c&&this.rememberBatchMessage(e,c),`${o+1}. ${m} ${d}: ${p}`}).filter(Boolean).join(`
|
|
2
|
-
`).trim():s.map(r=>this.formatAttachment(r)).join(`
|
|
3
|
-
`))}batchMessageKey(e,t){const s=String(e.messageId||e.msgid||e.id||e.rawId||"").trim();if(s)return`id:${s}`;const n=String(e.senderExternalId||e.senderId||e.senderName||"").trim(),r=String(e.timestampIso||e.timestamp||e.receivedAt||"").trim(),o=String(e.text||"").trim(),i=String(e.contentType||"").trim(),c=String(e.conversationId||t.conversationId||"").trim(),a=this.normalizeAttachments(e).map(d=>[d.type,d.name||"",d.url||"",d.size??""].join(":")).join("|");return`content:${c}
|
|
4
|
-
${n}
|
|
5
|
-
${r}
|
|
6
|
-
${i}
|
|
7
|
-
${o}
|
|
8
|
-
${a}`}hasSeenBatchMessage(e,t){return e.seenBatchMessageKeys.has(t)}rememberBatchMessage(e,t){if(!e.seenBatchMessageKeys.has(t))for(e.seenBatchMessageKeys.add(t),e.seenBatchMessageQueue.push(t);e.seenBatchMessageQueue.length>2e3;){const s=e.seenBatchMessageQueue.shift();s&&e.seenBatchMessageKeys.delete(s)}}normalizeAttachments(e){const t=Array.isArray(e.attachments)?e.attachments:[],s=Array.isArray(e.messages)?e.messages.flatMap(n=>{if(!n||typeof n!="object")return[];const r=n;return Array.isArray(r.attachments)?r.attachments:[]}):[];return[...t,...s].filter(n=>!!n&&typeof n=="object").map(n=>({type:String(n.type||"file"),name:typeof n.name=="string"?n.name:void 0,url:typeof n.url=="string"?n.url:void 0,mimeType:typeof n.mimeType=="string"?n.mimeType:void 0,size:typeof n.size=="number"?n.size:void 0}))}formatAttachment(e){const t=e.name?`${e.type}: ${e.name}`:e.type;return e.url?`[${t} ${e.url}]`:`[${t}]`}formatMessageTime(e){const t=typeof e=="number"?new Date(e<1e10?e*1e3:e):new Date(String(e||""));return Number.isNaN(t.getTime())?String(e||""):new Intl.DateTimeFormat("zh-CN",{timeZone:"Asia/Shanghai",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1}).format(t).replace(/\//g,"-")}isDuplicate(e,t){if(e.dedup.has(t))return!0;if(e.dedup.add(t),e.dedupQueue.push(t),e.dedupQueue.length>1e3){const s=e.dedupQueue.shift();s&&e.dedup.delete(s)}return!1}parsePayload(e){try{const t=JSON.parse(e);return t&&typeof t=="object"?t:null}catch{return null}}}export{M as ExternalWebSocketChannelAdapter};
|
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import type { WeChatChannelObservedMessage } from './client.js';
|
|
2
|
-
export declare function normalizeWeChatAnchorText(value: unknown): string;
|
|
3
|
-
export declare function weChatAnchorText(message: WeChatChannelObservedMessage): string;
|
|
4
|
-
export declare function weChatTextSimilarity(left: unknown, right: unknown): number;
|
|
5
|
-
export declare function isLikelySameWeChatMessage(previous: WeChatChannelObservedMessage, current: WeChatChannelObservedMessage, threshold?: number): boolean;
|
|
6
|
-
export declare function filterNewWeChatMessagesByAnchor(input: {
|
|
7
|
-
previous: WeChatChannelObservedMessage[];
|
|
8
|
-
current: WeChatChannelObservedMessage[];
|
|
9
|
-
threshold?: number;
|
|
10
|
-
}): WeChatChannelObservedMessage[];
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function i(e){return typeof e!="string"?"":e.normalize("NFKC").replace(/\s+/g," ").trim().toLowerCase()}function a(e){return i(e.anchorText||e.normalizedText||e.textExcerpt||"")}function l(e,t){const o=i(e),r=i(t);return!o||!r?0:o===r?1:1-f(o,r)/Math.max(o.length,r.length)}function h(e,t,o=.95){if(e.stableMessageKey&&e.stableMessageKey===t.stableMessageKey)return!0;if(e.senderRole!==t.senderRole||e.kind!==t.kind)return!1;const r=a(e),s=a(t);return!r||!s?!1:l(r,s)>=o}function u(e){const t=new Set,o=[];for(const r of e.current){const s=e.previous.findIndex((n,c)=>!t.has(c)&&h(n,r,e.threshold));if(s>=0){t.add(s);continue}o.push(r)}return o}function f(e,t){const o=Array.from({length:t.length+1},(s,n)=>n),r=Array.from({length:t.length+1},()=>0);for(let s=1;s<=e.length;s+=1){r[0]=s;for(let n=1;n<=t.length;n+=1)r[n]=Math.min(o[n]+1,r[n-1]+1,o[n-1]+(e[s-1]===t[n-1]?0:1));for(let n=0;n<=t.length;n+=1)o[n]=r[n]}return o[t.length]}export{u as filterNewWeChatMessagesByAnchor,h as isLikelySameWeChatMessage,i as normalizeWeChatAnchorText,a as weChatAnchorText,l as weChatTextSimilarity};
|
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
export type WeChatAutomationLaneRunOptions = {
|
|
2
|
-
waitMs?: number;
|
|
3
|
-
};
|
|
4
|
-
export type WeChatAutomationLane = {
|
|
5
|
-
run<T>(label: string, operation: () => Promise<T>, options?: WeChatAutomationLaneRunOptions): Promise<T>;
|
|
6
|
-
snapshot(): WeChatAutomationLaneSnapshot;
|
|
7
|
-
};
|
|
8
|
-
export type WeChatAutomationLaneSnapshot = {
|
|
9
|
-
active: boolean;
|
|
10
|
-
queued: number;
|
|
11
|
-
lastLabel: string | null;
|
|
12
|
-
lockPath?: string;
|
|
13
|
-
};
|
|
14
|
-
export type WeChatAutomationLaneOptions = {
|
|
15
|
-
lockPath?: string;
|
|
16
|
-
staleMs?: number;
|
|
17
|
-
owner?: string;
|
|
18
|
-
defaultWaitMs?: number;
|
|
19
|
-
};
|
|
20
|
-
export declare class SerialWeChatAutomationLane implements WeChatAutomationLane {
|
|
21
|
-
private tail;
|
|
22
|
-
private active;
|
|
23
|
-
private queued;
|
|
24
|
-
private lastLabel;
|
|
25
|
-
private readonly lockPath?;
|
|
26
|
-
private readonly staleMs;
|
|
27
|
-
private readonly owner;
|
|
28
|
-
private readonly defaultWaitMs;
|
|
29
|
-
constructor(options?: WeChatAutomationLaneOptions);
|
|
30
|
-
run<T>(label: string, operation: () => Promise<T>, options?: WeChatAutomationLaneRunOptions): Promise<T>;
|
|
31
|
-
snapshot(): WeChatAutomationLaneSnapshot;
|
|
32
|
-
private acquireLockWithWait;
|
|
33
|
-
}
|
|
34
|
-
export declare function createWeChatAutomationLane(options?: WeChatAutomationLaneOptions): WeChatAutomationLane;
|
|
35
|
-
export declare function defaultWeChatAutomationLockPath(): string;
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{AsyncLocalStorage as L}from"node:async_hooks";import i from"node:fs";import m from"node:os";import u from"node:path";import{resolveShennianPath as P}from"../../config/index.js";const h=new L,w=900*1e3,p=3e4,y=100,A=1e3;class M{tail=Promise.resolve();active=!1;queued=0;lastLabel=null;lockPath;staleMs;owner;defaultWaitMs;constructor(t={}){this.lockPath=t.lockPath,this.staleMs=t.staleMs??w,this.owner=t.owner??`${process.platform}:${process.pid}`,this.defaultWaitMs=t.defaultWaitMs??p}async run(t,a,r={}){if(this.lockPath&&h.getStore()?.has(this.lockPath))return this.lastLabel=t,a();const n=Math.max(0,r.waitMs??this.defaultWaitMs);this.queued+=1;const o=this.tail;let s;this.tail=new Promise(l=>{s=l}),await o.catch(()=>{}),this.queued-=1,this.active=!0,this.lastLabel=t;const c=Date.now()+n;let f=null;try{if(f=await this.acquireLockWithWait(t,c),!this.lockPath)return await a();const l=h.getStore(),d=new Set(l??[]);return d.add(this.lockPath),await h.run(d,a)}finally{f?.release(),this.active=!1,s()}}snapshot(){return{active:this.active,queued:this.queued,lastLabel:this.lastLabel,lockPath:this.lockPath}}async acquireLockWithWait(t,a){if(!this.lockPath)return null;i.mkdirSync(u.dirname(this.lockPath),{recursive:!0});let r=y,n=null;for(;;)try{return i.mkdirSync(this.lockPath),O(this.lockPath,{pid:process.pid,label:t,owner:this.owner,hostname:m.hostname(),startedAt:new Date().toISOString()}),{release:()=>{i.rmSync(this.lockPath,{recursive:!0,force:!0})}}}catch(o){if(!b(o))throw o;const s=W(this.lockPath);if(n=s,v(this.lockPath,s,this.staleMs)){i.rmSync(this.lockPath,{recursive:!0,force:!0});continue}const c=a-Date.now();if(c<=0)throw new Error(T(this.lockPath,n));await _(Math.min(r,c)),r=Math.min(r*2,A)}}}function j(e={}){return new M({lockPath:S(),...e})}function S(){return P("runtime","wechat-automation.lock")}function _(e){return new Promise(t=>setTimeout(t,e))}function O(e,t){i.writeFileSync(u.join(e,"owner.json"),`${JSON.stringify(t,null,2)}
|
|
2
|
-
`,"utf8")}function W(e){try{const t=JSON.parse(i.readFileSync(u.join(e,"owner.json"),"utf8"));return t&&typeof t=="object"?t:null}catch{return null}}function v(e,t,a){if(t?.pid&&k(t.pid))return!1;if(t?.pid&&E(t)&&!k(t.pid))return!0;try{return Date.now()-i.statSync(e).mtimeMs>a}catch{return!0}}function E(e){return e?.hostname?e.hostname===m.hostname():!1}function k(e){if(!Number.isInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch{return!1}}function T(e,t){return`wechat_automation_busy: another WeChat automation run is active (${[`lock=${e}`,t?.pid?`pid=${t.pid}`:"",t?.label?`label=${t.label}`:"",t?.startedAt?`startedAt=${t.startedAt}`:"",t?.owner?`owner=${t.owner}`:""].filter(Boolean).join(" ")})`}function b(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="EEXIST"}export{M as SerialWeChatAutomationLane,j as createWeChatAutomationLane,S as defaultWeChatAutomationLockPath};
|