@wanji_dsh/dsh-sales 0.9.7 → 0.10.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/.dsh/skills/wanji-sales-assistant/SKILL.md +28 -3
- package/.dsh/skills/wanji-sales-assistant/references/draft-review.md +2 -2
- package/.dsh/skills/wanji-sales-assistant/references/wechat-delivery.md +24 -0
- package/README.md +28 -4
- package/README.zh.md +55 -4
- package/dist/client.js +9988 -667
- package/dist/host.js +4005 -1085
- package/dist/types/{agent-evaluators.d.ts → agent-evaluators-v2.d.ts} +17 -3
- package/dist/types/agent-knowledge.d.ts +11 -2
- package/dist/types/agent.d.ts +21 -8
- package/dist/types/commercial-boundary.d.ts +7 -0
- package/dist/types/customer-intent.d.ts +49 -0
- package/dist/types/customer-materials.d.ts +49 -0
- package/dist/types/dialogue-tasks.d.ts +10 -0
- package/dist/types/draft-edits.d.ts +7 -0
- package/dist/types/evaluation-client.d.ts +2 -6
- package/dist/types/fact-proof.d.ts +2 -1
- package/dist/types/generation-progress.d.ts +32 -0
- package/dist/types/generation-runtime.d.ts +17 -0
- package/dist/types/generation-session-route.d.ts +5 -0
- package/dist/types/generation-sessions.d.ts +36 -0
- package/dist/types/host.d.ts +15 -0
- package/dist/types/knowledge-host.d.ts +22 -3
- package/dist/types/knowledge-judgment-delivery.d.ts +2 -0
- package/dist/types/knowledge-judgments.d.ts +12 -0
- package/dist/types/knowledge-privacy.d.ts +2 -0
- package/dist/types/knowledge-turns.d.ts +22 -0
- package/dist/types/langfuse-config.d.ts +1 -0
- package/dist/types/langfuse-outbox.d.ts +10 -2
- package/dist/types/material-catalog.d.ts +17 -0
- package/dist/types/material-metadata.d.ts +4 -0
- package/dist/types/material-reply.d.ts +24 -0
- package/dist/types/material-request.d.ts +45 -0
- package/dist/types/material-retrieval.d.ts +29 -0
- package/dist/types/model.d.ts +23 -2
- package/dist/types/open-generation.d.ts +5 -2
- package/dist/types/open-review.d.ts +39 -15
- package/dist/types/operation-evidence.d.ts +7 -0
- package/dist/types/percentage-quote.d.ts +6 -0
- package/dist/types/plan-projection.d.ts +2 -0
- package/dist/types/product-evidence.d.ts +4 -0
- package/dist/types/question-relay.d.ts +24 -0
- package/dist/types/question-route.d.ts +4 -0
- package/dist/types/question-tracing.d.ts +84 -0
- package/dist/types/quote-context.d.ts +9 -5
- package/dist/types/response-contract.d.ts +10 -0
- package/dist/types/retrieval-queries.d.ts +4 -0
- package/dist/types/review-turn.d.ts +6 -0
- package/dist/types/sales-context-types.d.ts +15 -0
- package/dist/types/semantic-rerank.d.ts +9 -0
- package/dist/types/sending-policy.d.ts +2 -0
- package/dist/types/server/intent-evaluation.d.ts +27 -0
- package/dist/types/server/intent-host.d.ts +17 -0
- package/dist/types/stream-preview.d.ts +11 -0
- package/dist/types/turn-packet.d.ts +21 -8
- package/dist/types/turn-plan.d.ts +19 -7
- package/dist/types/update/activity.d.ts +28 -0
- package/dist/types/update/coordinator.d.ts +44 -0
- package/dist/types/update/guard.d.ts +3 -0
- package/dist/types/update/integration.d.ts +6 -0
- package/dist/types/update/manager.d.ts +13 -0
- package/dist/types/update/routes.d.ts +6 -0
- package/dist/types/update/state.d.ts +13 -0
- package/dist/types/update/types.d.ts +88 -0
- package/dist/types/update/version.d.ts +1 -0
- package/dist/types/verified-arithmetic.d.ts +5 -0
- package/dist/types/voice-examples.d.ts +1 -0
- package/dist/types/wechat/cua-approval.d.ts +36 -0
- package/dist/types/wechat/cua-sender.d.ts +160 -0
- package/dist/types/wechat/cua-vision.d.ts +31 -0
- package/dist/types/wechat/delivery.d.ts +47 -0
- package/dist/types/wechat/intent-scheduler.d.ts +26 -0
- package/dist/types/wechat/repository-client.d.ts +1 -1
- package/dist/types/wechat/routes.d.ts +9 -7
- package/dist/types/wechat/service.d.ts +12 -3
- package/dist/types/wechat/types.d.ts +5 -0
- package/dist/types/wechat-draft-input.d.ts +3 -0
- package/dist/types/wechat-voice.d.ts +3 -0
- package/dist/types/weknora-http.d.ts +8 -0
- package/dist/wechat-repository-worker.js +248 -22
- package/docs/agent-knowledge-observation.md +58 -0
- package/docs/auto-update.md +41 -0
- package/docs/customer-material-retrieval.md +48 -0
- package/docs/licenses/ccount@2.0.1.txt +24 -0
- package/docs/licenses/character-entities@2.0.2.txt +24 -0
- package/docs/licenses/debug@4.4.3.txt +21 -0
- package/docs/licenses/decode-named-character-reference@1.3.0.txt +24 -0
- package/docs/licenses/dequal@2.0.3.txt +23 -0
- package/docs/licenses/devlop@1.1.0.txt +24 -0
- package/docs/licenses/escape-string-regexp@5.0.0.txt +11 -0
- package/docs/licenses/longest-streak@3.1.0.txt +24 -0
- package/docs/licenses/markdown-table@3.1.0.txt +24 -0
- package/docs/licenses/mdast-util-find-and-replace@3.0.4.txt +24 -0
- package/docs/licenses/mdast-util-from-markdown@2.0.3.txt +24 -0
- package/docs/licenses/mdast-util-gfm-autolink-literal@2.1.0.txt +24 -0
- package/docs/licenses/mdast-util-gfm-footnote@2.1.0.txt +24 -0
- package/docs/licenses/mdast-util-gfm-strikethrough@2.0.1.txt +24 -0
- package/docs/licenses/mdast-util-gfm-table@2.0.1.txt +24 -0
- package/docs/licenses/mdast-util-gfm-task-list-item@2.0.1.txt +24 -0
- package/docs/licenses/mdast-util-gfm@3.0.0.txt +24 -0
- package/docs/licenses/mdast-util-phrasing@4.1.0.txt +25 -0
- package/docs/licenses/mdast-util-to-markdown@2.2.3.txt +24 -0
- package/docs/licenses/mdast-util-to-string@4.0.0.txt +24 -0
- package/docs/licenses/micromark-core-commonmark@2.0.4.txt +24 -0
- package/docs/licenses/micromark-extension-gfm-autolink-literal@2.1.0.txt +24 -0
- package/docs/licenses/micromark-extension-gfm-footnote@2.1.0.txt +24 -0
- package/docs/licenses/micromark-extension-gfm-strikethrough@2.1.0.txt +24 -0
- package/docs/licenses/micromark-extension-gfm-table@2.1.2.txt +24 -0
- package/docs/licenses/micromark-extension-gfm-tagfilter@2.0.0.txt +24 -0
- package/docs/licenses/micromark-extension-gfm-task-list-item@2.1.0.txt +24 -0
- package/docs/licenses/micromark-extension-gfm@3.0.0.txt +24 -0
- package/docs/licenses/micromark-factory-destination@2.0.1.txt +24 -0
- package/docs/licenses/micromark-factory-label@2.0.1.txt +24 -0
- package/docs/licenses/micromark-factory-space@2.1.0.txt +24 -0
- package/docs/licenses/micromark-factory-title@2.0.1.txt +24 -0
- package/docs/licenses/micromark-factory-whitespace@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-character@2.1.1.txt +24 -0
- package/docs/licenses/micromark-util-chunked@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-classify-character@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-combine-extensions@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-decode-numeric-character-reference@2.0.2.txt +24 -0
- package/docs/licenses/micromark-util-decode-string@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-edit-map@1.0.0.txt +24 -0
- package/docs/licenses/micromark-util-encode@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-html-tag-name@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-normalize-identifier@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-resolve-all@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-sanitize-uri@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-subtokenize@2.1.0.txt +24 -0
- package/docs/licenses/micromark-util-symbol@2.0.1.txt +24 -0
- package/docs/licenses/micromark-util-types@2.0.3.txt +24 -0
- package/docs/licenses/micromark@4.0.3.txt +24 -0
- package/docs/licenses/ms@2.1.3.txt +23 -0
- package/docs/licenses/unist-util-is@6.0.1.txt +24 -0
- package/docs/licenses/unist-util-stringify-position@4.0.0.txt +24 -0
- package/docs/licenses/unist-util-visit-parents@6.1.0.txt +24 -0
- package/docs/licenses/unist-util-visit@5.2.0.txt +24 -0
- package/docs/licenses/zwitch@2.0.4.txt +24 -0
- package/docs/sales-agent-evaluation-v2.md +102 -0
- package/docs/wechat-sync.md +23 -0
- package/package.json +21 -7
- package/runtime/customer-materials.json +1935 -0
- package/runtime/documented-operation-references.json +123 -0
- package/runtime/operation-references.json +352 -0
- package/runtime/product-references.json +10 -0
- package/runtime/wechat-manifest.json +1 -1
- package/runtime/wechat-ocr-arm64 +0 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
type Method = 'importBatch' | 'listContacts' | 'getContact' | 'listMessages' | 'getMedia' | 'bindCrm' | 'getState' | 'saveState' | 'markHandled' | 'getPairing';
|
|
1
|
+
type Method = 'importBatch' | 'listContacts' | 'getContact' | 'listMessages' | 'getMedia' | 'getDraftVoice' | '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;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
import type { DshWechatSender } from './cua-sender.ts';
|
|
1
2
|
import type { HostContext } from '../knowledge-host.ts';
|
|
2
|
-
import { WechatSyncService } from './service.ts';
|
|
3
|
-
import type { WechatRuntime } from './runtime.ts';
|
|
3
|
+
import { WechatSyncService, type WechatSyncOptions } from './service.ts';
|
|
4
4
|
/** Shared Harness Fetch routes already restrict access to authenticated owner peers. */
|
|
5
|
-
export declare function registerWechatRoutes(ctx: HostContext, options: {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
5
|
+
export declare function registerWechatRoutes(ctx: HostContext, options: WechatSyncOptions & {
|
|
6
|
+
sendingEnabled?: boolean;
|
|
7
|
+
transcribeVoice?: (audio: Uint8Array, signal: AbortSignal) => Promise<string | undefined>;
|
|
8
|
+
}, injected?: WechatSyncService, desktop?: {
|
|
9
|
+
available(): boolean;
|
|
10
|
+
sender: DshWechatSender;
|
|
11
|
+
}): WechatSyncService;
|
|
@@ -4,7 +4,10 @@ import { SourceWatcher } from './watcher.ts';
|
|
|
4
4
|
import { type NativeBackend } from './native.ts';
|
|
5
5
|
import type { SyncCapabilities, SyncStatus } from './types.ts';
|
|
6
6
|
import type { WechatRuntime } from './runtime.ts';
|
|
7
|
-
type
|
|
7
|
+
import { type IntentEvaluator } from './intent-scheduler.ts';
|
|
8
|
+
import type { ResumeIntent } from '../update/types.ts';
|
|
9
|
+
export type WechatSyncOptions = {
|
|
10
|
+
intentEvaluator?: IntentEvaluator;
|
|
8
11
|
storageDir: string;
|
|
9
12
|
componentRoot: string;
|
|
10
13
|
runtime?: WechatRuntime;
|
|
@@ -26,7 +29,10 @@ export declare class WechatSyncService {
|
|
|
26
29
|
private dirty;
|
|
27
30
|
private failures;
|
|
28
31
|
private interval;
|
|
32
|
+
private intent?;
|
|
33
|
+
private initialImport;
|
|
29
34
|
private closed;
|
|
35
|
+
private updatePreparing;
|
|
30
36
|
private capabilitiesAt;
|
|
31
37
|
private runtimePhase;
|
|
32
38
|
private capabilitiesLoading?;
|
|
@@ -34,7 +40,7 @@ export declare class WechatSyncService {
|
|
|
34
40
|
private committedRequest?;
|
|
35
41
|
private mediaCommittedRequest?;
|
|
36
42
|
private state;
|
|
37
|
-
constructor(options:
|
|
43
|
+
constructor(options: WechatSyncOptions);
|
|
38
44
|
private newNative;
|
|
39
45
|
capabilities(): Promise<SyncCapabilities>;
|
|
40
46
|
status(workspace: string): SyncStatus;
|
|
@@ -44,12 +50,15 @@ export declare class WechatSyncService {
|
|
|
44
50
|
private progress;
|
|
45
51
|
private repo;
|
|
46
52
|
data<T = any>(method: Parameters<RepositoryClient['call']>[0], workspace: string, ...args: any[]): Promise<T>;
|
|
53
|
+
openIntent(workspace: string, id: string): Promise<void>;
|
|
54
|
+
private seedIntents;
|
|
47
55
|
start(workspace: string, automatic?: boolean): Promise<SyncStatus>;
|
|
48
56
|
sourceChanged(): void;
|
|
49
57
|
private schedule;
|
|
50
58
|
private cycle;
|
|
51
59
|
pause(workspace: string): SyncStatus;
|
|
60
|
+
prepareUpdate(signal: AbortSignal): Promise<ResumeIntent>;
|
|
61
|
+
resumeAfterUpdate(intent: ResumeIntent): Promise<void>;
|
|
52
62
|
authorize(workspace: string, requestId: string, approved: boolean): SyncStatus;
|
|
53
63
|
close(): Promise<void>;
|
|
54
64
|
}
|
|
55
|
-
export {};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { SalesReply } from '../agent.ts';
|
|
1
2
|
import type { Contact } from '../model.ts';
|
|
2
3
|
import type { SalesIncrementalEnvelope } from './batch.ts';
|
|
3
4
|
export declare const WECHAT_METHOD = "wanji-sales-wechat/request";
|
|
@@ -27,6 +28,10 @@ export interface StoredMessage {
|
|
|
27
28
|
senderId?: string;
|
|
28
29
|
}
|
|
29
30
|
export interface SavedWechatState {
|
|
31
|
+
autoDraftedMessageId?: string;
|
|
32
|
+
autoDraftSuggestion?: Pick<SalesReply, 'judgment' | 'wechat' | 'next_step' | 'no_send'>;
|
|
33
|
+
generationError?: string;
|
|
34
|
+
generationNoReply?: true;
|
|
30
35
|
draft?: string;
|
|
31
36
|
draftKind?: 'edited' | 'agent' | 'empty';
|
|
32
37
|
progress?: Contact['progress'];
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface WeKnoraConnection {
|
|
2
|
+
baseUrl: string;
|
|
3
|
+
apiKey: string;
|
|
4
|
+
tenantId?: string;
|
|
5
|
+
}
|
|
6
|
+
/** Connection values are accepted only from the Host's installation config. */
|
|
7
|
+
export declare function resolveWeKnoraConnection(raw: unknown, label: string): WeKnoraConnection | undefined;
|
|
8
|
+
export declare function readWeKnoraData(response: Response): Promise<Record<string, unknown>>;
|
|
@@ -142,6 +142,9 @@ function validateSalesBatch(value) {
|
|
|
142
142
|
return value;
|
|
143
143
|
}
|
|
144
144
|
|
|
145
|
+
// src/customer-intent.ts
|
|
146
|
+
var intentSemanticPolicyVersion = 2;
|
|
147
|
+
|
|
145
148
|
// src/turn-packet.ts
|
|
146
149
|
function bindProgress(raw, packet) {
|
|
147
150
|
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw Error("\u5BA2\u6237\u8FDB\u5C55\u5FC5\u987B\u662F\u5E26\u6765\u6E90\u7684\u5BF9\u8C61\u3002");
|
|
@@ -149,7 +152,8 @@ function bindProgress(raw, packet) {
|
|
|
149
152
|
if (Object.keys(p).sort().join(",") !== "artifacts,decisions,source_id,stage" || !["exploring", "evaluating", "confirming", "paused", "declined"].includes(String(p.stage)) || !Array.isArray(p.decisions) || p.decisions.length > 16 || !Array.isArray(p.artifacts) || p.artifacts.length > 8) throw Error("\u8FDB\u5C55\u7ED3\u6784\u65E0\u6548\uFF1B\u4E0D\u80FD\u5939\u5E26\u4EF7\u683C\u6279\u51C6\u6216\u6267\u884C\u7ED3\u679C\u3002");
|
|
150
153
|
const bind = (id, customerOnly = false) => {
|
|
151
154
|
const s = typeof id === "string" ? packet.sources[id] : void 0;
|
|
152
|
-
if (
|
|
155
|
+
if (customerOnly && s?.authority !== "customer") throw Error("progress.artifacts\u6765\u6E90 " + String(id) + " \u4E0D\u662F\u5BA2\u6237\u539F\u8BDD\uFF0C\u4E0D\u80FD\u8BC1\u660E\u5BA2\u6237\u5DF2\u6536\u5230\u6216\u770B\u8FC7\u6750\u6599\u3002\u53EA\u5F15\u7528sources\u4E2Dauthority\u4E3Acustomer\u7684\u6765\u6E90\uFF1B\u516C\u53F8\u8BF4\u660E\u6216deal\u80CC\u666F\u4E0D\u80FD\u66FF\u4EE3\u3002\u6CA1\u6709\u6B64\u7C7B\u6765\u6E90\u7684\u65E7\u6750\u6599\u72B6\u6001\u7559\u7A7A\u3002");
|
|
156
|
+
if (!s || !["customer", "deal"].includes(s.authority)) throw Error("progress\u6765\u6E90 " + String(id) + " \u4E0D\u662F\u5BA2\u6237\u8BC1\u636E\u3002Q/V/O\u516C\u53F8\u6761\u4EF6\u5DF2\u4FDD\u7559\u5728approved_offer/current_company_facts\uFF0C\u4E0D\u653E\u5165\u5BA2\u6237progress\uFF1B\u53EA\u5F15\u7528C/F/P\u4E2D\u7684\u5BA2\u6237\u539F\u8BDD\u6216\u660E\u786E\u5BA2\u6237\u80CC\u666F\u3002");
|
|
153
157
|
return { source_id: id, quote: s.text };
|
|
154
158
|
};
|
|
155
159
|
const stage = bind(p.source_id), topics = /* @__PURE__ */ new Set(), artifacts = /* @__PURE__ */ new Set();
|
|
@@ -158,14 +162,14 @@ function bindProgress(raw, packet) {
|
|
|
158
162
|
topics.add(v.topic);
|
|
159
163
|
return { ...bind(v.source_id), topic: v.topic, meaning: v.meaning };
|
|
160
164
|
}), artifacts: p.artifacts.map((v) => {
|
|
161
|
-
if (!v || Object.keys(v).sort().join(",") !== "kind,source_id,status" || !["sample", "intro", "confirmation"].includes(v.kind) || !["requested", "received", "reviewed"].includes(v.status) || artifacts.has(v.kind)) throw Error("progress.artifacts\u6BCF\u9879\u53EA\u80FD\u542Bkind\u3001status\u3001source_id\
|
|
165
|
+
if (!v || Object.keys(v).sort().join(",") !== "kind,source_id,status" || !["sample", "intro", "confirmation"].includes(v.kind) || !["requested", "received", "reviewed"].includes(v.status) || artifacts.has(v.kind)) throw Error("progress.artifacts\u6BCF\u9879\u53EA\u80FD\u542Bkind\u3001status\u3001source_id\uFF1Bkind\u4EC5sample/intro/confirmation\uFF0C\u64CD\u4F5C\u6587\u6863\u3001\u89C6\u9891\u548C\u56FE\u7247\u7EDF\u4E00\u5F52intro\uFF0C\u4E0D\u80FD\u586Bdocument/video/image\uFF1B\u540C\u7C7B\u6700\u591A\u4E00\u9879\u3002topic/meaning\u5C5E\u4E8Edecisions\uFF0C\u4E0D\u80FD\u653E\u8FDBartifacts\uFF0C\u72B6\u6001\u4EC5requested/received/reviewed\u3002");
|
|
162
166
|
artifacts.add(v.kind);
|
|
163
167
|
return { ...bind(v.source_id, true), kind: v.kind, status: v.status };
|
|
164
168
|
}) };
|
|
165
169
|
}
|
|
166
170
|
function parseSavedProgress(raw) {
|
|
167
171
|
const p = raw;
|
|
168
|
-
if (!p || typeof p !== "object" || Object.keys(p).sort().join(",") !== "artifacts,decisions,quote,source_id,stage" || !Array.isArray(p.decisions) || !Array.isArray(p.artifacts)) throw Error("INVALID_PROGRESS");
|
|
172
|
+
if (!p || typeof p !== "object" || Object.keys(p).filter((k) => k !== "pending").sort().join(",") !== "artifacts,decisions,quote,source_id,stage" || !Array.isArray(p.decisions) || !Array.isArray(p.artifacts)) throw Error("INVALID_PROGRESS");
|
|
169
173
|
const sources = /* @__PURE__ */ Object.create(null);
|
|
170
174
|
const source = (item, keys) => {
|
|
171
175
|
if (!item || Object.keys(item).sort().join(",") !== keys || typeof item.quote !== "string" || !item.quote.trim() || typeof item.source_id !== "string" || !/^[CFP]\d+$/.test(item.source_id) || sources[item.source_id] && sources[item.source_id].text !== item.quote) throw Error("INVALID_PROGRESS");
|
|
@@ -174,12 +178,40 @@ function parseSavedProgress(raw) {
|
|
|
174
178
|
source({ source_id: p.source_id, quote: p.quote }, "quote,source_id");
|
|
175
179
|
for (const d of p.decisions) source(d, "meaning,quote,source_id,topic");
|
|
176
180
|
for (const a of p.artifacts) source(a, "kind,quote,source_id,status");
|
|
177
|
-
|
|
181
|
+
if (p.pending !== void 0) {
|
|
182
|
+
if (!Array.isArray(p.pending) || p.pending.length > 4) throw Error("INVALID_PROGRESS");
|
|
183
|
+
for (const task of p.pending) {
|
|
184
|
+
if (!task || Object.keys(task).sort().join(",") !== "basis,quote,source_id,topic" || !["returns", "timing", "fees", "permissions", "scope"].includes(task.topic) || typeof task.basis !== "string" || !/^[a-f0-9]{1,8}$/.test(task.basis) || typeof task.quote !== "string" || task.quote.length > 6e3 || !/^C\d+$|^P\d+$/.test(task.source_id)) throw Error("INVALID_PROGRESS");
|
|
185
|
+
source({ source_id: task.source_id, quote: task.quote }, "quote,source_id");
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const bound = bindProgress({ stage: p.stage, source_id: p.source_id, decisions: p.decisions.map(({ quote, ...d }) => d), artifacts: p.artifacts.map(({ quote, ...a }) => a) }, { sources });
|
|
189
|
+
return p.pending ? { ...bound, pending: structuredClone(p.pending) } : bound;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// src/wechat-draft-input.ts
|
|
193
|
+
var attachmentReplies = /* @__PURE__ */ new Map([
|
|
194
|
+
["voice", "\u8BED\u97F3\u6536\u5230\u4E86\uFF0C\u65B9\u4FBF\u7684\u8BDD\u628A\u91CD\u70B9\u6253\u51E0\u4E2A\u5B57\u7ED9\u6211\uFF0C\u6211\u597D\u63A5\u7740\u5E2E\u4F60\u770B\u3002"],
|
|
195
|
+
["file", "\u6587\u4EF6\u6536\u5230\u4E86\uFF0C\u4F60\u60F3\u8BA9\u6211\u91CD\u70B9\u770B\u54EA\u4E00\u5757\uFF1F"],
|
|
196
|
+
["image", "\u56FE\u6536\u5230\u4E86\uFF0C\u4F60\u60F3\u8BA9\u6211\u5E2E\u4F60\u770B\u56FE\u91CC\u7684\u54EA\u4E00\u5904\uFF1F"],
|
|
197
|
+
["video", "\u89C6\u9891\u6536\u5230\u4E86\uFF0C\u4F60\u60F3\u8BA9\u6211\u91CD\u70B9\u770B\u54EA\u4E00\u6BB5\uFF1F"]
|
|
198
|
+
]);
|
|
199
|
+
function attachmentReply(kind) {
|
|
200
|
+
return attachmentReplies.get(kind);
|
|
178
201
|
}
|
|
179
202
|
|
|
180
203
|
// src/wechat/repository.ts
|
|
181
204
|
var hash = (v) => createHash("sha256").update(JSON.stringify(v)).digest("hex");
|
|
182
205
|
var previewLabels = { image: "\u56FE\u7247", voice: "\u8BED\u97F3", video: "\u89C6\u9891", location: "\u4F4D\u7F6E", call: "\u901A\u8BDD", emoji: "\u8868\u60C5", link: "\u94FE\u63A5", file: "\u6587\u4EF6", mini_program: "\u5C0F\u7A0B\u5E8F", transfer: "\u8F6C\u8D26", red_packet: "\u7EA2\u5305", quote: "\u5F15\u7528", system: "\u7CFB\u7EDF\u6D88\u606F", unknown: "\u672A\u77E5\u6D88\u606F" };
|
|
206
|
+
var replyText = (message) => {
|
|
207
|
+
const text = message.text?.trim();
|
|
208
|
+
if (message.kind === "emoji") return !text || text.startsWith("<") || /^\[(?:emoji|表情|动画表情|动态表情|自定义表情)\]$/i.test(text) ? "[emoji]" : text;
|
|
209
|
+
return text && ["text", "quote", "link"].includes(message.kind) ? message.text : void 0;
|
|
210
|
+
};
|
|
211
|
+
function replyInputChanged(previous, incoming) {
|
|
212
|
+
if (incoming.direction === "system" && (!previous || previous.direction === "system")) return false;
|
|
213
|
+
return !previous || previous.direction !== incoming.direction || previous.kind !== incoming.kind || previous.sent_at !== incoming.sent_at || previous.sort_seq !== incoming.sort_seq || previous.local_id !== incoming.local_id || replyText(previous) !== replyText(incoming);
|
|
214
|
+
}
|
|
183
215
|
var WechatRepository = class _WechatRepository {
|
|
184
216
|
db;
|
|
185
217
|
closed = false;
|
|
@@ -187,6 +219,7 @@ var WechatRepository = class _WechatRepository {
|
|
|
187
219
|
this.db = new DatabaseSync(path);
|
|
188
220
|
this.db.exec(`
|
|
189
221
|
PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
|
|
222
|
+
CREATE TABLE IF NOT EXISTS deliveries(id TEXT PRIMARY KEY,workspace TEXT NOT NULL,contact_id TEXT NOT NULL,message_id TEXT NOT NULL,text TEXT NOT NULL,status TEXT NOT NULL,created TEXT NOT NULL,baseline TEXT NOT NULL,receipt TEXT);
|
|
190
223
|
CREATE TABLE IF NOT EXISTS active(workspace TEXT PRIMARY KEY,account TEXT NOT NULL);
|
|
191
224
|
CREATE TABLE IF NOT EXISTS chats(id TEXT PRIMARY KEY,workspace TEXT NOT NULL,account TEXT NOT NULL,chat_key TEXT NOT NULL,name TEXT NOT NULL,history_state TEXT,version INTEGER NOT NULL DEFAULT 0,handled INTEGER NOT NULL DEFAULT 0,crm TEXT,state TEXT NOT NULL DEFAULT '{}');
|
|
192
225
|
CREATE INDEX IF NOT EXISTS chats_scope ON chats(workspace,account);
|
|
@@ -198,9 +231,19 @@ var WechatRepository = class _WechatRepository {
|
|
|
198
231
|
CREATE TABLE IF NOT EXISTS runs(workspace TEXT NOT NULL,run_id TEXT NOT NULL,digest TEXT NOT NULL,result TEXT NOT NULL,PRIMARY KEY(workspace,run_id));
|
|
199
232
|
CREATE TABLE IF NOT EXISTS checkpoints(scope TEXT PRIMARY KEY,revision TEXT,active_revision TEXT,next_part INTEGER,part_count INTEGER);
|
|
200
233
|
CREATE TABLE IF NOT EXISTS pairing(workspace TEXT PRIMARY KEY,token TEXT NOT NULL);
|
|
234
|
+
CREATE TABLE IF NOT EXISTS customer_intents(
|
|
235
|
+
chat_id TEXT PRIMARY KEY REFERENCES chats(id), revision INTEGER NOT NULL DEFAULT 1,
|
|
236
|
+
assessed INTEGER NOT NULL DEFAULT 0, due INTEGER NOT NULL, result TEXT
|
|
237
|
+
);
|
|
238
|
+
CREATE TABLE IF NOT EXISTS intent_quota_pause(workspace TEXT PRIMARY KEY,resume_at INTEGER NOT NULL);
|
|
239
|
+
CREATE TABLE IF NOT EXISTS intent_seed(workspace TEXT NOT NULL,account TEXT NOT NULL,PRIMARY KEY(workspace,account));
|
|
201
240
|
`);
|
|
202
241
|
if (!this.rows("PRAGMA table_info(messages)").some((c) => c.name === "source_revision")) this.db.exec("ALTER TABLE messages ADD COLUMN source_revision TEXT");
|
|
203
242
|
for (const table of ["chats", "messages", "sources", "media"]) if (!this.rows("PRAGMA table_info(" + table + ")").some((c) => c.name === "metadata")) this.db.exec("ALTER TABLE " + table + " ADD COLUMN metadata TEXT NOT NULL DEFAULT '{}'");
|
|
243
|
+
if (!this.rows("PRAGMA table_info(messages)").some((c) => c.name === "intent_revision")) {
|
|
244
|
+
this.db.exec("ALTER TABLE messages ADD COLUMN intent_revision INTEGER NOT NULL DEFAULT 0");
|
|
245
|
+
}
|
|
246
|
+
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");
|
|
204
247
|
this.db.exec(`INSERT OR IGNORE INTO avatars(workspace,account,owner,media_id,observed_at)
|
|
205
248
|
SELECT c.workspace,c.account,c.chat_key,m.id,0 FROM chats c JOIN media m
|
|
206
249
|
ON m.id=json_extract(c.metadata,'$.avatarId') AND m.workspace=c.workspace AND m.account=c.account`);
|
|
@@ -225,7 +268,7 @@ var WechatRepository = class _WechatRepository {
|
|
|
225
268
|
if (!row) throw Error("WECHAT_ACCOUNT_SCOPE");
|
|
226
269
|
return row;
|
|
227
270
|
}
|
|
228
|
-
importBatch(workspace, raw) {
|
|
271
|
+
importBatch(workspace, raw, trackIntent = false, initial = false) {
|
|
229
272
|
if (typeof workspace !== "string" || !workspace.trim() || workspace.length > 256) throw Error("WECHAT_WORKSPACE_INVALID");
|
|
230
273
|
const encoded = JSON.stringify(raw);
|
|
231
274
|
if (encoded.length > 65 * 1024 * 1024) throw Error("WECHAT_BATCH_TOO_LARGE");
|
|
@@ -247,8 +290,13 @@ var WechatRepository = class _WechatRepository {
|
|
|
247
290
|
const source = hash([workspace, account, batch.source.kind ?? "", batch.source.device_id ?? ""]);
|
|
248
291
|
const active = this.row("SELECT account FROM active WHERE workspace=?", workspace)?.account;
|
|
249
292
|
if (batch.delivery && active !== account) throw Error("WANJI_RESYNC_REQUIRED: media account baseline missing");
|
|
250
|
-
const changed = /* @__PURE__ */ new Set();
|
|
293
|
+
const changed = /* @__PURE__ */ new Set(), replyChanges = /* @__PURE__ */ new Set(), voiceChanges = /* @__PURE__ */ new Map();
|
|
251
294
|
let messages = 0, avatarsUpdated = 0;
|
|
295
|
+
const trackVoiceChange = (chatId, id) => {
|
|
296
|
+
const voices = voiceChanges.get(chatId) ?? /* @__PURE__ */ new Set();
|
|
297
|
+
voices.add(id);
|
|
298
|
+
voiceChanges.set(chatId, voices);
|
|
299
|
+
};
|
|
252
300
|
const receipt = batch.sync ? { protocol: batch.sync.protocol, scope: batch.sync.scope, revision: batch.sync.revision, part_index: batch.sync.part_index, part_count: batch.sync.part_count, committed: batch.sync.part_index === batch.sync.part_count - 1 } : void 0;
|
|
253
301
|
this.db.exec("BEGIN IMMEDIATE");
|
|
254
302
|
try {
|
|
@@ -280,7 +328,9 @@ var WechatRepository = class _WechatRepository {
|
|
|
280
328
|
if (batch.delivery && !existing) throw Error("WANJI_RESYNC_REQUIRED: media chat missing");
|
|
281
329
|
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);
|
|
282
330
|
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);
|
|
283
|
-
if (!batch.delivery && (!existing || existing.name !== chat.display_name || existing.metadata !== encodedMetadata)) changed.add(chatId);
|
|
331
|
+
if (!batch.delivery && (!existing || existing.name !== chat.display_name || existing.history_state !== (chat.history_state ?? null) || existing.metadata !== encodedMetadata)) changed.add(chatId);
|
|
332
|
+
const advanceIntent = trackIntent && (!(initial || active !== account || batch.sync?.mode === "full") || !!this.row("SELECT 1 FROM customer_intents WHERE chat_id=?", chatId));
|
|
333
|
+
let intentRevision;
|
|
284
334
|
for (const m of chat.messages) {
|
|
285
335
|
const oldSource = this.row("SELECT * FROM sources WHERE scope=? AND chat_id=? AND message_key=?", source, chatId, m.message_key);
|
|
286
336
|
if (batch.delivery) {
|
|
@@ -291,6 +341,7 @@ var WechatRepository = class _WechatRepository {
|
|
|
291
341
|
if (old2.media_id !== mediaId2) {
|
|
292
342
|
this.db.prepare("UPDATE messages SET media_id=? WHERE id=?").run(mediaId2, old2.id);
|
|
293
343
|
changed.add(chatId);
|
|
344
|
+
if (old2.kind === "voice" && old2.direction === "inbound" && old2.auto_draft_arrival === 1) trackVoiceChange(chatId, old2.id);
|
|
294
345
|
}
|
|
295
346
|
continue;
|
|
296
347
|
}
|
|
@@ -298,15 +349,33 @@ var WechatRepository = class _WechatRepository {
|
|
|
298
349
|
const id = server ? hash([chatId, "server", server]) : hash([chatId, "local", source, m.message_key]);
|
|
299
350
|
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;
|
|
300
351
|
if (!old || 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)) {
|
|
352
|
+
if (replyInputChanged(old, m)) replyChanges.add(chatId);
|
|
353
|
+
if (m.kind === "voice" && m.direction === "inbound" && old?.auto_draft_arrival === 1 && old.media_id !== mediaId) trackVoiceChange(chatId, id);
|
|
301
354
|
this.db.prepare("INSERT INTO messages(id,chat_id,sent_at,sort_seq,local_id,direction,kind,text,media_id,source_revision,metadata) VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET 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));
|
|
302
355
|
changed.add(chatId);
|
|
303
356
|
if (!old) messages++;
|
|
304
357
|
}
|
|
358
|
+
if (!old && !initial && active === account && batch.sync?.mode !== "full" && m.direction === "inbound" && (replyText(m) || attachmentReply(m.kind))) {
|
|
359
|
+
this.db.prepare("UPDATE messages SET auto_draft_arrival=1 WHERE id=?").run(id);
|
|
360
|
+
}
|
|
361
|
+
const meaningful = (row) => row.direction !== "system" && ["text", "quote", "link"].includes(row.kind) && typeof row.text === "string" && !!row.text.trim();
|
|
362
|
+
const intentChanged = !old ? meaningful(m) : (meaningful(m) || meaningful(old)) && (old.text !== m.text || old.direction !== m.direction || old.kind !== m.kind);
|
|
363
|
+
if (advanceIntent && intentChanged) {
|
|
364
|
+
intentRevision ??= this.queueIntentRow(chatId, Date.now() + 3500, true);
|
|
365
|
+
this.db.prepare("UPDATE messages SET intent_revision=? WHERE id=?").run(intentRevision, id);
|
|
366
|
+
}
|
|
305
367
|
this.db.prepare("INSERT INTO sources(scope,chat_id,message_key,message_id,source_revision,metadata) VALUES(?,?,?,?,?,?) ON CONFLICT(scope,chat_id,message_key) DO UPDATE SET message_id=excluded.message_id,source_revision=excluded.source_revision,metadata=excluded.metadata").run(source, chatId, m.message_key, id, m.source_revision ?? null, JSON.stringify(m));
|
|
306
368
|
}
|
|
307
369
|
}
|
|
308
370
|
for (const id of changed) {
|
|
309
|
-
const row = this.row("SELECT state FROM chats WHERE id=?", id), state = JSON.parse(row.state);
|
|
371
|
+
const row = this.row("SELECT version,state,handled FROM chats WHERE id=?", id), state = JSON.parse(row.state);
|
|
372
|
+
const latest = voiceChanges.has(id) && active === account ? this.listMessages(workspace, id, void 0, 1, true)[0] : void 0;
|
|
373
|
+
const refreshVoice = !!latest && row.version > row.handled && voiceChanges.get(id)?.has(latest.id);
|
|
374
|
+
if (!replyChanges.has(id) && !refreshVoice) continue;
|
|
375
|
+
delete state.autoDraftSuggestion;
|
|
376
|
+
delete state.autoDraftedMessageId;
|
|
377
|
+
delete state.generationError;
|
|
378
|
+
delete state.generationNoReply;
|
|
310
379
|
if (state.draftKind === "agent") {
|
|
311
380
|
state.draft = "";
|
|
312
381
|
state.draftKind = "empty";
|
|
@@ -324,6 +393,97 @@ var WechatRepository = class _WechatRepository {
|
|
|
324
393
|
throw error;
|
|
325
394
|
}
|
|
326
395
|
}
|
|
396
|
+
queueIntentRow(id, due, overwrite) {
|
|
397
|
+
const onConflict = overwrite ? "DO UPDATE SET revision=revision+1,due=excluded.due" : "DO NOTHING";
|
|
398
|
+
this.db.prepare(`INSERT INTO customer_intents(chat_id,due) VALUES(?,?) ON CONFLICT(chat_id) ${onConflict}`).run(id, due);
|
|
399
|
+
return this.row("SELECT revision FROM customer_intents WHERE chat_id=?", id).revision;
|
|
400
|
+
}
|
|
401
|
+
queueIntent(workspace, id) {
|
|
402
|
+
this.scope(workspace, id);
|
|
403
|
+
this.queueIntentRow(id, Date.now(), false);
|
|
404
|
+
this.requeueLegacyIntents(workspace, id);
|
|
405
|
+
}
|
|
406
|
+
requeueLegacyIntents(workspace, contactId) {
|
|
407
|
+
this.db.prepare(`UPDATE customer_intents SET revision=revision+1,due=?
|
|
408
|
+
WHERE assessed=revision AND (
|
|
409
|
+
(json_extract(result,'$.status')='ready' AND COALESCE(json_extract(result,'$.policyVersion'),1)<?)
|
|
410
|
+
OR (json_extract(result,'$.status')='failed' AND json_extract(result,'$.policyVersion')=?)
|
|
411
|
+
)
|
|
412
|
+
AND json_extract(result,'$.products')='{}' AND json_type(result,'$.crm') IS NULL
|
|
413
|
+
AND EXISTS(SELECT 1 FROM chats c JOIN active a ON a.workspace=c.workspace AND a.account=c.account
|
|
414
|
+
WHERE c.id=customer_intents.chat_id AND c.workspace=? AND c.crm IS NULL)
|
|
415
|
+
${contactId === void 0 ? "" : "AND chat_id=?"}`).run(Date.now(), intentSemanticPolicyVersion, intentSemanticPolicyVersion, workspace, ...contactId === void 0 ? [] : [contactId]);
|
|
416
|
+
}
|
|
417
|
+
seedIntents(workspace) {
|
|
418
|
+
const active = this.row("SELECT account FROM active WHERE workspace=?", workspace);
|
|
419
|
+
if (!active) return;
|
|
420
|
+
this.requeueLegacyIntents(workspace);
|
|
421
|
+
if (this.row("SELECT 1 FROM intent_seed WHERE workspace=? AND account=?", workspace, active.account)) return;
|
|
422
|
+
const contacts = this.rows(`SELECT c.id FROM chats c WHERE c.workspace=? AND c.account=?
|
|
423
|
+
AND (c.crm IS NOT NULL OR EXISTS(SELECT 1 FROM messages m WHERE m.chat_id=c.id AND m.direction='inbound' AND m.kind IN ('text','quote','link') AND length(trim(m.text))>0))
|
|
424
|
+
ORDER BY c.crm IS NULL,(SELECT MAX(sent_at) FROM messages m WHERE m.chat_id=c.id) DESC,c.id LIMIT 10`, workspace, active.account);
|
|
425
|
+
if (!contacts.length) return;
|
|
426
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
427
|
+
try {
|
|
428
|
+
for (const contact of contacts) this.queueIntentRow(contact.id, Date.now(), false);
|
|
429
|
+
this.db.prepare("INSERT OR IGNORE INTO intent_seed VALUES(?,?)").run(workspace, active.account);
|
|
430
|
+
this.db.exec("COMMIT");
|
|
431
|
+
} catch (error) {
|
|
432
|
+
this.db.exec("ROLLBACK");
|
|
433
|
+
throw error;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
nextIntent(workspace) {
|
|
437
|
+
const row = this.row(`SELECT i.chat_id,i.revision,MAX(i.due,COALESCE(p.resume_at,0)) AS due FROM customer_intents i
|
|
438
|
+
JOIN chats c ON c.id=i.chat_id JOIN active a ON a.workspace=c.workspace AND a.account=c.account
|
|
439
|
+
LEFT JOIN intent_quota_pause p ON p.workspace=c.workspace
|
|
440
|
+
WHERE c.workspace=? AND i.assessed<i.revision ORDER BY i.due,c.id LIMIT 1`, workspace);
|
|
441
|
+
if (row) return { contactId: row.chat_id, version: row.revision, due: row.due };
|
|
442
|
+
}
|
|
443
|
+
getIntentInput(workspace, job) {
|
|
444
|
+
const chat = this.scope(workspace, job.contactId);
|
|
445
|
+
const row = this.row("SELECT * FROM customer_intents WHERE chat_id=? AND revision=? AND assessed<revision", chat.id, job.version);
|
|
446
|
+
if (!row) return;
|
|
447
|
+
const messages = this.rows(`SELECT id,sent_at,direction,text,intent_revision FROM messages WHERE chat_id=? AND direction IN ('inbound','outbound')
|
|
448
|
+
AND kind IN ('text','quote','link') AND length(trim(text))>0 ORDER BY sent_at DESC,length(sort_seq) DESC,sort_seq DESC,length(local_id) DESC,local_id DESC,id DESC LIMIT 36`, chat.id);
|
|
449
|
+
const previous = row.result ? JSON.parse(row.result) : void 0;
|
|
450
|
+
const needsLegacyEvidence = previous && (previous.policyVersion ?? 1) < intentSemanticPolicyVersion && !chat.crm && !Object.keys(previous.products).length;
|
|
451
|
+
const evaluated = needsLegacyEvidence ? 0 : previous?.evaluatedVersion ?? 0;
|
|
452
|
+
return {
|
|
453
|
+
...job,
|
|
454
|
+
crm: chat.crm ? JSON.parse(chat.crm) : void 0,
|
|
455
|
+
previous,
|
|
456
|
+
messages: messages.reverse().map((m) => ({ id: m.id, time: m.sent_at, direction: m.direction === "inbound" ? "in" : "out", text: m.text.slice(0, 2e3), changed: !evaluated || m.intent_revision > evaluated }))
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
finishIntent(workspace, id, result) {
|
|
460
|
+
const scope = `chat_id=? AND revision=? AND assessed<revision
|
|
461
|
+
AND EXISTS(SELECT 1 FROM chats c JOIN active a ON a.workspace=c.workspace AND a.account=c.account WHERE c.id=? AND c.workspace=?)`;
|
|
462
|
+
const params = [JSON.stringify(result), id, result.version, id, workspace];
|
|
463
|
+
if (!result.retryAt) {
|
|
464
|
+
return Number(this.db.prepare(`UPDATE customer_intents SET assessed=?,result=? WHERE ${scope}`).run(result.version, ...params).changes) > 0;
|
|
465
|
+
}
|
|
466
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
467
|
+
try {
|
|
468
|
+
const saved = Number(this.db.prepare(`UPDATE customer_intents SET due=?,result=? WHERE ${scope}`).run(result.retryAt, ...params).changes) > 0;
|
|
469
|
+
if (saved) this.db.prepare(`INSERT INTO intent_quota_pause VALUES(?,?) ON CONFLICT(workspace)
|
|
470
|
+
DO UPDATE SET resume_at=MAX(resume_at,excluded.resume_at)`).run(workspace, result.retryAt);
|
|
471
|
+
this.db.exec("COMMIT");
|
|
472
|
+
return saved;
|
|
473
|
+
} catch (error) {
|
|
474
|
+
this.db.exec("ROLLBACK");
|
|
475
|
+
throw error;
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
intentFor(id) {
|
|
479
|
+
const row = this.row(`SELECT i.revision,i.assessed,i.result,p.resume_at FROM customer_intents i JOIN chats c ON c.id=i.chat_id
|
|
480
|
+
LEFT JOIN intent_quota_pause p ON p.workspace=c.workspace WHERE i.chat_id=?`, id);
|
|
481
|
+
if (!row) return;
|
|
482
|
+
const last = row.result ? JSON.parse(row.result) : void 0;
|
|
483
|
+
if (row.assessed === row.revision) return last;
|
|
484
|
+
const retryAt = row.resume_at > Date.now() ? row.resume_at : void 0;
|
|
485
|
+
return { ...last, products: last?.products ?? {}, version: row.revision, status: "pending", retryAt };
|
|
486
|
+
}
|
|
327
487
|
listContacts(workspace, limit = 200, offset = 0) {
|
|
328
488
|
return this.rows("SELECT c.* FROM chats c JOIN active a ON a.workspace=c.workspace AND a.account=c.account WHERE c.workspace=? ORDER BY (SELECT MAX(sent_at) FROM messages WHERE chat_id=c.id) DESC,c.id LIMIT ? OFFSET ?", workspace, Math.max(1, Math.min(200, limit)), Math.max(0, offset)).map((c) => this.project(c, 2));
|
|
329
489
|
}
|
|
@@ -331,47 +491,113 @@ var WechatRepository = class _WechatRepository {
|
|
|
331
491
|
return this.project(this.scope(workspace, id), 100);
|
|
332
492
|
}
|
|
333
493
|
project(c, limit) {
|
|
334
|
-
const recent = this.listMessages(c.workspace, c.id, void 0, limit
|
|
494
|
+
const recent = this.listMessages(c.workspace, c.id, void 0, limit, true), last = recent.at(-1);
|
|
495
|
+
const latest = this.listMessages(c.workspace, c.id, void 0, 1)[0];
|
|
335
496
|
let budget = 16e3;
|
|
336
497
|
const messages = [];
|
|
337
498
|
for (const m of [...recent].reverse()) {
|
|
338
|
-
|
|
339
|
-
if (m.
|
|
340
|
-
|
|
341
|
-
|
|
499
|
+
const text = replyText(m);
|
|
500
|
+
if (m.direction === "system" || !text) continue;
|
|
501
|
+
if (text.length > budget) break;
|
|
502
|
+
budget -= text.length;
|
|
503
|
+
messages.unshift({ id: m.id, direction: m.direction === "inbound" ? "in" : "out", text, time: m.sentAt });
|
|
342
504
|
}
|
|
505
|
+
const latestInbound = recent.filter((m) => m.direction === "inbound").at(-1);
|
|
343
506
|
const state = JSON.parse(c.state);
|
|
507
|
+
const hasText = !!latestInbound && messages.some((m) => m.id === latestInbound.id);
|
|
508
|
+
const settled = state.sourceVersion === c.version && (state.draftKind === "agent" || state.generationError || state.generationNoReply || state.draftKind === "edited" && state.autoDraftedMessageId === latestInbound?.id && !!latestInbound);
|
|
509
|
+
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;
|
|
510
|
+
const intent = this.intentFor(c.id);
|
|
344
511
|
const avatar = this.row("SELECT media_id,observed_at FROM avatars WHERE workspace=? AND account=? AND owner=?", c.workspace, c.account, c.chat_key);
|
|
345
512
|
const self = this.row("SELECT media_id,observed_at FROM avatars WHERE workspace=? AND account=? AND owner=?", c.workspace, c.account, c.account);
|
|
346
|
-
return { id: c.id, name: c.name, initials: Array.from(String(c.name))[0] ?? "\u5FAE", segment: "\u5FAE\u4FE1", time: latest?.sentAt ?? "", preview: latest ? latest.text || `[${previewLabels[latest.kind] ?? latest.kind}]` : "", status: last?.direction === "inbound" && c.version > c.handled ? "pending" : "handled", unread: last?.direction === "inbound" && c.version > c.handled ? 1 : 0, product: "\u4E07\u673A\u7BA1\u5BB6 ERP / \u4E07\u673A\u5858", budget: "\u5F85\u786E\u8BA4", moneyAmounts: [], tags: [], facts: [], messages, candidates: [], wechat: { accountId: c.account, chatKey: c.chat_key, version: c.version, ...avatar ? { avatarId: avatar.media_id, avatarUpdatedAt: avatar.observed_at } : JSON.parse(c.metadata).avatarId ? { avatarId: JSON.parse(c.metadata).avatarId } : {}, ...self ? { selfAvatarId: self.media_id, selfAvatarUpdatedAt: self.observed_at } : {}, ...c.history_state ? { historyState: c.history_state } : {} }, ...c.crm ? { crm: JSON.parse(c.crm) } : {}, ...state.progress ? { progress: state.progress } : {} };
|
|
513
|
+
return { id: c.id, name: c.name, initials: Array.from(String(c.name))[0] ?? "\u5FAE", segment: "\u5FAE\u4FE1", time: latest?.sentAt ?? "", preview: latest ? latest.text || `[${previewLabels[latest.kind] ?? latest.kind}]` : "", status: last?.direction === "inbound" && c.version > c.handled ? "pending" : "handled", unread: last?.direction === "inbound" && c.version > c.handled ? 1 : 0, product: "\u4E07\u673A\u7BA1\u5BB6 ERP / \u4E07\u673A\u5858", budget: "\u5F85\u786E\u8BA4", moneyAmounts: [], tags: [], facts: [], messages, candidates: [], wechat: { accountId: c.account, chatKey: c.chat_key, version: c.version, ...canDraft ? { autoDraftMessageId: latestInbound.id } : {}, ...latestInbound ? { latestInbound: { id: latestInbound.id, kind: latestInbound.kind, hasText, ...latestInbound.kind === "voice" && latestInbound.mediaId ? { voiceMediaId: latestInbound.mediaId } : {} } } : {}, ...avatar ? { avatarId: avatar.media_id, avatarUpdatedAt: avatar.observed_at } : JSON.parse(c.metadata).avatarId ? { avatarId: JSON.parse(c.metadata).avatarId } : {}, ...self ? { selfAvatarId: self.media_id, selfAvatarUpdatedAt: self.observed_at } : {}, ...c.history_state ? { historyState: c.history_state } : {} }, ...c.crm ? { crm: JSON.parse(c.crm) } : {}, ...state.progress ? { progress: state.progress } : {}, ...intent ? { intent } : {} };
|
|
347
514
|
}
|
|
348
|
-
listMessages(workspace, id, before, limit = 100) {
|
|
515
|
+
listMessages(workspace, id, before, limit = 100, excludeSystem = false) {
|
|
349
516
|
this.scope(workspace, id);
|
|
350
517
|
const anchor = before ? this.row("SELECT sent_at,sort_seq,local_id,id FROM messages WHERE id=? AND chat_id=?", before, id) : void 0;
|
|
351
518
|
if (before && !anchor) throw Error("WECHAT_MESSAGE_CURSOR");
|
|
352
|
-
return this.rows(`SELECT * FROM messages WHERE chat_id=? ${anchor ? "AND (sent_at,length(sort_seq),sort_seq,length(local_id),local_id,id)<(?,?,?,?,?,?)" : ""} ORDER BY sent_at DESC,length(sort_seq) DESC,sort_seq DESC,length(local_id) DESC,local_id DESC,id DESC LIMIT ?`, id, ...anchor ? [anchor.sent_at, anchor.sort_seq.length, anchor.sort_seq, anchor.local_id.length, anchor.local_id, anchor.id] : [], Math.max(1, Math.min(200, limit))).reverse().map((m) => ({ id: m.id, direction: m.direction, kind: m.kind, text: m.text, sentAt: m.sent_at, sortSeq: m.sort_seq, localId: m.local_id, ...m.media_id ? { mediaId: m.media_id } : {}, rawType: JSON.parse(m.metadata).raw_type, senderId: JSON.parse(m.metadata).sender_wxid }));
|
|
519
|
+
return this.rows(`SELECT * FROM messages WHERE chat_id=? ${excludeSystem ? "AND direction<>'system'" : ""} ${anchor ? "AND (sent_at,length(sort_seq),sort_seq,length(local_id),local_id,id)<(?,?,?,?,?,?)" : ""} ORDER BY sent_at DESC,length(sort_seq) DESC,sort_seq DESC,length(local_id) DESC,local_id DESC,id DESC LIMIT ?`, id, ...anchor ? [anchor.sent_at, anchor.sort_seq.length, anchor.sort_seq, anchor.local_id.length, anchor.local_id, anchor.id] : [], Math.max(1, Math.min(200, limit))).reverse().map((m) => ({ id: m.id, direction: m.direction, kind: m.kind, text: m.text, sentAt: m.sent_at, sortSeq: m.sort_seq, localId: m.local_id, ...m.media_id ? { mediaId: m.media_id } : {}, rawType: JSON.parse(m.metadata).raw_type, senderId: JSON.parse(m.metadata).sender_wxid }));
|
|
520
|
+
}
|
|
521
|
+
getDeliverySource(workspace, id) {
|
|
522
|
+
const row = this.scope(workspace, id), contact = this.getContact(workspace, id), state = this.getState(workspace, id), meta = JSON.parse(row.metadata), inbound = contact.messages.filter((m) => m.direction === "in").at(-1);
|
|
523
|
+
return { accountId: row.account, chatKey: row.chat_key, version: row.version, messageId: contact.wechat?.latestInbound?.id ?? "", pending: contact.status === "pending", text: inbound?.text ?? "", draft: state.sourceVersion === row.version ? state.draft ?? "" : "", kind: state.draftKind ?? "empty", alias: meta.alias, name: row.name };
|
|
524
|
+
}
|
|
525
|
+
claimDelivery(workspace, key, input) {
|
|
526
|
+
if (workspace !== input.workspaceId) throw Error("WECHAT_DELIVERY_SCOPE");
|
|
527
|
+
const source = this.getDeliverySource(input.workspaceId, input.contactId);
|
|
528
|
+
if (source.version !== input.version || source.messageId !== input.messageId || source.draft !== input.text || !source.pending) throw Error("WECHAT_DELIVERY_STALE");
|
|
529
|
+
if (this.row("SELECT id FROM deliveries WHERE contact_id=? AND status IN ('unknown','awaiting-receipt','claimed')", input.contactId)) throw Error("WECHAT_DELIVERY_UNRESOLVED");
|
|
530
|
+
const previous = this.row("SELECT status FROM deliveries WHERE id=?", key);
|
|
531
|
+
if (previous?.status === "blocked" && !input.automatic) {
|
|
532
|
+
this.db.prepare("DELETE FROM deliveries WHERE id=? AND status='blocked'").run(key);
|
|
533
|
+
}
|
|
534
|
+
return Number(this.db.prepare("INSERT OR IGNORE INTO deliveries VALUES(?,?,?,?,?,?,?,?,NULL)").run(key, input.workspaceId, input.contactId, input.messageId, input.text, "claimed", (/* @__PURE__ */ new Date()).toISOString(), JSON.stringify(this.listMessages(input.workspaceId, input.contactId, void 0, 200).map((m) => m.id))).changes) === 1;
|
|
535
|
+
}
|
|
536
|
+
settleDelivery(workspace, key, status) {
|
|
537
|
+
this.db.prepare("UPDATE deliveries SET status=? WHERE id=? AND workspace=?").run(status, key, workspace);
|
|
538
|
+
}
|
|
539
|
+
deliveryStatus(workspace, id) {
|
|
540
|
+
this.scope(workspace, id);
|
|
541
|
+
const rows = this.rows("SELECT * FROM deliveries WHERE workspace=? AND contact_id=? ORDER BY created DESC", workspace, id);
|
|
542
|
+
for (const row of rows) {
|
|
543
|
+
if (row.status === "sent") continue;
|
|
544
|
+
const baseline = new Set(JSON.parse(row.baseline)), receipt = this.listMessages(workspace, id, void 0, 200).find((m) => m.direction === "outbound" && m.text === row.text && !baseline.has(m.id) && Date.parse(m.sentAt) >= Date.parse(row.created) - 1e4);
|
|
545
|
+
if (receipt) {
|
|
546
|
+
this.db.prepare("UPDATE deliveries SET status='sent',receipt=? WHERE id=?").run(receipt.id, row.id);
|
|
547
|
+
row.status = "sent";
|
|
548
|
+
} else if (row.status === "claimed") row.status = "unknown";
|
|
549
|
+
}
|
|
550
|
+
return rows[0] ? { status: rows[0].status, messageId: rows[0].message_id } : { status: "idle" };
|
|
353
551
|
}
|
|
354
552
|
getMedia(workspace, id) {
|
|
355
553
|
const row = this.row("SELECT m.* FROM media m JOIN active a ON a.workspace=m.workspace AND a.account=m.account WHERE m.workspace=? AND m.id=?", workspace, id);
|
|
356
554
|
if (!row) throw Error("WECHAT_MEDIA_SCOPE");
|
|
357
555
|
return { mimeType: row.mime, data: Buffer.from(row.data).toString("base64") };
|
|
358
556
|
}
|
|
359
|
-
|
|
557
|
+
getDraftVoice(workspace, contactId, messageId, version) {
|
|
558
|
+
const contact = this.getContact(workspace, contactId), inbound = contact.wechat?.latestInbound;
|
|
559
|
+
if (contact.wechat?.version !== version || inbound?.id !== messageId) throw Error("WECHAT_STATE_STALE");
|
|
560
|
+
if (!inbound.voiceMediaId) return;
|
|
561
|
+
const row = this.row("SELECT data FROM media WHERE workspace=? AND account=? AND id=? AND mime='audio/wav'", workspace, contact.wechat.accountId, inbound.voiceMediaId);
|
|
562
|
+
return row?.data;
|
|
563
|
+
}
|
|
564
|
+
bindCrm(workspace, id, binding, trackIntent = false) {
|
|
360
565
|
const c = this.scope(workspace, id);
|
|
361
566
|
if (!binding || binding.conversationId !== id || !/^1\d{10}$/.test(binding.customerPhone) || ![binding.salesName, binding.salesPhone].some((x) => typeof x === "string" && !!x.trim())) throw Error("WECHAT_CRM_BINDING_INVALID");
|
|
362
567
|
const normalized = { conversationId: id, customerPhone: binding.customerPhone, ...binding.salesName ? { salesName: binding.salesName } : {}, ...binding.salesPhone ? { salesPhone: binding.salesPhone } : {} };
|
|
363
568
|
if (c.crm && JSON.stringify(JSON.parse(c.crm)) !== JSON.stringify(normalized)) throw Error("CONVERSATION_IDENTITY_CHANGED");
|
|
364
|
-
|
|
569
|
+
if (c.crm) return;
|
|
570
|
+
this.db.exec("BEGIN IMMEDIATE");
|
|
571
|
+
try {
|
|
572
|
+
this.db.prepare("UPDATE chats SET crm=? WHERE id=?").run(JSON.stringify(normalized), id);
|
|
573
|
+
if (trackIntent) this.queueIntentRow(id, Date.now(), true);
|
|
574
|
+
this.db.exec("COMMIT");
|
|
575
|
+
} catch (error) {
|
|
576
|
+
this.db.exec("ROLLBACK");
|
|
577
|
+
throw error;
|
|
578
|
+
}
|
|
365
579
|
}
|
|
366
580
|
getState(workspace, id) {
|
|
367
581
|
return JSON.parse(this.scope(workspace, id).state);
|
|
368
582
|
}
|
|
369
583
|
saveState(workspace, id, state) {
|
|
370
584
|
const c = this.scope(workspace, id);
|
|
371
|
-
if (!state || Object.keys(state).some((k) => !["draft", "draftKind", "progress", "sourceVersion"].includes(k)) || state.draft !== void 0 && (typeof state.draft !== "string" || state.draft.length > 5e4) || state.draftKind !== void 0 && !["edited", "agent", "empty"].includes(state.draftKind) || state.sourceVersion !== void 0 && (!Number.isSafeInteger(state.sourceVersion) || state.sourceVersion < 0)) throw Error("WECHAT_STATE_INVALID");
|
|
372
|
-
if (state.
|
|
585
|
+
if (!state || Object.keys(state).some((k) => !["draft", "draftKind", "progress", "sourceVersion", "generationError", "generationNoReply", "autoDraftedMessageId", "autoDraftSuggestion"].includes(k)) || state.draft !== void 0 && (typeof state.draft !== "string" || state.draft.length > 5e4) || state.draftKind !== void 0 && !["edited", "agent", "empty"].includes(state.draftKind) || state.sourceVersion !== void 0 && (!Number.isSafeInteger(state.sourceVersion) || state.sourceVersion < 0)) throw Error("WECHAT_STATE_INVALID");
|
|
586
|
+
if (state.generationError !== void 0 && (typeof state.generationError !== "string" || state.generationError.length > 1e3)) throw Error("WECHAT_STATE_INVALID");
|
|
587
|
+
if (state.generationNoReply !== void 0 && state.generationNoReply !== true) throw Error("WECHAT_STATE_INVALID");
|
|
588
|
+
if ((state.draftKind === "agent" || state.generationError || state.generationNoReply) && state.sourceVersion !== c.version) throw Error("WECHAT_STATE_STALE");
|
|
589
|
+
const prior = JSON.parse(c.state);
|
|
590
|
+
if (state.autoDraftedMessageId !== void 0 && (state.sourceVersion !== c.version || typeof state.autoDraftedMessageId !== "string" || this.project(c, 100).wechat?.autoDraftMessageId !== state.autoDraftedMessageId && prior.autoDraftedMessageId !== state.autoDraftedMessageId)) throw Error("WECHAT_STATE_STALE");
|
|
591
|
+
if (state.autoDraftSuggestion !== void 0) {
|
|
592
|
+
const suggestion = state.autoDraftSuggestion;
|
|
593
|
+
if (state.sourceVersion !== c.version || state.draftKind !== "edited" || !suggestion || Object.keys(suggestion).sort().join(",") !== "judgment,next_step,no_send,wechat" || typeof suggestion.no_send !== "boolean" || ["judgment", "wechat", "next_step"].some((key) => typeof suggestion[key] !== "string" || suggestion[key].length > 5e4)) throw Error("WECHAT_STATE_INVALID");
|
|
594
|
+
}
|
|
595
|
+
if (prior.autoDraftedMessageId && state.autoDraftedMessageId === void 0) state = { ...state, autoDraftedMessageId: prior.autoDraftedMessageId };
|
|
373
596
|
if (state.progress) state = { ...state, progress: parseSavedProgress(state.progress) };
|
|
374
|
-
|
|
597
|
+
const encoded = JSON.stringify(state);
|
|
598
|
+
if (encoded === c.state) return false;
|
|
599
|
+
this.db.prepare("UPDATE chats SET state=? WHERE id=?").run(encoded, id);
|
|
600
|
+
return true;
|
|
375
601
|
}
|
|
376
602
|
markHandled(workspace, id) {
|
|
377
603
|
this.scope(workspace, id);
|
|
@@ -394,7 +620,7 @@ var WechatRepository = class _WechatRepository {
|
|
|
394
620
|
|
|
395
621
|
// src/wechat/repository-worker.ts
|
|
396
622
|
var repository = await WechatRepository.open(workerData.root);
|
|
397
|
-
var allowed = /* @__PURE__ */ new Set(["importBatch", "listContacts", "getContact", "listMessages", "getMedia", "bindCrm", "getState", "saveState", "markHandled", "getPairing"]);
|
|
623
|
+
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"]);
|
|
398
624
|
parentPort.on("message", ({ id, method, args }) => {
|
|
399
625
|
try {
|
|
400
626
|
if (!allowed.has(method)) throw Error("WECHAT_OPERATION_INVALID");
|