@wanji_dsh/dsh-sales 0.10.6 → 0.11.1
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.zh.md +3 -1
- package/dist/client.js +508 -169
- package/dist/host.js +1434 -787
- package/dist/types/company/host.d.ts +45 -0
- package/dist/types/company/identity.d.ts +23 -0
- package/dist/types/company/remote.d.ts +36 -0
- package/dist/types/generation-runtime.d.ts +9 -1
- package/dist/types/knowledge-host.d.ts +3 -0
- package/dist/types/wechat/batch.d.ts +2 -0
- package/dist/types/wechat/native.d.ts +6 -0
- package/dist/types/wechat/receiver.d.ts +12 -4
- package/dist/types/wechat/repository-client.d.ts +1 -1
- package/dist/types/wechat/service.d.ts +8 -0
- package/dist/types/wechat/types.d.ts +14 -0
- package/dist/types/wechat-draft-input.d.ts +2 -0
- package/dist/types/weknora-http.d.ts +1 -0
- package/dist/types/weknora-retrieval.d.ts +22 -0
- package/dist/wechat-repository-worker.js +58 -12
- package/docs/wechat-native-implementation.md +1 -1
- package/docs/wechat-sync.md +1 -1
- package/package.json +1 -1
- package/runtime/wechat-manifest.json +16 -16
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { HostContext } from '../knowledge-host.ts';
|
|
2
|
+
import { type CompanyBindingHint } from './identity.ts';
|
|
3
|
+
export type VerifiedIdentity = {
|
|
4
|
+
status: 'unavailable' | 'unbound' | 'ineligible';
|
|
5
|
+
} | {
|
|
6
|
+
status: 'awaiting';
|
|
7
|
+
authorizeUrl: string;
|
|
8
|
+
verificationCode?: string;
|
|
9
|
+
} | {
|
|
10
|
+
status: 'bound';
|
|
11
|
+
alias: string;
|
|
12
|
+
company?: string;
|
|
13
|
+
department?: string;
|
|
14
|
+
position?: string;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* The company account integration owns credential storage and verification.
|
|
18
|
+
* Every request on its registered model provider must enforce current permission.
|
|
19
|
+
*/
|
|
20
|
+
export interface SalesCompanyIdentity {
|
|
21
|
+
readonly authorizeOrigin: string;
|
|
22
|
+
refresh(signal: AbortSignal): Promise<VerifiedIdentity>;
|
|
23
|
+
begin(hint: CompanyBindingHint, signal: AbortSignal): Promise<VerifiedIdentity>;
|
|
24
|
+
unbind(signal: AbortSignal): Promise<void>;
|
|
25
|
+
canUseSharedModel(): boolean;
|
|
26
|
+
}
|
|
27
|
+
type ModelSelection = {
|
|
28
|
+
provider: string;
|
|
29
|
+
model: string;
|
|
30
|
+
reasoningEffort?: string;
|
|
31
|
+
};
|
|
32
|
+
export declare function resolveCompanySalesModel(service: SalesCompanyIdentity | undefined, companyModelReady: boolean, local?: ModelSelection): {
|
|
33
|
+
readonly provider: "wanji-sales-company-flash";
|
|
34
|
+
readonly model: "deepseek-v4.1-flash";
|
|
35
|
+
} | ModelSelection | undefined;
|
|
36
|
+
export interface AccountProfileReader {
|
|
37
|
+
getProfile(client: {
|
|
38
|
+
version: string;
|
|
39
|
+
locale: string;
|
|
40
|
+
timezoneOffsetSeconds: number;
|
|
41
|
+
}): Promise<unknown>;
|
|
42
|
+
}
|
|
43
|
+
export declare function readAccountPhone(account: AccountProfileReader | undefined): Promise<string | undefined>;
|
|
44
|
+
export declare function registerCompanyIdentityRoute(ctx: HostContext, findService: () => SalesCompanyIdentity | undefined, modelReady: () => boolean, account?: () => AccountProfileReader | undefined): void;
|
|
45
|
+
export {};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export declare const COMPANY_IDENTITY_ENDPOINT = "wanji-sales-company/identity";
|
|
2
|
+
export declare const COMPANY_FLASH: {
|
|
3
|
+
readonly provider: "wanji-sales-company-flash";
|
|
4
|
+
readonly model: "deepseek-v4.1-flash";
|
|
5
|
+
};
|
|
6
|
+
export interface CompanyBindingHint {
|
|
7
|
+
alias?: string;
|
|
8
|
+
phone?: string;
|
|
9
|
+
}
|
|
10
|
+
export type CompanyIdentityView = {
|
|
11
|
+
status: 'unavailable' | 'unbound' | 'ineligible';
|
|
12
|
+
} | {
|
|
13
|
+
status: 'awaiting';
|
|
14
|
+
authorizeUrl: string;
|
|
15
|
+
verificationCode?: string;
|
|
16
|
+
} | {
|
|
17
|
+
status: 'bound';
|
|
18
|
+
alias: string;
|
|
19
|
+
company?: string;
|
|
20
|
+
department?: string;
|
|
21
|
+
position?: string;
|
|
22
|
+
modelReady: boolean;
|
|
23
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { SalesCompanyIdentity } from './host.ts';
|
|
2
|
+
export declare const COMPANY_ORIGIN = "https://wanjidazi.com";
|
|
3
|
+
interface CredentialStore {
|
|
4
|
+
resolve(ref: string): Promise<{
|
|
5
|
+
value: string;
|
|
6
|
+
source: string;
|
|
7
|
+
} | undefined>;
|
|
8
|
+
set(ref: string, value: string): Promise<void>;
|
|
9
|
+
unset(ref: string): Promise<void>;
|
|
10
|
+
}
|
|
11
|
+
interface Settings {
|
|
12
|
+
describe(options: {
|
|
13
|
+
redactSecrets: true;
|
|
14
|
+
}): {
|
|
15
|
+
ns: string;
|
|
16
|
+
revision: number;
|
|
17
|
+
value: unknown;
|
|
18
|
+
base?: unknown;
|
|
19
|
+
user?: unknown;
|
|
20
|
+
}[];
|
|
21
|
+
update(ns: string, patch: object, revision: number): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
interface Connection {
|
|
24
|
+
credentials: CredentialStore;
|
|
25
|
+
settings: Settings;
|
|
26
|
+
fetch?: typeof fetch;
|
|
27
|
+
}
|
|
28
|
+
export declare function createCompanyConnection({ credentials, settings, fetch: request }: Connection): {
|
|
29
|
+
identity: SalesCompanyIdentity;
|
|
30
|
+
ready: () => boolean;
|
|
31
|
+
};
|
|
32
|
+
export declare function companyConnectionFor(credentials: unknown, settings: unknown): {
|
|
33
|
+
identity: SalesCompanyIdentity;
|
|
34
|
+
ready: () => boolean;
|
|
35
|
+
} | undefined;
|
|
36
|
+
export {};
|
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
import type { GenerationServices } from './generation-sessions.ts';
|
|
2
2
|
export declare const SALES_GENERATION_PRESET = "wanji-sales-generation";
|
|
3
|
+
type GenerationModel = {
|
|
4
|
+
provider: string;
|
|
5
|
+
model: string;
|
|
6
|
+
reasoningEffort?: string;
|
|
7
|
+
};
|
|
3
8
|
/** Permanent product-owned composition; never borrows the coding preset or its AGENTS/tools. */
|
|
4
9
|
export declare function createGenerationRuntime(sdk: {
|
|
5
10
|
agents: any;
|
|
6
11
|
presets: any;
|
|
7
|
-
defaults:
|
|
12
|
+
defaults: {
|
|
13
|
+
currentSelection(): GenerationModel | undefined;
|
|
14
|
+
};
|
|
8
15
|
registry: any;
|
|
9
16
|
titles?: {
|
|
10
17
|
rename(session: any, title: string): unknown;
|
|
@@ -15,3 +22,4 @@ export declare function createGenerationRuntime(sdk: {
|
|
|
15
22
|
}): GenerationServices & {
|
|
16
23
|
close(): Promise<void>;
|
|
17
24
|
};
|
|
25
|
+
export {};
|
|
@@ -64,6 +64,9 @@ export interface KnowledgeConfig {
|
|
|
64
64
|
materialKnowledgeBaseId?: string;
|
|
65
65
|
materialAssetBaseUrl?: string;
|
|
66
66
|
materialMetadata?: WeKnoraConnection;
|
|
67
|
+
knowledgeConnection?: WeKnoraConnection;
|
|
68
|
+
materialConnection?: WeKnoraConnection;
|
|
69
|
+
draftKnowledgeEnabled?: boolean;
|
|
67
70
|
langfuseConfigFile?: string;
|
|
68
71
|
evaluation?: EvaluationConnection;
|
|
69
72
|
toolVersion: string;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export declare const SALES_BATCH_SCHEMA = "wanji.wechat.batch.v1";
|
|
2
|
+
export declare function isFocusedTextBatch(raw: unknown): boolean;
|
|
2
3
|
export declare const SALES_MESSAGE_KINDS: readonly ["text", "image", "voice", "video", "location", "call", "emoji", "link", "file", "mini_program", "transfer", "red_packet", "quote", "system", "unknown"];
|
|
3
4
|
export type SalesMessageKind = typeof SALES_MESSAGE_KINDS[number];
|
|
4
5
|
export type SalesMessageDirection = 'inbound' | 'outbound' | 'system';
|
|
@@ -66,6 +67,7 @@ export interface SalesBatch {
|
|
|
66
67
|
protocol: 'wanji.media-patch.v1';
|
|
67
68
|
phase: 'media';
|
|
68
69
|
};
|
|
70
|
+
history_backfill?: boolean;
|
|
69
71
|
sync?: SalesIncrementalEnvelope;
|
|
70
72
|
}
|
|
71
73
|
export interface SalesIncrementalEnvelope {
|
|
@@ -1,12 +1,17 @@
|
|
|
1
|
+
import type { MediaPriorityHint } from './types.ts';
|
|
1
2
|
export interface NativeCapabilities {
|
|
2
3
|
platform: 'windows' | 'macos' | 'unsupported';
|
|
3
4
|
arch: string;
|
|
4
5
|
ready: boolean;
|
|
5
6
|
limitations: string[];
|
|
6
7
|
version?: string;
|
|
8
|
+
dynamicBridge?: boolean;
|
|
9
|
+
mediaPriority?: boolean;
|
|
7
10
|
}
|
|
8
11
|
export declare class WechatLoginPendingError extends Error {
|
|
9
12
|
}
|
|
13
|
+
export declare class WechatCaptureBusyError extends Error {
|
|
14
|
+
}
|
|
10
15
|
export interface NativeCompletion {
|
|
11
16
|
type: 'completed';
|
|
12
17
|
stats: Record<string, number>;
|
|
@@ -22,6 +27,7 @@ export interface NativeBackend {
|
|
|
22
27
|
requestId: string;
|
|
23
28
|
syncAddress: string;
|
|
24
29
|
fullSync: boolean;
|
|
30
|
+
mediaPriority?: MediaPriorityHint;
|
|
25
31
|
}, onEvent: (event: any) => void, signal: AbortSignal): Promise<NativeCompletion>;
|
|
26
32
|
authorize(requestId: string, approved: boolean): void;
|
|
27
33
|
close(): Promise<void>;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { MediaPriorityHint } from './types.ts';
|
|
1
2
|
interface Options {
|
|
2
3
|
token: string;
|
|
3
4
|
port?: number;
|
|
@@ -10,15 +11,22 @@ interface Options {
|
|
|
10
11
|
export declare class LoopbackReceiver {
|
|
11
12
|
readonly address: string;
|
|
12
13
|
private headers;
|
|
13
|
-
private
|
|
14
|
+
private readonly pairingPort;
|
|
14
15
|
private options;
|
|
15
|
-
private
|
|
16
|
-
private
|
|
16
|
+
private endpoint?;
|
|
17
|
+
private desiredPort?;
|
|
18
|
+
private priority?;
|
|
19
|
+
private prioritySequence;
|
|
20
|
+
private sentPriority;
|
|
21
|
+
private livePriority;
|
|
17
22
|
private connected;
|
|
18
23
|
private stopped;
|
|
19
24
|
constructor(options: Options);
|
|
20
25
|
private request;
|
|
21
|
-
|
|
26
|
+
setMediaPriority(hint?: MediaPriorityHint): void;
|
|
27
|
+
private sendPriority;
|
|
28
|
+
start(port?: number): void;
|
|
29
|
+
suspend(): void;
|
|
22
30
|
waitConnected(timeout?: number): Promise<void>;
|
|
23
31
|
private delay;
|
|
24
32
|
private poll;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
type Method = 'importBatch' | 'listContacts' | 'getContact' | 'listMessages' | 'getMedia' | 'getDraftVoice' | 'bindCrm' | 'getState' | 'saveState' | 'markHandled' | 'getPairing' | 'getDeliverySource' | 'claimDelivery' | 'settleDelivery' | 'deliveryStatus' | 'queueIntent' | 'seedIntents' | 'nextIntent' | 'getIntentInput' | 'finishIntent';
|
|
1
|
+
type Method = 'importBatch' | 'listContacts' | 'getContact' | 'listMessages' | 'getMedia' | 'getMediaPriority' | 'getDraftVoice' | 'getVoiceForTranscription' | 'bindCrm' | 'getState' | 'saveState' | 'markHandled' | 'getPairing' | 'getDeliverySource' | 'claimDelivery' | 'settleDelivery' | 'deliveryStatus' | 'queueIntent' | 'seedIntents' | 'nextIntent' | 'getIntentInput' | 'finishIntent';
|
|
2
2
|
/** SQLite imports execute off the Host event loop so leases/control events remain responsive. */
|
|
3
3
|
export declare class RepositoryClient {
|
|
4
4
|
private worker;
|
|
@@ -39,6 +39,9 @@ export declare class WechatSyncService {
|
|
|
39
39
|
private revisions;
|
|
40
40
|
private committedRequest?;
|
|
41
41
|
private mediaCommittedRequest?;
|
|
42
|
+
private priorityVersion;
|
|
43
|
+
private mediaFocus?;
|
|
44
|
+
private mediaRequest?;
|
|
42
45
|
private state;
|
|
43
46
|
constructor(options: WechatSyncOptions);
|
|
44
47
|
private newNative;
|
|
@@ -47,6 +50,11 @@ export declare class WechatSyncService {
|
|
|
47
50
|
retryRuntime(workspace: string): SyncStatus;
|
|
48
51
|
private changed;
|
|
49
52
|
private assertScope;
|
|
53
|
+
prioritizeMedia(workspace: string, contactId: string, focusId: string, messageId?: string): Promise<{
|
|
54
|
+
queued: boolean;
|
|
55
|
+
}>;
|
|
56
|
+
clearMediaFocus(workspace: string, focusId: string): void;
|
|
57
|
+
private currentMediaPriority;
|
|
50
58
|
private progress;
|
|
51
59
|
private repo;
|
|
52
60
|
data<T = any>(method: Parameters<RepositoryClient['call']>[0], workspace: string, ...args: any[]): Promise<T>;
|
|
@@ -43,6 +43,20 @@ export interface SyncCapabilities {
|
|
|
43
43
|
ready: boolean;
|
|
44
44
|
limitations: string[];
|
|
45
45
|
version?: string;
|
|
46
|
+
dynamicBridge?: boolean;
|
|
47
|
+
mediaPriority?: boolean;
|
|
48
|
+
}
|
|
49
|
+
export interface MediaPriorityHint extends MediaPriority {
|
|
50
|
+
focusId: string;
|
|
51
|
+
scan?: boolean;
|
|
52
|
+
}
|
|
53
|
+
export interface MediaPriority {
|
|
54
|
+
account: string;
|
|
55
|
+
chatKey: string;
|
|
56
|
+
messages: {
|
|
57
|
+
key: string;
|
|
58
|
+
revision: string;
|
|
59
|
+
}[];
|
|
46
60
|
}
|
|
47
61
|
export type SyncPhase = 'disconnected' | 'ready' | 'starting' | 'authorizing' | 'collecting' | 'importing' | 'awaiting-login' | 'waiting' | 'paused' | 'error';
|
|
48
62
|
export interface SyncProgress {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
1
|
import type { Contact } from './model.ts';
|
|
2
2
|
export declare function attachmentReply(kind: string): string | undefined;
|
|
3
3
|
export declare function canDraftWechat(contact: Contact): boolean;
|
|
4
|
+
/** Installed 0.11.0 persisted this error without a structured failure code. */
|
|
5
|
+
export declare function isLegacyMissingDraftKnowledge(error?: string): boolean;
|
|
@@ -5,4 +5,5 @@ export interface WeKnoraConnection {
|
|
|
5
5
|
}
|
|
6
6
|
/** Connection values are accepted only from the Host's installation config. */
|
|
7
7
|
export declare function resolveWeKnoraConnection(raw: unknown, label: string): WeKnoraConnection | undefined;
|
|
8
|
+
export declare function readWeKnoraEnvelope(response: Response): Promise<Record<string, unknown>>;
|
|
8
9
|
export declare function readWeKnoraData(response: Response): Promise<Record<string, unknown>>;
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { type KnowledgeDocument, type KnowledgeHit, type NamedDocument } from './knowledge-types.ts';
|
|
2
|
+
import { type WeKnoraConnection } from './weknora-http.ts';
|
|
3
|
+
/** Only the sales Host can select the connection and its allowed libraries. */
|
|
4
|
+
export declare function createWeKnoraRetrieval(connection: WeKnoraConnection, libraryIds: readonly string[], timeoutMs: number, evaluation: boolean): {
|
|
5
|
+
list(signal: AbortSignal): Promise<{
|
|
6
|
+
count: number;
|
|
7
|
+
knowledge_bases: {
|
|
8
|
+
id: string;
|
|
9
|
+
name: string;
|
|
10
|
+
description: string;
|
|
11
|
+
}[];
|
|
12
|
+
}>;
|
|
13
|
+
search(args: Record<string, unknown>, signal: AbortSignal): Promise<{
|
|
14
|
+
request_id?: string | undefined;
|
|
15
|
+
query: string;
|
|
16
|
+
knowledge_base_ids: string[];
|
|
17
|
+
count: number;
|
|
18
|
+
results: KnowledgeHit[];
|
|
19
|
+
documents: NamedDocument[];
|
|
20
|
+
}>;
|
|
21
|
+
read(args: Record<string, unknown>, signal: AbortSignal): Promise<KnowledgeDocument>;
|
|
22
|
+
};
|
|
@@ -10,6 +10,9 @@ import { createHash, randomBytes } from "node:crypto";
|
|
|
10
10
|
// src/wechat/batch.ts
|
|
11
11
|
var SALES_BATCH_SCHEMA = "wanji.wechat.batch.v1";
|
|
12
12
|
var MAX_VIDEO_BYTES = 16 * 1024 * 1024;
|
|
13
|
+
function isFocusedTextBatch(raw) {
|
|
14
|
+
return !!raw && typeof raw === "object" && "run_id" in raw && typeof raw.run_id === "string" && /^priority-[a-f0-9]{32}(?::[0-9]+)?$/.test(raw.run_id);
|
|
15
|
+
}
|
|
13
16
|
var SALES_MESSAGE_KINDS = [
|
|
14
17
|
"text",
|
|
15
18
|
"image",
|
|
@@ -52,6 +55,7 @@ function validateSalesBatch(value) {
|
|
|
52
55
|
throw new Error("warnings must be a string array");
|
|
53
56
|
}
|
|
54
57
|
if (!isRecord(value.stats)) throw new Error("stats must be an object");
|
|
58
|
+
if (value.history_backfill !== void 0 && typeof value.history_backfill !== "boolean") throw Error("Invalid history_backfill flag");
|
|
55
59
|
const mediaPatch = value.delivery !== void 0;
|
|
56
60
|
if (mediaPatch && (!isRecord(value.delivery) || value.delivery.protocol !== "wanji.media-patch.v1" || value.delivery.phase !== "media" || value.sync !== void 0 || typeof value.source.account_wxid !== "string" || !value.source.account_wxid.trim())) {
|
|
57
61
|
throw new Error("Invalid media patch envelope");
|
|
@@ -205,6 +209,9 @@ var attachmentReplies = /* @__PURE__ */ new Map([
|
|
|
205
209
|
function attachmentReply(kind) {
|
|
206
210
|
return attachmentReplies.get(kind);
|
|
207
211
|
}
|
|
212
|
+
function isLegacyMissingDraftKnowledge(error) {
|
|
213
|
+
return error?.startsWith("\u8FD9\u6B21\u56DE\u590D\u9700\u8981\u7684\u8D44\u6599\u6682\u4E0D\u53EF\u7528\uFF1A\u77E5\u8BC6\u5E93\u5DE5\u5177\u672A\u5C31\u7EEA\uFF0C\u8BF7\u68C0\u67E5\u77E5\u8BC6\u5E93\u63D2\u4EF6\u662F\u5426\u5DF2\u542F\u7528\u3002") === true;
|
|
214
|
+
}
|
|
208
215
|
|
|
209
216
|
// src/wechat/repository.ts
|
|
210
217
|
var hash = (v) => createHash("sha256").update(JSON.stringify(v)).digest("hex");
|
|
@@ -249,6 +256,7 @@ var WechatRepository = class _WechatRepository {
|
|
|
249
256
|
if (!this.rows("PRAGMA table_info(messages)").some((c) => c.name === "intent_revision")) {
|
|
250
257
|
this.db.exec("ALTER TABLE messages ADD COLUMN intent_revision INTEGER NOT NULL DEFAULT 0");
|
|
251
258
|
}
|
|
259
|
+
if (!this.rows("PRAGMA table_info(messages)").some((c) => c.name === "preview_only")) this.db.exec("ALTER TABLE messages ADD COLUMN preview_only INTEGER NOT NULL DEFAULT 0");
|
|
252
260
|
if (!this.rows("PRAGMA table_info(messages)").some((c) => c.name === "auto_draft_arrival")) this.db.exec("ALTER TABLE messages ADD COLUMN auto_draft_arrival INTEGER NOT NULL DEFAULT 0");
|
|
253
261
|
this.db.exec(`INSERT OR IGNORE INTO avatars(workspace,account,owner,media_id,observed_at)
|
|
254
262
|
SELECT c.workspace,c.account,c.chat_key,m.id,0 FROM chats c JOIN media m
|
|
@@ -296,6 +304,8 @@ var WechatRepository = class _WechatRepository {
|
|
|
296
304
|
const source = hash([workspace, account, batch.source.kind ?? "", batch.source.device_id ?? ""]);
|
|
297
305
|
const active = this.row("SELECT account FROM active WHERE workspace=?", workspace)?.account;
|
|
298
306
|
if (batch.delivery && active !== account) throw Error("WANJI_RESYNC_REQUIRED: media account baseline missing");
|
|
307
|
+
const preview = isFocusedTextBatch(batch), backfill = initial || batch.sync?.mode === "full" || batch.history_backfill === true;
|
|
308
|
+
if (preview && (active !== account || batch.sync || batch.delivery || batch.media.length || batch.chats.length !== 1 || !this.row("SELECT id FROM chats WHERE workspace=? AND account=? AND chat_key=?", workspace, account, batch.chats[0].chat_key))) throw Error("WECHAT_FOCUSED_BATCH_SCOPE");
|
|
299
309
|
const changed = /* @__PURE__ */ new Set(), replyChanges = /* @__PURE__ */ new Set(), voiceChanges = /* @__PURE__ */ new Map();
|
|
300
310
|
let messages = 0, avatarsUpdated = 0;
|
|
301
311
|
const imageAreas = new Map(batch.delivery ? batch.media.filter((media) => media.kind === "image").map((media) => [media.media_key, media.width * media.height]) : []);
|
|
@@ -334,9 +344,9 @@ var WechatRepository = class _WechatRepository {
|
|
|
334
344
|
const chatId = "wx-" + hash([workspace, account, chat.chat_key]), existing = this.row("SELECT * FROM chats WHERE id=?", chatId);
|
|
335
345
|
if (batch.delivery && !existing) throw Error("WANJI_RESYNC_REQUIRED: media chat missing");
|
|
336
346
|
const metadata = { ...existing ? JSON.parse(existing.metadata) : {}, ...Object.fromEntries(["remark", "nickname", "alias"].filter((key) => Object.hasOwn(chat, key)).map((key) => [key, chat[key]])) }, encodedMetadata = JSON.stringify(metadata);
|
|
337
|
-
if (!batch.delivery) this.db.prepare("INSERT INTO chats(id,workspace,account,chat_key,name,history_state,metadata) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,history_state=excluded.history_state,metadata=excluded.metadata").run(chatId, workspace, account, chat.chat_key, chat.display_name, chat.history_state ?? null, encodedMetadata);
|
|
338
|
-
if (!batch.delivery && (!existing || existing.name !== chat.display_name || existing.history_state !== (chat.history_state ?? null) || existing.metadata !== encodedMetadata)) changed.add(chatId);
|
|
339
|
-
const advanceIntent = trackIntent && (!(
|
|
347
|
+
if (!preview && !batch.delivery) this.db.prepare("INSERT INTO chats(id,workspace,account,chat_key,name,history_state,metadata) VALUES(?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET name=excluded.name,history_state=excluded.history_state,metadata=excluded.metadata").run(chatId, workspace, account, chat.chat_key, chat.display_name, chat.history_state ?? null, encodedMetadata);
|
|
348
|
+
if (!preview && !batch.delivery && (!existing || existing.name !== chat.display_name || existing.history_state !== (chat.history_state ?? null) || existing.metadata !== encodedMetadata)) changed.add(chatId);
|
|
349
|
+
const advanceIntent = trackIntent && !preview && (!(backfill || active !== account) || !!this.row("SELECT 1 FROM customer_intents WHERE chat_id=?", chatId));
|
|
340
350
|
let intentRevision;
|
|
341
351
|
for (const m of chat.messages) {
|
|
342
352
|
const oldSource = this.row("SELECT * FROM sources WHERE scope=? AND chat_id=? AND message_key=?", source, chatId, m.message_key);
|
|
@@ -359,18 +369,21 @@ var WechatRepository = class _WechatRepository {
|
|
|
359
369
|
const server = typeof m.server_id === "string" && /^\d+$/.test(m.server_id) && !/^0+$/.test(m.server_id) ? m.server_id : void 0;
|
|
360
370
|
const id = server ? hash([chatId, "server", server]) : hash([chatId, "local", source, m.message_key]);
|
|
361
371
|
const old = this.row("SELECT * FROM messages WHERE id=?", id), revisionChanged = !!old && old.source_revision !== (m.source_revision ?? null), mediaId = m.media_key ? hash([source, m.media_key]) : revisionChanged ? null : old?.media_id ?? null;
|
|
362
|
-
if (
|
|
363
|
-
|
|
372
|
+
if (preview && old) continue;
|
|
373
|
+
const newlyConfirmed = !preview && (!old || old.preview_only === 1);
|
|
374
|
+
if (!old || newlyConfirmed || old.text !== m.text || old.direction !== m.direction || old.kind !== m.kind || old.sent_at !== m.sent_at || old.media_id !== mediaId || revisionChanged || old.metadata !== JSON.stringify(m)) {
|
|
375
|
+
if (!preview && replyInputChanged(newlyConfirmed ? void 0 : old, m)) replyChanges.add(chatId);
|
|
364
376
|
if (m.kind === "voice" && m.direction === "inbound" && old?.auto_draft_arrival === 1 && old.media_id !== mediaId) trackVoiceChange(chatId, id);
|
|
365
|
-
this.db.prepare("INSERT INTO messages(id,chat_id,sent_at,sort_seq,local_id,direction,kind,text,media_id,source_revision,metadata) VALUES(
|
|
377
|
+
this.db.prepare("INSERT INTO messages(id,chat_id,sent_at,sort_seq,local_id,direction,kind,text,media_id,source_revision,metadata,preview_only) VALUES(?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET preview_only=0,sent_at=excluded.sent_at,sort_seq=excluded.sort_seq,local_id=excluded.local_id,direction=excluded.direction,kind=excluded.kind,text=excluded.text,media_id=excluded.media_id,source_revision=excluded.source_revision,metadata=excluded.metadata").run(id, chatId, m.sent_at, m.sort_seq, m.local_id, m.direction, m.kind, m.text, mediaId, m.source_revision ?? null, JSON.stringify(m), preview ? 1 : 0);
|
|
366
378
|
changed.add(chatId);
|
|
367
379
|
if (!old) messages++;
|
|
368
380
|
}
|
|
369
|
-
if (
|
|
381
|
+
if (preview) continue;
|
|
382
|
+
if (newlyConfirmed && !backfill && active === account && m.direction === "inbound" && (replyText(m) || attachmentReply(m.kind))) {
|
|
370
383
|
this.db.prepare("UPDATE messages SET auto_draft_arrival=1 WHERE id=?").run(id);
|
|
371
384
|
}
|
|
372
385
|
const meaningful = (row) => row.direction !== "system" && ["text", "quote", "link"].includes(row.kind) && typeof row.text === "string" && !!row.text.trim();
|
|
373
|
-
const intentChanged = !old ? meaningful(m) : (meaningful(m) || meaningful(old)) && (old.text !== m.text || old.direction !== m.direction || old.kind !== m.kind);
|
|
386
|
+
const intentChanged = !old || newlyConfirmed ? meaningful(m) : (meaningful(m) || meaningful(old)) && (old.text !== m.text || old.direction !== m.direction || old.kind !== m.kind);
|
|
374
387
|
if (advanceIntent && intentChanged) {
|
|
375
388
|
intentRevision ??= this.queueIntentRow(chatId, Date.now() + 3500, true);
|
|
376
389
|
this.db.prepare("UPDATE messages SET intent_revision=? WHERE id=?").run(intentRevision, id);
|
|
@@ -516,7 +529,8 @@ var WechatRepository = class _WechatRepository {
|
|
|
516
529
|
const latestInbound = recent.filter((m) => m.direction === "inbound").at(-1);
|
|
517
530
|
const state = JSON.parse(c.state);
|
|
518
531
|
const hasText = !!latestInbound && messages.some((m) => m.id === latestInbound.id);
|
|
519
|
-
const
|
|
532
|
+
const recoverKnowledgeFailure = state.draftKind !== "edited" && state.autoDraftedMessageId === latestInbound?.id && isLegacyMissingDraftKnowledge(state.generationError);
|
|
533
|
+
const settled = state.sourceVersion === c.version && (state.draftKind === "agent" || state.generationError && !recoverKnowledgeFailure || state.generationNoReply || state.draftKind === "edited" && state.autoDraftedMessageId === latestInbound?.id && !!latestInbound);
|
|
520
534
|
const canDraft = latestInbound && last?.id === latestInbound.id && c.version > c.handled && !settled && (hasText || attachmentReply(latestInbound.kind)) && this.row("SELECT auto_draft_arrival FROM messages WHERE id=?", latestInbound.id)?.auto_draft_arrival === 1;
|
|
521
535
|
const intent = this.intentFor(c.id);
|
|
522
536
|
const avatar = this.row("SELECT media_id,observed_at FROM avatars WHERE workspace=? AND account=? AND owner=?", c.workspace, c.account, c.chat_key);
|
|
@@ -565,11 +579,43 @@ var WechatRepository = class _WechatRepository {
|
|
|
565
579
|
if (!row) throw Error("WECHAT_MEDIA_SCOPE");
|
|
566
580
|
return { mimeType: row.mime, data: Buffer.from(row.data).toString("base64") };
|
|
567
581
|
}
|
|
582
|
+
getMediaPriority(workspace, contactId, messageId, afterId) {
|
|
583
|
+
const chat = this.scope(workspace, contactId);
|
|
584
|
+
if (messageId && !this.row("SELECT id FROM messages WHERE chat_id=? AND id=?", contactId, messageId)) throw Error("WECHAT_MEDIA_SCOPE");
|
|
585
|
+
const after = afterId && !messageId ? this.row("SELECT sent_at,id FROM messages WHERE chat_id=? AND id=?", contactId, afterId) : void 0;
|
|
586
|
+
const candidates = this.db.prepare(`SELECT id,metadata,source_revision FROM messages
|
|
587
|
+
WHERE chat_id=? AND media_id IS NULL AND kind IN ('image','voice') AND length(source_revision)=64
|
|
588
|
+
${messageId ? "AND id=?" : ""} ${after ? "AND (sent_at,id)<(?,?)" : ""} ORDER BY sent_at DESC,id DESC`);
|
|
589
|
+
const messages = [];
|
|
590
|
+
let nextAfter;
|
|
591
|
+
for (const row of candidates.iterate(contactId, ...messageId ? [messageId] : [], ...after ? [after.sent_at, after.id] : [])) {
|
|
592
|
+
const key = JSON.parse(String(row.metadata)).message_key, revision = row.source_revision;
|
|
593
|
+
if (typeof key === "string" && /^[!-~]{1,160}$/.test(key) && typeof revision === "string" && /^[0-9a-f]{64}$/.test(revision)) {
|
|
594
|
+
messages.push({ key, revision });
|
|
595
|
+
if (messages.length === 24) {
|
|
596
|
+
nextAfter = String(row.id);
|
|
597
|
+
break;
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
if (after && !messages.length) return this.getMediaPriority(workspace, contactId);
|
|
602
|
+
return { account: chat.account, chatKey: chat.chat_key, messages, ...nextAfter ? { nextAfter } : {} };
|
|
603
|
+
}
|
|
568
604
|
getDraftVoice(workspace, contactId, messageId, version) {
|
|
569
605
|
const contact = this.getContact(workspace, contactId), inbound = contact.wechat?.latestInbound;
|
|
570
606
|
if (contact.wechat?.version !== version || inbound?.id !== messageId) throw Error("WECHAT_STATE_STALE");
|
|
571
|
-
|
|
572
|
-
|
|
607
|
+
return this.getVoiceForTranscription(workspace, contactId, messageId);
|
|
608
|
+
}
|
|
609
|
+
getVoiceForTranscription(workspace, contactId, messageId) {
|
|
610
|
+
const chat = this.scope(workspace, contactId);
|
|
611
|
+
const row = this.row(
|
|
612
|
+
`SELECT a.data FROM messages m JOIN media a ON a.id=m.media_id
|
|
613
|
+
WHERE m.chat_id=? AND m.id=? AND m.kind='voice' AND a.workspace=? AND a.account=? AND a.mime='audio/wav'`,
|
|
614
|
+
contactId,
|
|
615
|
+
messageId,
|
|
616
|
+
workspace,
|
|
617
|
+
chat.account
|
|
618
|
+
);
|
|
573
619
|
return row?.data;
|
|
574
620
|
}
|
|
575
621
|
bindCrm(workspace, id, binding, trackIntent = false) {
|
|
@@ -631,7 +677,7 @@ var WechatRepository = class _WechatRepository {
|
|
|
631
677
|
|
|
632
678
|
// src/wechat/repository-worker.ts
|
|
633
679
|
var repository = await WechatRepository.open(workerData.root);
|
|
634
|
-
var allowed = /* @__PURE__ */ new Set(["importBatch", "listContacts", "getContact", "listMessages", "getMedia", "getDraftVoice", "bindCrm", "getState", "saveState", "markHandled", "getPairing", "getDeliverySource", "claimDelivery", "settleDelivery", "deliveryStatus", "queueIntent", "seedIntents", "nextIntent", "getIntentInput", "finishIntent"]);
|
|
680
|
+
var allowed = /* @__PURE__ */ new Set(["importBatch", "listContacts", "getContact", "listMessages", "getMedia", "getMediaPriority", "getDraftVoice", "getVoiceForTranscription", "bindCrm", "getState", "saveState", "markHandled", "getPairing", "getDeliverySource", "claimDelivery", "settleDelivery", "deliveryStatus", "queueIntent", "seedIntents", "nextIntent", "getIntentInput", "finishIntent"]);
|
|
635
681
|
parentPort.on("message", ({ id, method, args }) => {
|
|
636
682
|
try {
|
|
637
683
|
if (!allowed.has(method)) throw Error("WECHAT_OPERATION_INVALID");
|
|
@@ -12,7 +12,7 @@ Mac 固定 `DSHWechatWorker --serve`,普通用户常驻 stdio,每轮/授权
|
|
|
12
12
|
|
|
13
13
|
Windows 固定 `DSHWechatLauncher.exe`(本插件 C++ 源码),只接受有界十进制端口和64位hex令牌,只通过 ShellExecuteExW/runas 启动同目录固定 Worker,没有 shell/PowerShell/拼接脚本。Host 绑定随机 loopback TCP,以随机32字节令牌和 protocolVersion 2 鉴别首帧后复用连接。原用户 profile 来自 Node OS userInfo;提权 Worker 用 OS API 取得实际 token 用户 profile,不信任继承的 USERPROFILE。拒绝其他管理员账号。Host EOF 监视线程可撤销正在执行的采集,取消解码并结束 Worker,不等下一轮命令。
|
|
14
14
|
|
|
15
|
-
|
|
15
|
+
配对地址沿用 `http://127.0.0.1:18765/#wanji-local-sync=<64hex>`,用于保留既有同步检查点。Host 核验组件后,新版 Mac Worker 绑定系统分配的回环端口,通过当前请求的 `bridge_ready` 帧通知接收器。旧版 Mac 和 Windows 组件仍使用配对地址的固定端口。并行实例仍遵守同一用户的采集锁。新版 Mac 遇到锁被占用时,自动同步会稍后按原模式重试。手动全量同步仍保留后续增量检查点。其他断线按原有流程暂停或重新连接。
|
|
16
16
|
|
|
17
17
|
## 源码、许可证与构建
|
|
18
18
|
|
package/docs/wechat-sync.md
CHANGED
|
@@ -38,7 +38,7 @@ Mac 采集器按原值读取微信联系人标识,包括以短横线开头的
|
|
|
38
38
|
|
|
39
39
|
数据库/WAL/journal事件合并300ms,连续事件最长1秒唤醒;当前轮在运行时只记变化,完成后继续一轮,避免并发读取。可靠快速检查时5秒兜底,否则30秒;失败有上限退避。Mac 自动同步开始检查时,如遇微信尚未运行或尚未完成登录,页面显示“等待微信登录”。插件分别间隔 5、15、30、60 秒重试,最多四次,每次重新核验当前账号,并沿用原来的全量或增量模式。等待时可暂停;重试用尽后,登录微信并点击“重新同步”。其他 Worker 断连仍需手动重连。上述是调度参数,首次历史、解密、媒体与SQLite耗时另计,实际文字延迟待各平台真机测量。
|
|
40
40
|
|
|
41
|
-
|
|
41
|
+
原始数据库与读取密钥留在本机采集链路。批次通过 `127.0.0.1` 交给 Host,新版 Mac 组件使用系统分配的端口,旧版 Mac 和 Windows 组件使用 `18765`。SQLite 在独立线程提交消息、媒体、来源映射、分片基线及回执后才 ACK,失败或 ACK 丢失后可重放保留的快照。切号显示新账号,已入库旧账号历史保留并隔离。相同 server_id 跨平台归一,来源游标和无 server_id 的消息仍按平台设备区分。
|
|
42
42
|
|
|
43
43
|
消息库位于插件`storageDir/wechat/sales.sqlite`,目录0700、库文件0600;备份时应停止插件并保留SQLite相关文件。真实消息不写入旧演示journal。AI草稿绑定微信源版本,新消息会使其失效;人工稿保留并提示复核。生成只使用有界的文字证据,系统/未知消息及媒体占位不作为客户事实。AI仍使用已配置模型服务,不代表全部离线。
|
|
44
44
|
|
package/package.json
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema": 1,
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.1",
|
|
4
4
|
"targets": {
|
|
5
5
|
"win32-x64": {
|
|
6
|
-
"url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.
|
|
7
|
-
"sha256": "
|
|
8
|
-
"bytes":
|
|
9
|
-
"unpackedBytes":
|
|
10
|
-
"componentSha256": "
|
|
6
|
+
"url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.2-win32-x64-9748e032830ccf40.tgz",
|
|
7
|
+
"sha256": "9748e032830ccf406049142e9359126ba8a98ddb98313c5d7d036235bbaad066",
|
|
8
|
+
"bytes": 22908326,
|
|
9
|
+
"unpackedBytes": 47600016,
|
|
10
|
+
"componentSha256": "53faf766238bb20c0f6bcd5c4a07a8f80dd5e27bc15bab2cf669f74983223c05"
|
|
11
11
|
},
|
|
12
12
|
"darwin-arm64": {
|
|
13
|
-
"url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.
|
|
14
|
-
"sha256": "
|
|
15
|
-
"bytes":
|
|
16
|
-
"unpackedBytes":
|
|
17
|
-
"componentSha256": "
|
|
13
|
+
"url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.4-darwin-arm64-f1256982cb2ffe92.tgz",
|
|
14
|
+
"sha256": "f1256982cb2ffe924e795b2e8314b80e93b4a15c683c62081663d8f39085b639",
|
|
15
|
+
"bytes": 26146175,
|
|
16
|
+
"unpackedBytes": 63510330,
|
|
17
|
+
"componentSha256": "0fe87ac2b7a1b8ffeef7326c9c2c8e4204d49249647a7be4e1dbd18fc2cc191c"
|
|
18
18
|
},
|
|
19
19
|
"darwin-x64": {
|
|
20
|
-
"url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.
|
|
21
|
-
"sha256": "
|
|
22
|
-
"bytes":
|
|
23
|
-
"unpackedBytes":
|
|
24
|
-
"componentSha256": "
|
|
20
|
+
"url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.3-darwin-x64-d7949a324b96bfd4.tgz",
|
|
21
|
+
"sha256": "d7949a324b96bfd438ecff84a368d6836f6835b3b189e1f3e12acd263a7f047f",
|
|
22
|
+
"bytes": 27833081,
|
|
23
|
+
"unpackedBytes": 66649013,
|
|
24
|
+
"componentSha256": "657457a18c54f3c8f0bc9fa977e14c0254d2561e8ece9d690803ccc017cb7c36"
|
|
25
25
|
}
|
|
26
26
|
}
|
|
27
27
|
}
|