@wanji_dsh/dsh-sales 0.11.4 → 0.11.6

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.
@@ -28,6 +28,7 @@ interface Options {
28
28
  directory: string;
29
29
  knowledgeBaseId: string;
30
30
  toolPrefix: string;
31
+ requireExplicitScope?: boolean;
31
32
  environment?: 'test' | 'production';
32
33
  material?: {
33
34
  knowledgeBaseId: string;
@@ -2,11 +2,13 @@ import { type CustomerProgress } from './turn-packet.ts';
2
2
  export { buildReviewPrompt, applyDeliveryReview, reviewSentences } from './delivery-review.ts';
3
3
  import { type SalesKnowledgeContext } from './sales-context-types.ts';
4
4
  import type { Contact } from './model.ts';
5
- import type { GenerationOptions, GenerationStream, GenerationTimings } from './generation-progress.ts';
5
+ import { type GenerationOptions, type GenerationStream, type GenerationTimings } from './generation-progress.ts';
6
6
  import { type CustomerMaterials } from './customer-materials.ts';
7
7
  /** Uses the Harness connection carrier, including its existing authentication. */
8
8
  export interface RpcTransport {
9
9
  call(channel: string, endpoint: string, payload: unknown, signal?: AbortSignal): Promise<unknown>;
10
+ /** The desktop workbench uses direct model calls. Existing evaluation drivers can still exercise the session API. */
11
+ draftModel?: true;
10
12
  follow?(sessionId: string, signal: AbortSignal): GenerationStream;
11
13
  }
12
14
  export interface SalesReply {
@@ -172,5 +174,5 @@ export declare function buildPrompt(contact: Contact, latest: string, knowledge?
172
174
  quote: string;
173
175
  } | null;
174
176
  }): string;
175
- /** Each generation and delivery review own fresh Sessions; neither can inherit another merchant. */
177
+ /** Each draft and its reviews only receive history belonging to the current merchant. */
176
178
  export declare function generateReply(rpc: RpcTransport, workspaceId: string, contact: Contact, latest: string, signal: AbortSignal, options?: GenerationOptions): Promise<SalesReply>;
@@ -0,0 +1,13 @@
1
+ import type { ObservationEvent } from '../langfuse-outbox.ts';
2
+ export declare const COMPANY_OBSERVATION_TARGET: import("../langfuse-config.ts").Destination;
3
+ export interface CompanyObservationCredentials {
4
+ resolve(ref: string): Promise<{
5
+ value: string;
6
+ source: string;
7
+ } | undefined>;
8
+ }
9
+ /** Host-only transport. The device credential never enters events or the browser. */
10
+ export declare function createCompanyObservationRelay(store: () => CompanyObservationCredentials | undefined, request?: typeof fetch): {
11
+ deviceScope: () => Promise<string | undefined>;
12
+ submit: (event: ObservationEvent, signal: AbortSignal) => Promise<void>;
13
+ };
@@ -1,5 +1,5 @@
1
1
  export declare const intentSemanticPolicyVersion = 2;
2
- export declare const intentPolicyVersion = 3;
2
+ export declare const intentPolicyVersion = 4;
3
3
  export declare const intentProducts: readonly ["erp", "wanjitang"];
4
4
  export type IntentProduct = typeof intentProducts[number];
5
5
  export type IntentGrade = 'A' | 'B' | 'C' | 'D';
@@ -0,0 +1,5 @@
1
+ import { type GenerationModel } from './generation-runtime.ts';
2
+ import type { HostContext } from './knowledge-host.ts';
3
+ import { type LlmService } from './server/llm.ts';
4
+ /** Draft computation uses the owner connection and the same Flash route without creating a Harness agent. */
5
+ export declare function registerGenerationModelRoute(ctx: HostContext, llm: LlmService, selectModel: () => GenerationModel | undefined, hasWorkspace: (id: string) => boolean): void;
@@ -30,3 +30,8 @@ export interface GenerationOptions {
30
30
  export interface GenerationStream extends AsyncIterable<unknown> {
31
31
  dispose(): void;
32
32
  }
33
+ export declare const GENERATION_MODEL_ENDPOINT = "wanji-sales-generation/model";
34
+ export interface GenerationExchange {
35
+ prompt: string;
36
+ text: string;
37
+ }
@@ -1,10 +1,14 @@
1
1
  import type { GenerationServices } from './generation-sessions.ts';
2
2
  export declare const SALES_GENERATION_PRESET = "wanji-sales-generation";
3
- type GenerationModel = {
3
+ export type GenerationModel = {
4
4
  provider: string;
5
5
  model: string;
6
6
  reasoningEffort?: string;
7
7
  };
8
+ export declare function generationInstructions(): {
9
+ role: string;
10
+ system: string;
11
+ };
8
12
  /** Permanent product-owned composition; never borrows the coding preset or its AGENTS/tools. */
9
13
  export declare function createGenerationRuntime(sdk: {
10
14
  agents: any;
@@ -22,4 +26,3 @@ export declare function createGenerationRuntime(sdk: {
22
26
  }): GenerationServices & {
23
27
  close(): Promise<void>;
24
28
  };
25
- export {};
@@ -7,6 +7,7 @@ import { type KnowledgeConfig, type HostContext as KnowledgeHostContext } from '
7
7
  import { SalesQuestionObserver } from './question-tracing.ts';
8
8
  import { type SalesQuestionRelay } from './question-relay.ts';
9
9
  export interface Config extends Omit<ProfileConfig, 'requestTimeoutMs'>, KnowledgeConfig {
10
+ wechatAsrApiKeyRef: string;
10
11
  wechatComponentRoot?: string;
11
12
  wechatRuntimeBaseUrl?: string;
12
13
  /** CRM/download/transcription deadline; knowledge keeps the existing requestTimeoutMs. */
@@ -11,6 +11,7 @@ export interface ObservationEvent {
11
11
  question?: {
12
12
  sessionId: string;
13
13
  source: QuestionSource;
14
+ deviceScope?: string;
14
15
  };
15
16
  agent?: {
16
17
  sessionId: string;
@@ -1,3 +1,4 @@
1
+ import { type Destination } from './langfuse-config.ts';
1
2
  import { type ObservationEvent, type QuestionSource } from './langfuse-outbox.ts';
2
3
  type Status = 'answered' | 'no-reply' | 'error' | 'cancelled' | 'interrupted';
3
4
  export interface ObservedQuestion {
@@ -17,6 +18,7 @@ type Options = {
17
18
  directory: string;
18
19
  knowledgeBaseId: string;
19
20
  toolPrefix: string;
21
+ requireExplicitScope?: boolean;
20
22
  deliver?: (event: ObservationEvent) => Promise<void>;
21
23
  } & ({
22
24
  configFile: string;
@@ -25,7 +27,9 @@ type Options = {
25
27
  } | {
26
28
  relay: (event: ObservationEvent, signal: AbortSignal) => Promise<void>;
27
29
  configFile?: never;
28
- environment?: never;
30
+ environment?: 'test' | 'production';
31
+ relayTarget?: Destination;
32
+ deviceScope?: () => Promise<string | undefined>;
29
33
  });
30
34
  type SessionEvent = {
31
35
  type: string;
@@ -46,7 +50,8 @@ export declare class SalesQuestionTurns {
46
50
  private readonly salesSessions;
47
51
  private readonly tools;
48
52
  private readonly knowledgeBaseId;
49
- constructor(toolPrefix: string, knowledgeBaseId: string);
53
+ private readonly requireExplicitScope;
54
+ constructor(toolPrefix: string, knowledgeBaseId: string, requireExplicitScope?: boolean);
50
55
  observe(session: SessionRef, event: SessionEvent): {
51
56
  input: ObservedQuestion;
52
57
  outcome: QuestionOutcome;
@@ -61,6 +66,7 @@ export declare class SalesQuestionObserver {
61
66
  private readonly timer;
62
67
  private readonly turns;
63
68
  private readonly active;
69
+ private readonly owners;
64
70
  private target?;
65
71
  private sanitize?;
66
72
  private delivery?;
@@ -69,6 +75,7 @@ export declare class SalesQuestionObserver {
69
75
  constructor(options: Options);
70
76
  private configure;
71
77
  private event;
78
+ private captureScope;
72
79
  begin(input: ObservedQuestion): Promise<void>;
73
80
  finish(input: ObservedQuestion, outcome: QuestionOutcome): Promise<void>;
74
81
  observe(session: SessionRef, event: SessionEvent, alreadyEvaluated?: boolean): void;
@@ -1,16 +1,30 @@
1
- export interface LlmService {
2
- stream(options: {
1
+ export type ModelRoute = {
2
+ provider: string;
3
+ model: string;
4
+ reasoningEffort?: string;
5
+ maxTokens?: number;
6
+ };
7
+ type TextContent = {
8
+ type: 'text';
9
+ text: string;
10
+ }[];
11
+ type ModelMessage = {
12
+ role: 'user';
13
+ content: TextContent;
14
+ } | {
15
+ role: 'assistant';
16
+ id: string;
17
+ source: {
18
+ kind: 'model';
3
19
  provider: string;
4
20
  model: string;
5
- maxTokens: number;
21
+ };
22
+ content: TextContent;
23
+ };
24
+ export interface LlmService {
25
+ stream(options: ModelRoute & {
6
26
  system: string;
7
- messages: {
8
- role: 'user';
9
- content: {
10
- type: 'text';
11
- text: string;
12
- }[];
13
- }[];
27
+ messages: ModelMessage[];
14
28
  signal: AbortSignal;
15
29
  }): AsyncIterable<unknown>;
16
30
  }
@@ -23,3 +37,5 @@ export declare function runModel(llm: LlmService, route: {
23
37
  system: string;
24
38
  text: string;
25
39
  }, signal: AbortSignal): Promise<unknown>;
40
+ export declare function collectModelText(llm: LlmService, route: ModelRoute, system: string, messages: ModelMessage[], signal: AbortSignal, maxChars: number, onFailure: (reason: Record<string, unknown>) => never, onText?: (text: string) => void): Promise<string>;
41
+ export {};
@@ -67,6 +67,7 @@ export interface SalesBatch {
67
67
  protocol: 'wanji.media-patch.v1';
68
68
  phase: 'media';
69
69
  };
70
+ previous_run_id?: string | null;
70
71
  history_backfill?: boolean;
71
72
  sync?: SalesIncrementalEnvelope;
72
73
  }
@@ -1,4 +1,4 @@
1
- import type { CustomerIntent } from '../customer-intent.ts';
1
+ import { type CustomerIntent } from '../customer-intent.ts';
2
2
  import type { IntentInput, IntentJob } from '../server/intent-evaluation.ts';
3
3
  export type IntentEvaluator = (workspace: string, input: IntentInput, signal: AbortSignal) => Promise<CustomerIntent>;
4
4
  interface Queue {
@@ -13,9 +13,13 @@ export declare class IntentScheduler {
13
13
  private suspended;
14
14
  private closed;
15
15
  private cancellation?;
16
+ private lastModelReady?;
17
+ private readonly reportModelState;
18
+ private readonly assess;
16
19
  private readonly queue;
17
20
  private readonly evaluate;
18
- constructor(queue: Queue, evaluate: IntentEvaluator);
21
+ private readonly modelReady;
22
+ constructor(queue: Queue, evaluate: IntentEvaluator, modelReady?: () => boolean);
19
23
  wake(workspace: string): void;
20
24
  private schedule;
21
25
  private run;
@@ -27,6 +27,7 @@ export interface NativeBackend {
27
27
  requestId: string;
28
28
  syncAddress: string;
29
29
  fullSync: boolean;
30
+ sourceWatch?: "changed" | "watching";
30
31
  mediaPriority?: MediaPriorityHint;
31
32
  }, onEvent: (event: any) => void, signal: AbortSignal): Promise<NativeCompletion>;
32
33
  authorize(requestId: string, approved: boolean): void;
@@ -1,4 +1,4 @@
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';
1
+ type Method = 'importBatch' | 'listContacts' | 'contactsPage' | '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;
@@ -4,7 +4,7 @@ import { WechatSyncService, type WechatSyncOptions } from './service.ts';
4
4
  /** Shared Harness Fetch routes already restrict access to authenticated owner peers. */
5
5
  export declare function registerWechatRoutes(ctx: HostContext, options: WechatSyncOptions & {
6
6
  sendingEnabled?: boolean;
7
- transcribeVoice?: (audio: Uint8Array, signal: AbortSignal) => Promise<string | undefined>;
7
+ transcribeVoice?: (audio: Uint8Array, signal: AbortSignal, mode: 'draft' | 'manual') => Promise<string | undefined>;
8
8
  }, injected?: WechatSyncService, desktop?: {
9
9
  available(): boolean;
10
10
  sender: DshWechatSender;
@@ -8,6 +8,7 @@ import { type IntentEvaluator } from './intent-scheduler.ts';
8
8
  import type { ResumeIntent } from '../update/types.ts';
9
9
  export type WechatSyncOptions = {
10
10
  intentEvaluator?: IntentEvaluator;
11
+ intentModelReady?: () => boolean;
11
12
  storageDir: string;
12
13
  componentRoot: string;
13
14
  runtime?: WechatRuntime;
@@ -26,6 +27,7 @@ export declare class WechatSyncService {
26
27
  private lifetime;
27
28
  private task?;
28
29
  private starting;
30
+ private fileChanged;
29
31
  private dirty;
30
32
  private failures;
31
33
  private interval;
@@ -0,0 +1,20 @@
1
+ export declare const DEFAULT_WECHAT_ASR_KEY_REF = "DASHSCOPE_API_KEY";
2
+ type CredentialStore = {
3
+ resolve(ref: string): Promise<{
4
+ value: string;
5
+ } | undefined>;
6
+ };
7
+ type ProviderSettings = {
8
+ describe(options: {
9
+ redactSecrets: true;
10
+ }): {
11
+ ns: string;
12
+ value: unknown;
13
+ }[];
14
+ };
15
+ export declare function resolveWechatAsrKey(ref: string, store?: CredentialStore, settings?: ProviderSettings): Promise<string | undefined>;
16
+ export declare class WechatTranscriptionError extends Error {
17
+ constructor(code: 'WECHAT_TRANSCRIPTION_NOT_CONFIGURED' | 'WECHAT_TRANSCRIPTION_AUTH_FAILED' | 'WECHAT_TRANSCRIPTION_UNAVAILABLE' | 'WECHAT_TRANSCRIPTION_INVALID_AUDIO');
18
+ }
19
+ export declare function transcribeWechatWav(audio: Uint8Array, apiKey: string, signal: AbortSignal): Promise<string>;
20
+ export {};
@@ -3,6 +3,7 @@ import type { Contact } from '../model.ts';
3
3
  import type { SalesIncrementalEnvelope } from './batch.ts';
4
4
  export declare const WECHAT_METHOD = "wanji-sales-wechat/request";
5
5
  export interface ImportResult {
6
+ confirmed_run?: string;
6
7
  duplicate: boolean;
7
8
  chats: number;
8
9
  messages: number;
@@ -79,6 +80,7 @@ export interface SyncStatus {
79
80
  workspaceId?: string;
80
81
  message: string;
81
82
  revision: number;
83
+ stableContactPages?: true;
82
84
  progress?: SyncProgress;
83
85
  runtime?: RuntimeStatus;
84
86
  mediaImporting?: boolean;
@@ -12,6 +12,7 @@ export declare class SourceWatcher {
12
12
  private deadline?;
13
13
  private generation;
14
14
  private roots;
15
+ get active(): boolean;
15
16
  private notify;
16
17
  private options;
17
18
  constructor(notify: () => void, options?: WatchOptions);
@@ -5,7 +5,7 @@ import { parentPort, workerData } from "node:worker_threads";
5
5
  import { DatabaseSync } from "node:sqlite";
6
6
  import { mkdir, chmod } from "node:fs/promises";
7
7
  import { join } from "node:path";
8
- import { createHash, randomBytes } from "node:crypto";
8
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
9
9
 
10
10
  // src/wechat/batch.ts
11
11
  var SALES_BATCH_SCHEMA = "wanji.wechat.batch.v1";
@@ -56,6 +56,7 @@ function validateSalesBatch(value) {
56
56
  }
57
57
  if (!isRecord(value.stats)) throw new Error("stats must be an object");
58
58
  if (value.history_backfill !== void 0 && typeof value.history_backfill !== "boolean") throw Error("Invalid history_backfill flag");
59
+ if (value.previous_run_id !== void 0 && (value.source.kind !== "wechat_windows_local" || value.delivery !== void 0 || value.sync !== void 0 || isFocusedTextBatch(value) || value.previous_run_id !== null && (typeof value.previous_run_id !== "string" || !/^[a-zA-Z0-9:-]{1,128}$/.test(value.previous_run_id)))) throw Error("Invalid Windows batch baseline");
59
60
  const mediaPatch = value.delivery !== void 0;
60
61
  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())) {
61
62
  throw new Error("Invalid media patch envelope");
@@ -154,6 +155,7 @@ function validateSalesBatch(value) {
154
155
 
155
156
  // src/customer-intent.ts
156
157
  var intentSemanticPolicyVersion = 2;
158
+ var intentPolicyVersion = 4;
157
159
 
158
160
  // src/turn-packet.ts
159
161
  function bindProgress(raw, packet) {
@@ -225,8 +227,12 @@ function replyInputChanged(previous, incoming) {
225
227
  if (incoming.direction === "system" && (!previous || previous.direction === "system")) return false;
226
228
  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);
227
229
  }
230
+ var CONTACT_PAGE_TTL_MS = 12e4;
231
+ var MAX_CONTACT_PAGE_SESSIONS = 8;
228
232
  var WechatRepository = class _WechatRepository {
233
+ importStatements = /* @__PURE__ */ new Map();
229
234
  db;
235
+ contactPages = /* @__PURE__ */ new Map();
230
236
  closed = false;
231
237
  constructor(path) {
232
238
  this.db = new DatabaseSync(path);
@@ -271,6 +277,14 @@ var WechatRepository = class _WechatRepository {
271
277
  await chmod(path, 384);
272
278
  return repo;
273
279
  }
280
+ importStatement(sql) {
281
+ let statement = this.importStatements.get(sql);
282
+ if (!statement) {
283
+ statement = this.db.prepare(sql);
284
+ this.importStatements.set(sql, statement);
285
+ }
286
+ return statement;
287
+ }
274
288
  row(sql, ...args) {
275
289
  return this.db.prepare(sql).get(...args);
276
290
  }
@@ -317,6 +331,7 @@ var WechatRepository = class _WechatRepository {
317
331
  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;
318
332
  this.db.exec("BEGIN IMMEDIATE");
319
333
  try {
334
+ if (batch.previous_run_id && (active !== account || !this.row("SELECT 1 FROM runs WHERE workspace=? AND run_id=? AND json_extract(result,'$.confirmed_source')=?", workspace, batch.previous_run_id, source))) throw Error("WANJI_RESYNC_REQUIRED: prior Windows batch missing");
320
335
  const sync = batch.sync, checkpointScope = hash([source, sync?.scope]);
321
336
  if (sync) {
322
337
  const c = this.row("SELECT * FROM checkpoints WHERE scope=?", checkpointScope);
@@ -349,10 +364,10 @@ var WechatRepository = class _WechatRepository {
349
364
  const advanceIntent = trackIntent && !preview && (!(backfill || active !== account) || !!this.row("SELECT 1 FROM customer_intents WHERE chat_id=?", chatId));
350
365
  let intentRevision;
351
366
  for (const m of chat.messages) {
352
- const oldSource = this.row("SELECT * FROM sources WHERE scope=? AND chat_id=? AND message_key=?", source, chatId, m.message_key);
367
+ const oldSource = this.importStatement("SELECT * FROM sources WHERE scope=? AND chat_id=? AND message_key=?").get(source, chatId, m.message_key);
353
368
  if (batch.delivery) {
354
369
  if (!oldSource || oldSource.source_revision !== m.source_revision) throw Error("WANJI_RESYNC_REQUIRED: media revision mismatch");
355
- const old2 = this.row("SELECT * FROM messages WHERE id=?", oldSource.message_id);
370
+ const old2 = this.importStatement("SELECT * FROM messages WHERE id=?").get(oldSource.message_id);
356
371
  if (old2.kind !== m.kind || old2.direction !== m.direction || old2.source_revision !== m.source_revision) throw Error("WANJI_RESYNC_REQUIRED: media identity mismatch");
357
372
  const mediaId2 = hash([source, m.media_key]);
358
373
  if (old2.media_id !== mediaId2) {
@@ -360,7 +375,7 @@ var WechatRepository = class _WechatRepository {
360
375
  const current = this.row("SELECT json_extract(metadata,'$.width') * json_extract(metadata,'$.height') AS area FROM media WHERE id=?", old2.media_id);
361
376
  if ((imageAreas.get(m.media_key) ?? 0) < (current?.area ?? 0)) continue;
362
377
  }
363
- this.db.prepare("UPDATE messages SET media_id=? WHERE id=?").run(mediaId2, old2.id);
378
+ this.importStatement("UPDATE messages SET media_id=? WHERE id=?").run(mediaId2, old2.id);
364
379
  changed.add(chatId);
365
380
  if (old2.kind === "voice" && old2.direction === "inbound" && old2.auto_draft_arrival === 1) trackVoiceChange(chatId, old2.id);
366
381
  }
@@ -368,27 +383,27 @@ var WechatRepository = class _WechatRepository {
368
383
  }
369
384
  const server = typeof m.server_id === "string" && /^\d+$/.test(m.server_id) && !/^0+$/.test(m.server_id) ? m.server_id : void 0;
370
385
  const id = server ? hash([chatId, "server", server]) : hash([chatId, "local", source, m.message_key]);
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;
386
+ const old = this.importStatement("SELECT * FROM messages WHERE id=?").get(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;
372
387
  if (preview && old) continue;
373
388
  const newlyConfirmed = !preview && (!old || old.preview_only === 1);
374
389
  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
390
  if (!preview && replyInputChanged(newlyConfirmed ? void 0 : old, m)) replyChanges.add(chatId);
376
391
  if (m.kind === "voice" && m.direction === "inbound" && old?.auto_draft_arrival === 1 && old.media_id !== mediaId) trackVoiceChange(chatId, id);
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);
392
+ this.importStatement("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);
378
393
  changed.add(chatId);
379
394
  if (!old) messages++;
380
395
  }
381
396
  if (preview) continue;
382
397
  if (newlyConfirmed && !backfill && active === account && m.direction === "inbound" && (replyText(m) || attachmentReply(m.kind))) {
383
- this.db.prepare("UPDATE messages SET auto_draft_arrival=1 WHERE id=?").run(id);
398
+ this.importStatement("UPDATE messages SET auto_draft_arrival=1 WHERE id=?").run(id);
384
399
  }
385
400
  const meaningful = (row) => row.direction !== "system" && ["text", "quote", "link"].includes(row.kind) && typeof row.text === "string" && !!row.text.trim();
386
401
  const intentChanged = !old || newlyConfirmed ? meaningful(m) : (meaningful(m) || meaningful(old)) && (old.text !== m.text || old.direction !== m.direction || old.kind !== m.kind);
387
402
  if (advanceIntent && intentChanged) {
388
403
  intentRevision ??= this.queueIntentRow(chatId, Date.now() + 3500, true);
389
- this.db.prepare("UPDATE messages SET intent_revision=? WHERE id=?").run(intentRevision, id);
404
+ this.importStatement("UPDATE messages SET intent_revision=? WHERE id=?").run(intentRevision, id);
390
405
  }
391
- 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));
406
+ this.importStatement("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));
392
407
  }
393
408
  }
394
409
  for (const id of changed) {
@@ -408,7 +423,7 @@ var WechatRepository = class _WechatRepository {
408
423
  }
409
424
  if (!batch.delivery) this.db.prepare("INSERT INTO active VALUES(?,?) ON CONFLICT(workspace) DO UPDATE SET account=excluded.account").run(workspace, account);
410
425
  if (sync) this.db.prepare("INSERT INTO checkpoints VALUES(?,?,?,?,?) ON CONFLICT(scope) DO UPDATE SET revision=excluded.revision,active_revision=excluded.active_revision,next_part=excluded.next_part,part_count=excluded.part_count").run(checkpointScope, receipt.committed ? sync.revision : this.row("SELECT revision FROM checkpoints WHERE scope=?", checkpointScope)?.revision ?? null, receipt.committed ? null : sync.revision, receipt.committed ? 0 : sync.part_index + 1, sync.part_count);
411
- const result = { duplicate: false, chats: batch.chats.length, messages, mediaUpdated: batch.media.length, avatarsUpdated, changedChatIds: [...changed], accountChanged: !!active && active !== account, warnings: batch.warnings, ...receipt ? { sync_receipt: receipt } : {} };
426
+ const result = { duplicate: false, chats: batch.chats.length, messages, mediaUpdated: batch.media.length, avatarsUpdated, changedChatIds: [...changed], accountChanged: !!active && active !== account, warnings: batch.warnings, ...batch.previous_run_id !== void 0 ? { confirmed_run: batch.run_id, confirmed_source: source } : {}, ...receipt ? { sync_receipt: receipt } : {} };
412
427
  this.db.prepare("INSERT INTO runs VALUES(?,?,?,?)").run(workspace, batch.run_id, digest, JSON.stringify(result));
413
428
  this.db.exec("COMMIT");
414
429
  return result;
@@ -429,14 +444,14 @@ var WechatRepository = class _WechatRepository {
429
444
  }
430
445
  requeueLegacyIntents(workspace, contactId) {
431
446
  this.db.prepare(`UPDATE customer_intents SET revision=revision+1,due=?
432
- WHERE assessed=revision AND (
433
- (json_extract(result,'$.status')='ready' AND COALESCE(json_extract(result,'$.policyVersion'),1)<?)
434
- OR (json_extract(result,'$.status')='failed' AND json_extract(result,'$.policyVersion')=?)
435
- )
436
- AND json_extract(result,'$.products')='{}' AND json_type(result,'$.crm') IS NULL
437
- AND EXISTS(SELECT 1 FROM chats c JOIN active a ON a.workspace=c.workspace AND a.account=c.account
438
- WHERE c.id=customer_intents.chat_id AND c.workspace=? AND c.crm IS NULL)
439
- ${contactId === void 0 ? "" : "AND chat_id=?"}`).run(Date.now(), intentSemanticPolicyVersion, intentSemanticPolicyVersion, workspace, ...contactId === void 0 ? [] : [contactId]);
447
+ WHERE assessed=revision AND EXISTS(SELECT 1 FROM chats c JOIN active a ON a.workspace=c.workspace AND a.account=c.account
448
+ WHERE c.id=customer_intents.chat_id AND c.workspace=? AND (
449
+ (json_extract(result,'$.status')='failed' AND COALESCE(json_extract(result,'$.policyVersion'),1)<?)
450
+ OR (c.crm IS NULL AND json_extract(result,'$.status')='ready'
451
+ AND COALESCE(json_extract(result,'$.policyVersion'),1)<?
452
+ AND json_extract(result,'$.products')='{}' AND json_type(result,'$.crm') IS NULL)
453
+ ))
454
+ ${contactId === void 0 ? "" : "AND chat_id=?"}`).run(Date.now(), workspace, intentPolicyVersion, intentSemanticPolicyVersion, ...contactId === void 0 ? [] : [contactId]);
440
455
  }
441
456
  seedIntents(workspace) {
442
457
  const active = this.row("SELECT account FROM active WHERE workspace=?", workspace);
@@ -511,6 +526,26 @@ var WechatRepository = class _WechatRepository {
511
526
  listContacts(workspace, limit = 200, offset = 0) {
512
527
  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));
513
528
  }
529
+ /** Freeze membership and order for paging. Rows are projected with their current state. */
530
+ contactsPage(workspace, snapshotId, limit, offset, revision) {
531
+ const account = this.row("SELECT account FROM active WHERE workspace=?", workspace)?.account;
532
+ const now = Date.now();
533
+ let page = this.contactPages.get(snapshotId);
534
+ if (!snapshotId) {
535
+ snapshotId = randomUUID();
536
+ const ids = this.rows(`SELECT id FROM chats c WHERE workspace=? AND account=?
537
+ ORDER BY (SELECT MAX(sent_at) FROM messages WHERE chat_id=c.id) DESC,c.id`, workspace, account ?? null).map((row) => String(row.id));
538
+ page = { workspace, account, ids, revision, expiresAt: now + CONTACT_PAGE_TTL_MS };
539
+ }
540
+ if (!page || page.workspace !== workspace || page.account !== account || page.expiresAt <= now)
541
+ throw Error("WECHAT_CONTACT_SNAPSHOT_EXPIRED");
542
+ page.expiresAt = now + CONTACT_PAGE_TTL_MS;
543
+ this.contactPages.delete(snapshotId);
544
+ this.contactPages.set(snapshotId, page);
545
+ if (this.contactPages.size > MAX_CONTACT_PAGE_SESSIONS) this.contactPages.delete(this.contactPages.keys().next().value);
546
+ const contacts = page.ids.slice(offset, offset + limit).map((id) => this.project(this.scope(workspace, id), 2));
547
+ return { contacts, revision: page.revision, snapshotId };
548
+ }
514
549
  getContact(workspace, id) {
515
550
  return this.project(this.scope(workspace, id), 100);
516
551
  }
@@ -669,6 +704,7 @@ var WechatRepository = class _WechatRepository {
669
704
  }
670
705
  close() {
671
706
  if (!this.closed) {
707
+ this.importStatements.clear();
672
708
  this.db.close();
673
709
  this.closed = true;
674
710
  }
@@ -677,7 +713,7 @@ var WechatRepository = class _WechatRepository {
677
713
 
678
714
  // src/wechat/repository-worker.ts
679
715
  var repository = await WechatRepository.open(workerData.root);
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"]);
716
+ var allowed = /* @__PURE__ */ new Set(["importBatch", "listContacts", "contactsPage", "getContact", "listMessages", "getMedia", "getMediaPriority", "getDraftVoice", "getVoiceForTranscription", "bindCrm", "getState", "saveState", "markHandled", "getPairing", "getDeliverySource", "claimDelivery", "settleDelivery", "deliveryStatus", "queueIntent", "seedIntents", "nextIntent", "getIntentInput", "finishIntent"]);
681
717
  parentPort.on("message", ({ id, method, args }) => {
682
718
  try {
683
719
  if (!allowed.has(method)) throw Error("WECHAT_OPERATION_INVALID");
@@ -35,6 +35,7 @@ if ($files.Count -gt 0) {
35
35
  | `wechat.runtime`、`wechat.sync` | 组件下载、解压、校验、自检、登录等待和同步结果 |
36
36
  | `dingtalk.http.start`、`dingtalk.oauth-challenge`、`dingtalk.status.*`、`dingtalk.model-route` | 请求登录、生成授权入口、等待确认、绑定结果和模型配置。钉钉浏览器端授权回调发生在服务端,需要按时间对照服务端记录。 |
37
37
  | `mcp.knowledge`、`mcp.materials`、`knowledge`、`weknora.http` | 工具缺失、调用超时、HTTP 错误、响应解析、知识库范围和素材文件检查。分别核对 MCP 调用和直连 WeKnora。 |
38
+ | `wechat.rpc.contacts`、`intent.model-readiness`、`intent.inference`、`intent.evaluate` | 核对联系人分页冲突、评分模型是否就绪、推理失败原因和评估结果。同步可以继续。 |
38
39
  | `crm.http`、`tool.crm_` | CRM 请求和工具执行,含网络、HTTP 状态和耗时 |
39
40
  | `langfuse` | 配置、凭据、项目检查、上传响应、托管转发、队列待重试或已确认。测试配置可查托管转发。生产直连可通过 Host 环境变量注入 API 和脱敏密钥,Windows 使用同一方式。 |
40
41
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wanji_dsh/dsh-sales",
3
- "version": "0.11.4",
3
+ "version": "0.11.6",
4
4
  "type": "module",
5
5
  "description": "Sales workspace with local Windows/macOS WeChat sync, one-time CRM context, Flash drafts and filtered knowledge.",
6
6
  "engines": {
@@ -1,27 +1,27 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "0.11.4",
3
+ "version": "0.11.6",
4
4
  "targets": {
5
5
  "win32-x64": {
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"
6
+ "url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.3-win32-x64-040c24ad35c875db.tgz",
7
+ "sha256": "040c24ad35c875db1b6d8e423935cede0a8e3150269bcfc01bf926b2e0fce55e",
8
+ "bytes": 22917486,
9
+ "unpackedBytes": 47611545,
10
+ "componentSha256": "b72916b0b8ee6e55e540a0ecb2cb9310248c29778289a2f06302fe40ca4e9ae9"
11
11
  },
12
12
  "darwin-arm64": {
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"
13
+ "url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.5-darwin-arm64-3942e780ff1d3877.tgz",
14
+ "sha256": "3942e780ff1d38770291ae64029c860ec52bf7326fe2123f32a2c0e06083c09c",
15
+ "bytes": 25125580,
16
+ "unpackedBytes": 64495137,
17
+ "componentSha256": "a2817efdcefd4ea78c3bc657a03bdf39b41a3468df1ba03f959f95d3adf6c025"
18
18
  },
19
19
  "darwin-x64": {
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"
20
+ "url": "https://wanjidazi.com/plugins/sales-assistant/runtimes/wanji-wechat-runtime-1.0.4-darwin-x64-3aa17267c37531a9.tgz",
21
+ "sha256": "3aa17267c37531a9b7a0acbcb6537f9ccb7e0430a879d16396c3a3dc604a09e7",
22
+ "bytes": 27838054,
23
+ "unpackedBytes": 66653818,
24
+ "componentSha256": "1d441c8f7fe2b923b96051ea74b10d60c7229ced66b6225eee52a9849afdc0b4"
25
25
  }
26
26
  }
27
27
  }