@wanji_dsh/dsh-sales 0.10.4 → 0.10.5

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/dist/host.js CHANGED
@@ -16312,6 +16312,13 @@ async function probeUpdateCapability(raw) {
16312
16312
  return { status: "unsupported", reason: "manager-unavailable" };
16313
16313
  }
16314
16314
  }
16315
+ var companyArtifact = /(?:^|@)file:(?:[A-Za-z]:)?[\\/].*[\\/]company-plugin-artifacts[\\/][0-9a-f-]{36}-[^\\/]+[\\/]plugin\.tgz$/u;
16316
+ async function companyInstalledVersion(raw) {
16317
+ const manager = raw;
16318
+ if (typeof manager?.listBundles !== "function") throw Error("UPDATE_MANAGER_UNAVAILABLE");
16319
+ const bundle = (await manager.listBundles()).find((row) => row.name === PACKAGE_NAME && row.installed && !row.official && companyArtifact.test(row.source ?? ""));
16320
+ return bundle?.version;
16321
+ }
16315
16322
  var stable = (v2) => /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(v2) ? v2.split(".").map(BigInt) : void 0;
16316
16323
  function selectCandidate(list3, running) {
16317
16324
  if (list3.status !== "listed") return;
@@ -16357,7 +16364,7 @@ var UpdateCoordinator = class {
16357
16364
  failures = 0;
16358
16365
  constructor(options) {
16359
16366
  this.options = options;
16360
- this.view = { phase: "idle", runningVersion: options.version, automatic: DEFAULT_AUTOMATIC };
16367
+ this.view = { phase: "idle", runningVersion: options.version, automatic: options.companyMarket ? false : DEFAULT_AUTOMATIC, ...options.companyMarket ? { source: "company-market" } : {} };
16361
16368
  }
16362
16369
  snapshot() {
16363
16370
  return structuredClone(this.view);
@@ -16366,6 +16373,13 @@ var UpdateCoordinator = class {
16366
16373
  return this.initialized ??= this.initializeOnce();
16367
16374
  }
16368
16375
  async initializeOnce() {
16376
+ if (this.options.companyMarket) {
16377
+ try {
16378
+ this.record = await this.options.state.read();
16379
+ } catch {
16380
+ }
16381
+ return;
16382
+ }
16369
16383
  try {
16370
16384
  this.record = await this.options.state.read();
16371
16385
  this.view.automatic = this.record.automatic;
@@ -16426,12 +16440,16 @@ var UpdateCoordinator = class {
16426
16440
  await this.options.state.write(this.record);
16427
16441
  this.view.phase = "updated";
16428
16442
  } else this.view.phase = this.record.phase === "failed" ? "failed" : "idle";
16429
- if (this.record.resume) {
16430
- try {
16431
- await this.options.sync.resumeAfterUpdate(this.record.resume);
16432
- delete this.record.resume;
16433
- await this.options.state.write(this.record);
16434
- } catch (error) {
16443
+ await this.resumeSync();
16444
+ }
16445
+ async resumeSync() {
16446
+ if (!this.record.resume) return;
16447
+ try {
16448
+ await this.options.sync.resumeAfterUpdate(this.record.resume);
16449
+ delete this.record.resume;
16450
+ await this.options.state.write(this.record);
16451
+ } catch (error) {
16452
+ if (!this.options.companyMarket) {
16435
16453
  this.view.phase = "failed";
16436
16454
  this.view.error = code(error);
16437
16455
  }
@@ -16441,7 +16459,7 @@ var UpdateCoordinator = class {
16441
16459
  void this.initialize().then(() => this.schedule(Math.max(0, this.nextCheck - Date.now())));
16442
16460
  }
16443
16461
  schedule(delay2 = this.view.phase === "installing" ? 1e3 : TICK_INTERVAL_MS) {
16444
- if (this.disposed) return;
16462
+ if (this.disposed || this.options.companyMarket && !this.record.resume) return;
16445
16463
  this.timer = setTimeout(() => {
16446
16464
  void this.tick().catch((e) => {
16447
16465
  this.view.error = code(e);
@@ -16453,6 +16471,18 @@ var UpdateCoordinator = class {
16453
16471
  if (this.disposed || this.invalid || this.job) return;
16454
16472
  const shared = await this.options.state.read();
16455
16473
  if (this.disposed || this.job) return;
16474
+ if (this.options.companyMarket) {
16475
+ this.record = shared;
16476
+ if (!shared.resume) return;
16477
+ const release = await this.options.state.acquire();
16478
+ if (release) try {
16479
+ this.record = await this.options.state.read();
16480
+ await this.resumeSync();
16481
+ } finally {
16482
+ await release();
16483
+ }
16484
+ return;
16485
+ }
16456
16486
  if (shared.requestId !== this.record.requestId || shared.phase !== this.record.phase) {
16457
16487
  await this.reconcile();
16458
16488
  return;
@@ -16476,6 +16506,18 @@ var UpdateCoordinator = class {
16476
16506
  return this.checking ??= (async () => {
16477
16507
  await this.initialize();
16478
16508
  if (this.disposed || this.invalid || this.job) return;
16509
+ if (this.options.companyMarket) {
16510
+ this.view.error = void 0;
16511
+ try {
16512
+ const version = await companyInstalledVersion(this.options.manager());
16513
+ this.view.installedVersion = version;
16514
+ this.view.phase = !version ? "migration-required" : version === this.options.version ? "idle" : "restart-required";
16515
+ } catch {
16516
+ this.view.installedVersion = void 0;
16517
+ this.view.phase = "failed";
16518
+ }
16519
+ return;
16520
+ }
16479
16521
  if (await this.options.state.held()) {
16480
16522
  this.view.phase = "installing";
16481
16523
  return;
@@ -16521,6 +16563,7 @@ var UpdateCoordinator = class {
16521
16563
  });
16522
16564
  }
16523
16565
  async setAutomatic(enabled) {
16566
+ if (this.options.companyMarket) throw Error("UPDATE_MANAGED_BY_COMPANY");
16524
16567
  await this.initialize();
16525
16568
  if (this.invalid || this.job || this.disposed) throw Error("UPDATE_BUSY");
16526
16569
  const release = await this.options.state.acquire();
@@ -16535,6 +16578,7 @@ var UpdateCoordinator = class {
16535
16578
  }
16536
16579
  }
16537
16580
  async requestInstall(manual = true) {
16581
+ if (this.options.companyMarket) throw Error("UPDATE_MANAGED_BY_COMPANY");
16538
16582
  await this.initialize();
16539
16583
  if (this.disposed || this.invalid || this.job) return;
16540
16584
  if (this.checking) await this.checking;
@@ -16798,7 +16842,7 @@ function registerUpdateRoutes(ctx, coordinator, clients) {
16798
16842
  }
16799
16843
 
16800
16844
  // src/update/version.ts
16801
- var RUNNING_VERSION = true ? "0.10.4" : "0.0.0-dev";
16845
+ var RUNNING_VERSION = true ? "0.10.5" : "0.0.0-dev";
16802
16846
 
16803
16847
  // src/update/integration.ts
16804
16848
  function mountUpdates(ctx, storageDir, activity, sync) {
@@ -16823,6 +16867,7 @@ function mountUpdates(ctx, storageDir, activity, sync) {
16823
16867
  clients,
16824
16868
  activity,
16825
16869
  sync,
16870
+ companyMarket: Boolean(process.env.WANJI_COMPANY_PLUGIN_CLIENT_VERSION),
16826
16871
  async health() {
16827
16872
  const workspace = ctx.workspaceRegistry?.list()[0]?.id ?? "update-health";
16828
16873
  await sync.data("listContacts", workspace, 1, 0);
@@ -16861,22 +16906,35 @@ function mentionedProductEditions(text6) {
16861
16906
  return [...new Set([...matches].filter((match) => !/(?:不是|不用|不要|别用|别给|排除)\s*$/.test(normalized.slice(0, match.index))).map((match) => match[0].replace(/\s/g, "")))];
16862
16907
  }
16863
16908
  function requestedMaterialText(query) {
16864
- return query.normalize("NFKC").replace(/(?:别|不用|不需要|不要|无需)(?:再|给我|发|提供|用)*[^,,。;;!?!?]*?(?=只要|只发|改要|[,,。;;!?!?]|$)/g, "");
16909
+ return query.normalize("NFKC").replace(/(^|[,,。;;!?!?\n])[^,,。;;!?!?\n]*?(?:图片|截图|视频|手册|文档|教程|PDF|长图)(?:我|我们)?(?:已(?:经)?(?:有|收到|看过)|手上有)(?:了)?\s*(?=[,,。;;!?!?\n]|$)/gi, "$1").replace(/(^|[,,。;;!?!?\n])[^,,。;;!?!?\n]*?(?:都|也)?(?:不要|不需要|不用)(?:发给我|发我|发|给我|提供)?(?:了)?\s*(?=[,,。;;!?!?\n]|$)/g, "$1").replace(/(?:别|不用|不需要|不要|不接受|无需)(?:再|给我|发|提供|用)*[^,,。;;!?!?\n]*?(?=只要|只发|改要|[,,。;;!?!?\n]|$)/g, "");
16865
16910
  }
16866
16911
  function materialConstraints(query) {
16867
16912
  const positive3 = requestedMaterialText(query);
16868
- const wanted = formats.filter(([, , pattern2]) => pattern2.test(positive3));
16913
+ const delivery = positive3.replace(/(?:我|我们)?(?:已经有|已有|手上有)[^,,。;;!?!?\n]+[,,。;;](?=[^。!?\n]*(?:找|给|发|需要|想看))/, "");
16914
+ const featureOverview = /功能卡(?!住|顿|死)|(?:功能|产品)(?:介绍|概览|总览|对照|一览)(?:长图|海报|卡|图)|(?:功能|介绍|概览)长图/.test(delivery);
16915
+ const interfaceImage = /界面图|界面截图|截图|截屏/.test(delivery);
16916
+ const contractFile = /合同(?:书|原件|样本|模板|范本|文件|文档|扫描件|电子版|下载链接|一份|给我|发我|吗|PDF|Word|[\s??。!!])*$/i.test(delivery.trim());
16917
+ let publicationPurpose;
16918
+ if (contractFile) publicationPurpose = "contract_document";
16919
+ else if (featureOverview) publicationPurpose = "product_introduction";
16920
+ else if (/(?:活动|促销|优惠)[^,。!?\n]{0,16}海报/.test(delivery)) publicationPurpose = "campaign_poster";
16921
+ else if (/(?:政策|条款)[^,。!?\n]{0,16}(?:原文|原件|盖章)/.test(delivery)) publicationPurpose = "policy_document";
16922
+ else if (/(?:年费|会员|官方|现行|版本)[^,。!?\n]{0,16}(?:价格表|价表)/.test(delivery)) publicationPurpose = "price_list";
16923
+ const wanted = formats.filter(([, , pattern2]) => pattern2.test(delivery));
16869
16924
  const kinds = new Set(wanted.flatMap(([, kind]) => kind ? [kind] : []));
16870
- if (/图片|截图|截屏|照片|流程图|操作图|示意图|界面图/.test(positive3)) kinds.add("image");
16871
- if (/视频|录像|录屏|片段/.test(positive3)) kinds.add("video");
16872
- if (kinds.size === 0 && /文档|文件|手册|指南/.test(positive3)) kinds.add("document");
16873
- const mentioned = mentionedProductEditions(positive3);
16925
+ if (/图片|截图|截屏|照片|流程图|操作图|示意图|界面图/.test(delivery) || featureOverview) kinds.add("image");
16926
+ if (/视频|录像|录屏|片段/.test(delivery)) kinds.add("video");
16927
+ if (kinds.size === 0 && /文档|文件|手册|指南|(?:纸面|文字)(?:的)?(?:操作)?步骤/.test(delivery)) kinds.add("document");
16928
+ const mentioned = mentionedProductEditions(delivery);
16874
16929
  const editions = materialEditions.filter((edition) => mentioned.includes(edition));
16875
16930
  const comparison = mentioned.length > 1 && /比较|对比|对照|分版本|各版本|两版|区别/.test(positive3);
16876
16931
  return {
16877
16932
  edition: comparison ? void 0 : editions[0],
16878
16933
  kind: [...kinds][0],
16879
16934
  format: wanted[0]?.[0],
16935
+ ...publicationPurpose ? { publicationPurpose } : {},
16936
+ ...interfaceImage ? { interfaceImage: true } : {},
16937
+ .../(?:最新|现行|当前有效|正在执行)(?:版|的)?[^,。!?\n]{0,10}(?:功能|权益|介绍|海报|长图|清单|版本)/.test(delivery) ? { currentVersion: true } : {},
16880
16938
  ambiguous: !comparison && mentioned.length > 1 || kinds.size > 1 || wanted.length > 1,
16881
16939
  ...comparison ? { comparison: true, comparedEditions: materialEditions.filter((edition) => editions.includes(edition) || mentioned.includes("\u4F01\u4E1A\u7248") && ["\u6807\u51C6\u7248", "\u4E13\u4E1A\u7248"].includes(edition)) } : {},
16882
16940
  ...mentioned.includes("\u4F01\u4E1A\u7248") && !editions.length ? { enterpriseEditionUnknown: true } : {}
@@ -17500,6 +17558,12 @@ import { createHash as createHash3, randomBytes, timingSafeEqual } from "node:cr
17500
17558
  import { lstat as lstat2, readFile as readFile4, readdir as readdir2, realpath as realpath2 } from "node:fs/promises";
17501
17559
  import { homedir as homedir2, userInfo } from "node:os";
17502
17560
  import path from "node:path";
17561
+ var pendingLoginMessages = /* @__PURE__ */ new Set([
17562
+ "\u5F53\u524D\u672A\u786E\u8BA4\u6709\u5FAE\u4FE1\u8D26\u53F7\u767B\u5F55\uFF0C\u8BF7\u5148\u5728 Mac \u5FAE\u4FE1\u4E2D\u5B8C\u6210\u767B\u5F55\uFF0C\u518D\u70B9\u51FB\u201C\u626B\u63CF\u5E76\u540C\u6B65\u201D\u3002",
17563
+ "\u5F53\u524D\u6CA1\u6709\u5FAE\u4FE1\u8D26\u53F7\u767B\u5F55\uFF0C\u8BF7\u5148\u767B\u5F55 Mac \u5FAE\u4FE1\uFF0C\u518D\u70B9\u51FB\u201C\u626B\u63CF\u5E76\u540C\u6B65\u201D\u3002"
17564
+ ]);
17565
+ var WechatLoginPendingError = class extends Error {
17566
+ };
17503
17567
  var names = { worker: process.platform === "win32" ? "DSHWechatWorker.exe" : "DSHWechatWorker", launcher: "DSHWechatLauncher.exe" };
17504
17568
  async function verifyComponent(root, platform = process.platform, arch = process.arch) {
17505
17569
  if (!path.isAbsolute(root) || await realpath2(root) !== root)
@@ -17603,7 +17667,8 @@ function createNativeBackend({ componentRoot }) {
17603
17667
  a.resolve(e);
17604
17668
  } else if (e.type === "failed") {
17605
17669
  if (process.platform === "darwin" || e.code === "user_mismatch" || e.code === "busy") void stop();
17606
- fail2(Error(typeof e.message === "string" ? e.message : "Native synchronization failed"));
17670
+ const pending = process.platform === "darwin" && e.code === "sync_failed" && pendingLoginMessages.has(e.message);
17671
+ fail2(pending ? new WechatLoginPendingError(e.message) : Error(typeof e.message === "string" ? e.message : "Native synchronization failed"));
17607
17672
  } else {
17608
17673
  if (e.type === "initialization_required")
17609
17674
  a.consent = "initialize";
@@ -17936,6 +18001,7 @@ var IntentScheduler = class {
17936
18001
  };
17937
18002
 
17938
18003
  // src/wechat/service.ts
18004
+ var loginRetryDelays = [5e3, 15e3, 3e4, 6e4];
17939
18005
  var isMediaBatch = (raw) => !!raw && typeof raw === "object" && raw.delivery?.protocol === "wanji.media-patch.v1";
17940
18006
  var WechatSyncService = class {
17941
18007
  options;
@@ -18115,23 +18181,25 @@ var WechatSyncService = class {
18115
18181
  this.dirty = true;
18116
18182
  if (!this.state.running && this.failures === 0) this.schedule(0);
18117
18183
  }
18118
- schedule(delay2) {
18184
+ schedule(delay2, next = () => this.cycle(false)) {
18119
18185
  clearTimeout(this.timer);
18120
18186
  if (this.closed || this.updatePreparing || !this.state.automatic || this.state.running) return;
18121
18187
  this.timer = setTimeout(() => {
18188
+ if (this.starting) return;
18122
18189
  this.state.running = true;
18123
- this.task = this.cycle(false);
18190
+ this.task = next();
18124
18191
  }, delay2);
18125
18192
  this.timer.unref();
18126
18193
  }
18127
- async cycle(fullSync, initial = false) {
18128
- if (!initial && !fullSync && !this.native.isConnected()) {
18194
+ async cycle(fullSync, allowStart = false, loginAttempt = 0) {
18195
+ if (!allowStart && !this.native.isConnected()) {
18129
18196
  this.state.running = false;
18130
18197
  this.state.automatic = false;
18131
18198
  this.state.phase = "paused";
18132
18199
  this.state.message = "WECHAT_RECONNECT_REQUIRED";
18133
18200
  return;
18134
18201
  }
18202
+ let retryLoginIn;
18135
18203
  this.initialImport = fullSync;
18136
18204
  const workspace = this.state.workspaceId, requestId = randomUUID9();
18137
18205
  this.dirty = false;
@@ -18141,9 +18209,16 @@ var WechatSyncService = class {
18141
18209
  try {
18142
18210
  const result = await this.native.run({ requestId, syncAddress: this.receiver.address, fullSync }, (event) => {
18143
18211
  if (this.closed || !this.state.running || this.state.requestId !== requestId || event.requestId && event.requestId !== requestId) return;
18144
- if (["initialization_required", "restart_initialization_required"].includes(event.type)) {
18212
+ if (event.type === "initialization_required" || event.type === "restart_initialization_required") {
18213
+ const kind = event.type === "initialization_required" ? "initialize" : "restart";
18214
+ const capabilities = this.state.capabilities;
18215
+ let message = kind === "initialize" ? "\u9996\u6B21\u8BFB\u53D6\u9700\u8981\u6388\u6743\u521D\u59CB\u5316\uFF1B\u5F53\u524D\u5B9E\u73B0\u8981\u6C42 SIP \u5DF2\u5173\u95ED\u3002" : "\u9700\u8981\u5355\u72EC\u786E\u8BA4\u6B63\u5E38\u91CD\u542F\u5FAE\u4FE1\u4E00\u6B21\uFF1B\u8BF7\u5728120\u79D2\u5185\u767B\u5F55\u540C\u4E00\u8D26\u53F7\u3002";
18216
+ if (kind === "restart" && capabilities?.platform === "macos" && capabilities.arch === "x64") {
18217
+ message += "\u5F53\u524D\u4F7F\u7528 Intel \u7248\u7EC4\u4EF6\uFF0C\u9996\u6B21\u521D\u59CB\u5316\u4ECD\u5F85\u771F\u673A\u9A8C\u6536\u3002";
18218
+ }
18145
18219
  this.state.phase = "authorizing";
18146
- this.state.consent = { requestId, kind: event.type === "initialization_required" ? "initialize" : "restart", message: event.type === "initialization_required" ? "\u9996\u6B21\u8BFB\u53D6\u9700\u8981\u6388\u6743\u521D\u59CB\u5316\uFF1B\u5F53\u524D\u5B9E\u73B0\u8981\u6C42 SIP \u5DF2\u5173\u95ED\u3002" : "\u9700\u8981\u5355\u72EC\u786E\u8BA4\u6B63\u5E38\u91CD\u542F\u5FAE\u4FE1\u4E00\u6B21\uFF1B\u8BF7\u5728120\u79D2\u5185\u767B\u5F55\u540C\u4E00\u8D26\u53F7\u3002Intel \u9996\u6B21\u521D\u59CB\u5316\u4ECD\u5F85\u771F\u673A\u9A8C\u6536\u3002" };
18220
+ this.state.message = "";
18221
+ this.state.consent = { requestId, kind, message };
18147
18222
  } else if (event.type === "progress" && !this.state.consent) {
18148
18223
  this.state.phase = "collecting";
18149
18224
  this.state.message = typeof event.message === "string" ? event.message.slice(0, 500) : "";
@@ -18164,20 +18239,27 @@ var WechatSyncService = class {
18164
18239
  this.state.lastSyncedAt = (/* @__PURE__ */ new Date()).toISOString();
18165
18240
  this.state.stats = { chat_count: Number(result.stats.chat_count) || 0, message_count: Number(result.stats.message_count) || 0, media_count: Number(result.stats.media_count) || 0 };
18166
18241
  } catch (e) {
18167
- if (!this.closed) {
18168
- this.failures++;
18242
+ if (this.closed) return;
18243
+ this.failures++;
18244
+ const loginPending = e instanceof WechatLoginPendingError && this.state.phase === "collecting" && (this.state.progress?.percent ?? 0) <= 1;
18245
+ if (loginPending && this.state.automatic) retryLoginIn = loginRetryDelays[loginAttempt];
18246
+ if (retryLoginIn !== void 0) {
18247
+ this.state.phase = "awaiting-login";
18248
+ this.state.message = "";
18249
+ this.state.progress = void 0;
18250
+ } else {
18169
18251
  this.state.phase = "error";
18170
- this.state.message = e instanceof Error ? e.message === "WECHAT_COMMIT_UNCONFIRMED" ? "\u6D88\u606F\u5C1A\u672A\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u540C\u6B65\u3002" : e.message.slice(0, 500) : "WECHAT_SYNC_FAILED";
18171
- const connected = this.native.isConnected?.() ?? false;
18172
- if (!connected) this.state.automatic = false;
18252
+ const reason = e instanceof Error ? e.message.slice(0, 500) : "WECHAT_SYNC_FAILED";
18253
+ this.state.message = reason === "WECHAT_COMMIT_UNCONFIRMED" ? "\u6D88\u606F\u5C1A\u672A\u786E\u8BA4\u4FDD\u5B58\uFF0C\u8BF7\u91CD\u65B0\u540C\u6B65\u3002" : reason;
18254
+ if (loginPending) this.state.message = "WECHAT_LOGIN_RETRY_REQUIRED";
18255
+ if (loginPending || !this.native.isConnected?.()) this.state.automatic = false;
18173
18256
  }
18174
18257
  } finally {
18175
18258
  this.state.running = false;
18176
18259
  this.state.consent = void 0;
18177
- if (!this.closed) {
18178
- if (!this.state.automatic && this.state.phase !== "error") this.state.phase = "paused";
18179
- this.schedule(this.failures ? Math.min(12e4, 3e4 * 2 ** (this.failures - 1)) : this.dirty ? 0 : this.interval);
18180
- }
18260
+ if (!this.state.automatic && this.state.phase !== "error") this.state.phase = "paused";
18261
+ if (retryLoginIn !== void 0) this.schedule(retryLoginIn, () => this.cycle(fullSync, true, loginAttempt + 1));
18262
+ else this.schedule(this.failures ? Math.min(12e4, 3e4 * 2 ** (this.failures - 1)) : this.dirty ? 0 : this.interval);
18181
18263
  }
18182
18264
  }
18183
18265
  pause(workspace) {
@@ -36744,19 +36826,20 @@ async function exportObservation(event, keys, extra2) {
36744
36826
  }
36745
36827
  };
36746
36828
  const ids = identities(event);
36747
- const processor = new LangfuseSpanProcessor({ exporter, baseUrl: event.target.baseUrl, publicKey: keys.publicKey, secretKey: keys.secretKey, environment: event.agent || event.question ? "knowledge-agent" : "knowledge-test", mediaUploadEnabled: false, shouldExportSpan: () => true, flushAt: 1e3, flushInterval: 3600 });
36829
+ const processor = new LangfuseSpanProcessor({ exporter, baseUrl: event.target.baseUrl, publicKey: keys.publicKey, secretKey: keys.secretKey, environment: event.agent || event.question || event.knowledgeCall ? "knowledge-agent" : "knowledge-test", mediaUploadEnabled: false, shouldExportSpan: () => true, flushAt: 1e3, flushInterval: 3600 });
36748
36830
  const provider = new import_sdk_trace_base2.BasicTracerProvider({ sampler: new import_sdk_trace_base2.AlwaysOnSampler(), spanProcessors: [processor], idGenerator: { generateTraceId: () => ids.traceId, generateSpanId: () => ids.spanId }, spanLimits: { attributeCountLimit: 256, attributeValueLengthLimit: 2 * 1024 * 1024 } });
36749
36831
  try {
36750
36832
  const context2 = event.kind === "read" && event.requestId ? trace.setSpanContext(ROOT_CONTEXT, { traceId: ids.traceId, spanId: stableId("wanji-search:" + event.requestId, 16), traceFlags: TraceFlags.SAMPLED, isRemote: true }) : ROOT_CONTEXT;
36751
- const span = provider.getTracer("langfuse-sdk", "wanji-sales-0.4.0").startSpan(event.question?.source ?? (event.output.audit_kind === "storage" ? "knowledge_storage_audit" : event.kind === "answer" ? "knowledge_answer" : event.kind === "search" ? "weknora_search" : "weknora_read_document"), { startTime: new Date(event.startedAt), attributes: {
36752
- "langfuse.trace.name": event.question ? "\u9500\u552E\u95EE\u7B54" : event.kind === "answer" ? "\u77E5\u8BC6\u5E93\u56DE\u7B54\u8BC4\u6D4B" : "\u9500\u552E\u77E5\u8BC6\u5E93\u68C0\u7D22",
36833
+ const span = provider.getTracer("langfuse-sdk", "wanji-sales-0.4.0").startSpan(event.question?.source ?? event.knowledgeCall?.name ?? (event.output.audit_kind === "storage" ? "knowledge_storage_audit" : event.kind === "answer" ? "knowledge_answer" : event.kind === "search" ? "weknora_search" : "weknora_read_document"), { startTime: new Date(event.startedAt), attributes: {
36834
+ "langfuse.trace.name": event.question ? "\u9500\u552E\u95EE\u7B54" : event.knowledgeCall ? "\u9500\u552E\u77E5\u8BC6\u5E93\u8C03\u7528" : event.kind === "answer" ? "\u77E5\u8BC6\u5E93\u56DE\u7B54\u8BC4\u6D4B" : "\u9500\u552E\u77E5\u8BC6\u5E93\u68C0\u7D22",
36753
36835
  "langfuse.trace.tags": event.question ? ["sales-question", event.question.source] : ["sales-knowledge", "harness-tool"],
36754
36836
  "langfuse.observation.type": event.question ? "chain" : event.kind === "answer" ? "span" : event.kind === "search" ? "retriever" : "tool",
36755
36837
  "langfuse.observation.input": JSON.stringify(event.input),
36756
36838
  "langfuse.observation.output": JSON.stringify(event.output),
36757
36839
  "langfuse.observation.metadata.knowledge_base_id": event.knowledgeBaseId,
36758
36840
  "langfuse.observation.metadata.event_id": event.id,
36759
- "langfuse.observation.metadata.source": event.question?.source ?? (event.agent ? "agent" : "test"),
36841
+ "langfuse.observation.metadata.source": event.question?.source ?? (event.knowledgeCall ? "sales-knowledge-call" : event.agent ? "agent" : "test"),
36842
+ ...event.knowledgeCall ? { "langfuse.observation.metadata.call_id": event.knowledgeCall.callId, "langfuse.observation.metadata.caller": event.agent ? "agent" : "workbench" } : {},
36760
36843
  ...event.question ? {
36761
36844
  "session.id": event.question.sessionId,
36762
36845
  "langfuse.trace.session_id": event.question.sessionId,
@@ -36788,6 +36871,10 @@ async function exportObservation(event, keys, extra2) {
36788
36871
  span.setStatus({ code: SpanStatusCode.ERROR });
36789
36872
  span.setAttribute("langfuse.observation.level", "ERROR");
36790
36873
  }
36874
+ if (event.knowledgeCall && ["error", "timeout"].includes(String(event.output.status))) {
36875
+ span.setStatus({ code: SpanStatusCode.ERROR });
36876
+ span.setAttribute("langfuse.observation.level", "ERROR");
36877
+ }
36791
36878
  span.end(new Date(Date.parse(event.startedAt) + event.elapsedMs));
36792
36879
  await provider.forceFlush();
36793
36880
  if (failed || !acknowledged) throw new Error("upload-failed");
@@ -36823,7 +36910,7 @@ import { join as join7 } from "node:path";
36823
36910
  import { randomUUID as randomUUID11 } from "node:crypto";
36824
36911
  var maxBytes = 2 * 1024 * 1024;
36825
36912
  function validEvent(event) {
36826
- const validKind = event.kind === "question" ? !!event.question && /^[a-zA-Z0-9_-]{1,160}$/.test(event.question.sessionId) && ["sales-reply", "sales-agent", "knowledge-search"].includes(event.question.source) : ["search", "read", "answer"].includes(event.kind) && !event.question;
36913
+ const validKind = event.kind === "question" ? !!event.question && /^[a-zA-Z0-9_-]{1,160}$/.test(event.question.sessionId) && ["sales-reply", "sales-agent", "knowledge-search"].includes(event.question.source) : !event.question && (event.kind === "tool" ? !!event.knowledgeCall && /^[a-zA-Z][a-zA-Z0-9_]{0,95}$/.test(event.knowledgeCall.name) && typeof event.knowledgeCall.callId === "string" : ["search", "read", "answer"].includes(event.kind));
36827
36914
  return validKind && /^[a-zA-Z0-9_-]{1,160}$/.test(event.id) && Number.isFinite(Date.parse(event.startedAt)) && Number.isFinite(event.elapsedMs) && event.elapsedMs >= 0 && !!event.input && !!event.output;
36828
36915
  }
36829
36916
  var LangfuseOutbox = class {
@@ -36929,9 +37016,10 @@ var LangfuseOutbox = class {
36929
37016
  // src/agent-knowledge.ts
36930
37017
  var object2 = (v2) => v2 && typeof v2 === "object" && !Array.isArray(v2) ? v2 : {};
36931
37018
  var list = (v2) => Array.isArray(v2) ? v2 : [];
37019
+ var knowledgeOperations = ["search", "read_document", "ask", "list_knowledge_bases"];
36932
37020
  function agentMetricValues(event) {
36933
37021
  const s3 = event.output.status;
36934
- if (event.kind === "answer") return {};
37022
+ if (event.kind === "answer" || event.kind === "tool") return {};
36935
37023
  if (s3 === "interrupted" || s3 === "capture-truncated") return {};
36936
37024
  if (event.kind === "read") return { document_read_success: s3 === "success" ? 1 : 0, document_read_elapsed_ms: event.elapsedMs };
36937
37025
  const ok = s3 === "success" || s3 === "empty";
@@ -36963,6 +37051,7 @@ var AgentKnowledgeObserver = class {
36963
37051
  entries = /* @__PURE__ */ new Map();
36964
37052
  finished = /* @__PURE__ */ new Set();
36965
37053
  grants = /* @__PURE__ */ new Map();
37054
+ documentScopes = /* @__PURE__ */ new Map();
36966
37055
  writes = Promise.resolve();
36967
37056
  pendingWrites = 0;
36968
37057
  target;
@@ -37009,32 +37098,57 @@ var AgentKnowledgeObserver = class {
37009
37098
  if (stamp !== void 0 && Date.now() - stamp < 36e5) return "read";
37010
37099
  }
37011
37100
  }
37101
+ callScope(exec) {
37102
+ const { toolPrefix, knowledgeBaseId, material } = this.options;
37103
+ const matches = (prefix) => knowledgeOperations.some((operation) => exec.name === prefix + "_" + operation);
37104
+ const allowed2 = [...matches(toolPrefix) ? [knowledgeBaseId] : [], ...material && matches(material.toolPrefix) ? [material.knowledgeBaseId] : []];
37105
+ const args = object2(exec.arguments), requested = args.knowledge_base_ids;
37106
+ if (requested !== void 0 && (!Array.isArray(requested) || requested.some((id2) => !allowed2.includes(id2)))) return;
37107
+ if (requested?.length === 1) return requested[0];
37108
+ if (allowed2.length === 1) return allowed2[0];
37109
+ const documentBase = exec.name.endsWith("_read_document") ? this.documentScopes.get(args.knowledge_id) : void 0;
37110
+ if (documentBase && allowed2.includes(documentBase)) return documentBase;
37111
+ if (allowed2.length) return "unverified";
37112
+ }
37113
+ rememberDocumentScopes(value, knowledgeBaseId) {
37114
+ if (list(value.knowledge_base_ids).length !== 1 || value.knowledge_base_ids[0] !== knowledgeBaseId) return;
37115
+ for (const doc of [...list(value.documents), ...list(value.results)]) {
37116
+ if (typeof doc?.knowledge_id !== "string" || doc.knowledge_base_id !== void 0 && doc.knowledge_base_id !== knowledgeBaseId) continue;
37117
+ const known = this.documentScopes.get(doc.knowledge_id);
37118
+ this.documentScopes.set(doc.knowledge_id, known && known !== knowledgeBaseId ? "unverified" : knowledgeBaseId);
37119
+ }
37120
+ while (this.documentScopes.size > 2e3) this.documentScopes.delete(this.documentScopes.keys().next().value);
37121
+ }
37012
37122
  begin(exec, dispatched) {
37013
37123
  if (this.finished.has(exec.token)) return;
37014
37124
  const existing = this.entries.get(exec.token);
37015
37125
  if (existing) return existing;
37016
- const kind = this.eligible(exec);
37017
- if (!kind || !this.target) return;
37126
+ if (!this.target) return;
37127
+ const detailed = this.eligible(exec);
37128
+ const knowledgeBaseId = detailed ? this.options.knowledgeBaseId : dispatched ? this.callScope(exec) : void 0;
37129
+ if (!knowledgeBaseId) return;
37130
+ const kind = detailed ?? "tool";
37018
37131
  if (this.entries.size >= 1e3) {
37019
37132
  this.dropped++;
37020
37133
  this.error = "capture-capacity";
37021
37134
  return;
37022
37135
  }
37023
- const input = this.sanitize(JSON.parse(JSON.stringify(object2(exec.arguments))));
37136
+ const input = detailed ? this.sanitize(JSON.parse(JSON.stringify(object2(exec.arguments)))) : {};
37024
37137
  if (Buffer.byteLength(JSON.stringify(input)) > 32e3) {
37025
37138
  this.dropped++;
37026
37139
  this.error = "input-too-large";
37027
37140
  return;
37028
37141
  }
37029
- const entry = { turn: this.turns.current(exec.agent.id)?.turn, since: performance.now(), event: {
37142
+ const entry = { turn: exec.agent ? this.turns.current(exec.agent.id)?.turn : void 0, since: performance.now(), event: {
37030
37143
  id: randomUUID12(),
37031
37144
  target: this.target,
37032
37145
  kind,
37033
- knowledgeBaseId: this.options.knowledgeBaseId,
37146
+ knowledgeBaseId,
37034
37147
  startedAt: (/* @__PURE__ */ new Date()).toISOString(),
37035
37148
  elapsedMs: 0,
37036
37149
  input,
37037
- agent: { sessionId: exec.agent.id, callId: exec.callId, rootCallId: exec.rootCallId, nested: exec.parent !== void 0, dispatched, instanceId: this.instanceId },
37150
+ ...detailed ? {} : { knowledgeCall: { name: exec.name, callId: exec.callId, instanceId: this.instanceId } },
37151
+ ...exec.agent ? { agent: { sessionId: exec.agent.id, callId: exec.callId, rootCallId: exec.rootCallId, nested: exec.parent !== void 0, dispatched, instanceId: this.instanceId } } : {},
37038
37152
  output: { status: "interrupted", judge_eligible: false, outcome_known: false }
37039
37153
  } };
37040
37154
  this.entries.set(exec.token, entry);
@@ -37058,7 +37172,7 @@ var AgentKnowledgeObserver = class {
37058
37172
  }
37059
37173
  /** At most 20ms local journal wait; no network or model is awaited by the search. */
37060
37174
  async start(exec) {
37061
- if (!this.eligible(exec)) return;
37175
+ if (this.lifetime.signal.aborted || !this.eligible(exec) && !this.callScope(exec)) return;
37062
37176
  try {
37063
37177
  const work = this.ready.then(() => {
37064
37178
  const entry = this.begin(exec, true);
@@ -37077,14 +37191,15 @@ var AgentKnowledgeObserver = class {
37077
37191
  }
37078
37192
  /** Harness emits a frozen final result. Snapshot synchronously, persist asynchronously. */
37079
37193
  finish(exec, result) {
37080
- if (!this.eligible(exec)) {
37081
- if (exec.agent?.id && [this.options.toolPrefix + "_search", this.options.toolPrefix + "_read_document"].includes(exec.name)) this.turns.invalidate(exec.agent.id);
37082
- return;
37083
- }
37194
+ if (this.finished.has(exec.token) || this.lifetime.signal.aborted) return;
37084
37195
  if (!this.initialized) {
37085
37196
  void this.ready.then(() => this.finish(exec, result));
37086
37197
  return;
37087
37198
  }
37199
+ if (!this.entries.has(exec.token) && !this.eligible(exec)) {
37200
+ if (exec.agent?.id && [this.options.toolPrefix + "_search", this.options.toolPrefix + "_read_document"].includes(exec.name)) this.turns.invalidate(exec.agent.id);
37201
+ return;
37202
+ }
37088
37203
  try {
37089
37204
  const entry = this.entries.get(exec.token) ?? this.begin(exec, false);
37090
37205
  if (!entry) return;
@@ -37092,6 +37207,21 @@ var AgentKnowledgeObserver = class {
37092
37207
  this.finished.add(exec.token);
37093
37208
  while (this.finished.size > 5e3) this.finished.delete(this.finished.values().next().value);
37094
37209
  const event = { ...entry.event, elapsedMs: Math.max(0, Math.round(performance.now() - entry.since)) }, value = object2(result.value);
37210
+ if (event.kind === "tool") {
37211
+ if (exec.agent && ["search", "read_document"].some((operation) => exec.name === this.options.toolPrefix + "_" + operation)) this.turns.invalidate(exec.agent.id);
37212
+ const returnedBase = value.knowledge_base_id ?? (list(value.knowledge_base_ids).length === 1 ? value.knowledge_base_ids[0] : void 0);
37213
+ if (event.knowledgeBaseId === "unverified" && [this.options.knowledgeBaseId, this.options.material?.knowledgeBaseId].includes(returnedBase)) event.knowledgeBaseId = returnedBase;
37214
+ const code4 = result.error?.info?.code;
37215
+ const empty = value.returned_chunks === 0 || exec.name.endsWith("_search") && !list(value.results).length && !list(value.documents).length;
37216
+ const status2 = result.isError ? code4 === "TOOL_TIMEOUT" ? "timeout" : exec.signal.aborted ? "cancelled" : "error" : empty ? "empty" : "success";
37217
+ if (!result.isError && exec.name.endsWith("_search")) this.rememberDocumentScopes(value, event.knowledgeBaseId);
37218
+ event.output = { status: status2 };
37219
+ void this.queue(async () => {
37220
+ await this.outbox.put(event);
37221
+ await this.started.remove(event);
37222
+ });
37223
+ return;
37224
+ }
37095
37225
  if (!result.isError && event.kind === "search") {
37096
37226
  const bases = list(value.knowledge_base_ids);
37097
37227
  if (!bases.length || bases.some((id2) => id2 !== this.options.knowledgeBaseId) || list(value.documents).some((d) => d.knowledge_base_id !== this.options.knowledgeBaseId) || list(value.results).some((d) => d.knowledge_base_id !== void 0 && d.knowledge_base_id !== this.options.knowledgeBaseId)) {
@@ -37102,6 +37232,7 @@ var AgentKnowledgeObserver = class {
37102
37232
  }
37103
37233
  for (const d of [...list(value.results), ...list(value.documents)]) if (typeof d.knowledge_id === "string") this.grants.set(exec.agent.id + "\0" + d.knowledge_id, Date.now());
37104
37234
  while (this.grants.size > 2e3) this.grants.delete(this.grants.keys().next().value);
37235
+ this.rememberDocumentScopes(value, event.knowledgeBaseId);
37105
37236
  }
37106
37237
  if (!result.isError && event.kind === "read" && (value.knowledge_id !== object2(exec.arguments).knowledge_id || value.knowledge_base_id !== void 0 && value.knowledge_base_id !== this.options.knowledgeBaseId)) {
37107
37238
  this.turns.invalidate(exec.agent.id);
@@ -37136,6 +37267,24 @@ var AgentKnowledgeObserver = class {
37136
37267
  this.dropped++;
37137
37268
  }
37138
37269
  }
37270
+ recordMaterialMetadata(knowledgeBaseId, startedAt, elapsedMs, status) {
37271
+ const callId = randomUUID12();
37272
+ void this.ready.then(() => {
37273
+ if (!this.target || this.lifetime.signal.aborted || knowledgeBaseId !== this.options.material?.knowledgeBaseId) return;
37274
+ const event = {
37275
+ id: callId,
37276
+ target: this.target,
37277
+ knowledgeBaseId,
37278
+ kind: "tool",
37279
+ knowledgeCall: { name: "weknora_material_metadata", callId },
37280
+ startedAt,
37281
+ elapsedMs,
37282
+ input: {},
37283
+ output: { status }
37284
+ };
37285
+ return this.queue(() => this.outbox.put(event));
37286
+ });
37287
+ }
37139
37288
  async drain() {
37140
37289
  await this.ready;
37141
37290
  await this.writes;
@@ -37159,7 +37308,7 @@ var AgentKnowledgeObserver = class {
37159
37308
  try {
37160
37309
  await this.started.flush(async (event) => {
37161
37310
  await this.outbox.put({ ...event, output: { status: "interrupted", judge_eligible: false, outcome_known: false } });
37162
- }, this.lifetime.signal, (event) => event.agent?.instanceId !== this.instanceId);
37311
+ }, this.lifetime.signal, (event) => (event.agent?.instanceId ?? event.knowledgeCall?.instanceId) !== this.instanceId);
37163
37312
  this.recoveryError = void 0;
37164
37313
  } catch {
37165
37314
  this.recoveryError = "journal-recovery-pending";
@@ -38944,6 +39093,32 @@ var knowledgeCases = [
38944
39093
 
38945
39094
  // src/material-catalog.ts
38946
39095
  import { randomUUID as randomUUID17 } from "node:crypto";
39096
+
39097
+ // src/customer-materials.ts
39098
+ var MATERIAL_KB_ID = "1f93aee2-6d66-42d7-8b7a-b5fe5d094550";
39099
+ var materialKinds = ["video", "document", "image", "any"];
39100
+ var materialEditions2 = ["\u95E8\u5E97\u7248", "\u4E13\u4E1A\u7248", "\u6807\u51C6\u7248", "unknown"];
39101
+ function assetUrl(value, sha) {
39102
+ const u2 = new URL(value);
39103
+ if (u2.protocol !== "https:" || u2.hostname !== "im-wanji.oss-cn-shanghai.aliyuncs.com" || u2.port || u2.username || u2.password || u2.search || u2.hash || !/^([a-f0-9]{64})$/.test(sha) || !u2.pathname.includes("/knowledge-assets/test/") || !new RegExp("/" + sha + "\\.(?:mp4|pdf|png|jpe?g)$", "i").test(u2.pathname)) throw Error("MATERIAL_URL_INVALID");
39104
+ return u2.href;
39105
+ }
39106
+ function parseCustomerMaterials(value) {
39107
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("\u7D20\u6750\u8FD4\u56DE\u683C\u5F0F\u65E0\u6548\u3002");
39108
+ const v2 = value;
39109
+ if (!["available", "not_found", "unavailable", "edition_required"].includes(v2.status) || v2.knowledgeBaseId !== MATERIAL_KB_ID || !Number.isFinite(Date.parse(v2.checkedAt)) || !Array.isArray(v2.items) || v2.items.length > 6) throw Error("\u7D20\u6750\u8FD4\u56DE\u8303\u56F4\u65E0\u6548\u3002");
39110
+ const seen = /* @__PURE__ */ new Set();
39111
+ for (const m2 of v2.items) {
39112
+ if (!m2 || typeof m2.id !== "string" || seen.has(m2.id) || typeof m2.title !== "string" || !m2.title.trim() || !["video", "document", "image"].includes(m2.kind) || !["\u95E8\u5E97\u7248", "\u4E13\u4E1A\u7248", "\u6807\u51C6\u7248"].includes(m2.edition) || typeof m2.knowledgeId !== "string" || typeof m2.assetId !== "string" || typeof m2.version !== "string" || !m2.version || typeof m2.text !== "string" || m2.text.length > 12e3 || typeof m2.boundary !== "string") throw Error("\u7D20\u6750\u8EAB\u4EFD\u65E0\u6548\u3002");
39113
+ const file = assetUrl(m2.fileUrl, m2.fileSha256), url = file + (m2.kind === "document" && m2.page ? `#page=${m2.page}` : "");
39114
+ if (m2.page !== void 0 && (!Number.isInteger(m2.page) || m2.page < 1 || m2.page > 1e4) || m2.url !== url) throw Error("\u7D20\u6750\u9875\u7801\u6216\u94FE\u63A5\u65E0\u6548\u3002");
39115
+ seen.add(m2.id);
39116
+ }
39117
+ if (v2.status === "available" && !v2.items.length || v2.status !== "available" && v2.items.length) throw Error("\u7D20\u6750\u72B6\u6001\u4E0E\u6761\u76EE\u4E0D\u4E00\u81F4\u3002");
39118
+ return v2;
39119
+ }
39120
+
39121
+ // src/material-catalog.ts
38947
39122
  var fileTypes = {
38948
39123
  pdf: { kind: "document", mime: "application/pdf", extension: /\.pdf$/i },
38949
39124
  png: { kind: "image", mime: "image/png", extension: /\.png$/i },
@@ -38981,6 +39156,18 @@ function fileLocation(value, kind) {
38981
39156
  }
38982
39157
  return void 0;
38983
39158
  }
39159
+ function qualifiedMaterialHits(response, query, calibrated) {
39160
+ const passages = array2(response.results).map(record);
39161
+ const documents = array2(response.documents).map(record);
39162
+ if (!calibrated) return [...passages, ...documents];
39163
+ const normalize = (text6) => text6.normalize("NFKC").replace(/\s/g, "").toLowerCase();
39164
+ const request2 = normalize(query);
39165
+ const hasTitle = (title) => typeof title === "string" && normalize(title).length >= 4 && request2.includes(normalize(title));
39166
+ return [
39167
+ ...passages.filter((hit) => typeof hit.score === "number" && Number.isFinite(hit.score) && hit.score >= 0.8 || hasTitle(hit.document)),
39168
+ ...documents.filter((doc) => hasTitle(doc.title))
39169
+ ];
39170
+ }
38984
39171
  function createMaterialCatalog(config, maxResults, invoke, readMetadata, head = fetch) {
38985
39172
  const grants = /* @__PURE__ */ new Map();
38986
39173
  async function inspect(id2, constraints, signal) {
@@ -38990,6 +39177,9 @@ function createMaterialCatalog(config, maxResults, invoke, readMetadata, head =
38990
39177
  if (meta.access_mode !== "public_customer" || !["ready", "published"].includes(String(meta.asset_status)) || !["passed", "version_scoped_reference", "explicit_user_authorized_original"].includes(String(meta.customer_use)) || meta.delivery_behavior !== "download_to_view" || typeof meta.selection_profile !== "string" || typeof meta.file_url !== "string") return void 0;
38991
39178
  const profile3 = record(JSON.parse(meta.selection_profile));
38992
39179
  if (profile3.schema !== 1 || typeof profile3.file_format !== "string" || !Object.hasOwn(fileTypes, profile3.file_format)) return void 0;
39180
+ if (constraints.currentVersion && profile3.subtype === "historical_feature_overview") return void 0;
39181
+ if (constraints.publicationPurpose && constraints.publicationPurpose !== profile3.purpose) return void 0;
39182
+ if (constraints.interfaceImage && constraints.publicationPurpose !== "product_introduction" && profile3.purpose === "product_introduction") return void 0;
38993
39183
  const format = profile3.file_format;
38994
39184
  const type = fileTypes[format];
38995
39185
  if (profile3.mime_type !== type.mime || meta.asset_kind !== type.kind || constraints.kind && constraints.kind !== type.kind || constraints.format && constraints.format !== format) return void 0;
@@ -39004,8 +39194,15 @@ function createMaterialCatalog(config, maxResults, invoke, readMetadata, head =
39004
39194
  }
39005
39195
  const url = new URL(meta.file_url);
39006
39196
  if (!url.href.startsWith(config.assetBaseUrl) || url.username || url.password || url.search || url.hash || !type.extension.test(url.pathname)) return void 0;
39007
- const candidate = { id: id2, title: modelText(source.title, 240), topic: modelText(typeof meta.topic === "string" ? meta.topic : "", 120), kind: type.kind, format, scope: modelText(scopeLabel, 160) };
39008
- return { candidate, url: url.href, location: fileLocation(profile3.locator, type.kind) };
39197
+ const deliveryNote = typeof profile3.delivery_note === "string" ? modelText(profile3.delivery_note, 200) : "";
39198
+ const candidate = { id: id2, title: modelText(source.title, 240), topic: modelText(typeof meta.topic === "string" ? meta.topic : "", 120), kind: type.kind, format, scope: modelText(scopeLabel, 160), ...deliveryNote ? { deliveryNote } : {} };
39199
+ const location = profile3.subtype === "historical_feature_overview" ? "\u529F\u80FD\u53CA\u5B50\u8D26\u53F7\u6570\u91CF\u4EE5\u672C\u5355\u73B0\u884C\u89C4\u5219\u4E3A\u51C6" : fileLocation(profile3.locator, type.kind);
39200
+ const operation = scope.status === "explicit_edition" && ["operation_reference", "operation_learning"].includes(String(profile3.purpose));
39201
+ return { candidate, url: url.href, location, operation };
39202
+ }
39203
+ async function readEvidence(id2, signal) {
39204
+ const doc = parseDocument(await invoke("read_document", { knowledge_id: id2, page: 1, page_size: 4 }, signal));
39205
+ return doc.knowledge_id === id2 && doc.page === 1 ? modelText(doc.content, 1900) : "";
39009
39206
  }
39010
39207
  async function available(id2, constraints, signal) {
39011
39208
  try {
@@ -39033,16 +39230,20 @@ function createMaterialCatalog(config, maxResults, invoke, readMetadata, head =
39033
39230
  const constraints = materialConstraints(query);
39034
39231
  if (constraints.ambiguous) return { status: "clarify" };
39035
39232
  if (constraints.format && !fileTypes[constraints.format]) return { status: "empty" };
39233
+ const calibrated = config.knowledgeBaseId === MATERIAL_KB_ID;
39234
+ let originalHasEvidence = false;
39036
39235
  async function candidates(searchQuery) {
39037
39236
  const response = record(await invoke("search", { query: searchQuery, knowledge_base_ids: [config.knowledgeBaseId], max_results: maxResults }, signal));
39038
39237
  if (response.query !== searchQuery || !Array.isArray(response.knowledge_base_ids) || response.knowledge_base_ids.length !== 1 || response.knowledge_base_ids[0] !== config.knowledgeBaseId) throw new KnowledgeError("scope-mismatch");
39039
- const ids = [...new Set([...array2(response.results), ...array2(response.documents)].map((v2) => record(v2).knowledge_id))].filter((id2) => typeof id2 === "string" && /^[\w-]{1,128}$/.test(id2)).slice(0, maxResults);
39238
+ const hits = qualifiedMaterialHits(response, query, calibrated);
39239
+ if (searchQuery === query) originalHasEvidence = hits.length > 0;
39240
+ const ids = [...new Set(hits.map((hit) => hit.knowledge_id))].filter((id2) => typeof id2 === "string" && /^[\w-]{1,128}$/.test(id2)).slice(0, maxResults);
39040
39241
  const reads = await Promise.allSettled(ids.map(async (id2) => {
39041
39242
  const item = await available(id2, constraints, signal);
39042
39243
  if (!item) return void 0;
39043
- const doc = parseDocument(await invoke("read_document", { knowledge_id: id2, page: 1, page_size: 4 }, signal));
39044
- if (doc.knowledge_id !== id2 || doc.page !== 1 || !doc.content.trim()) return void 0;
39045
- return { ...item, candidate: { ...item.candidate, evidence: modelText(doc.content, 1900) } };
39244
+ const evidence3 = await readEvidence(id2, signal);
39245
+ if (!evidence3) return void 0;
39246
+ return { ...item, candidate: { ...item.candidate, evidence: evidence3 } };
39046
39247
  }));
39047
39248
  signal.throwIfAborted();
39048
39249
  const checked2 = reads.flatMap((read) => read.status === "fulfilled" && read.value ? [read.value] : []);
@@ -39053,7 +39254,9 @@ function createMaterialCatalog(config, maxResults, invoke, readMetadata, head =
39053
39254
  const topicQueries = constraints.kind === "video" || !constraints.kind ? materialTopicQueries(query) : [];
39054
39255
  let checked;
39055
39256
  if (topicQueries.length) {
39056
- const settled = await Promise.allSettled([query, ...topicQueries].map(candidates));
39257
+ const original = calibrated ? await candidates(query) : void 0;
39258
+ if (calibrated && !originalHasEvidence) return { status: "empty" };
39259
+ const settled = await Promise.allSettled([original ?? candidates(query), ...topicQueries.map(candidates)]);
39057
39260
  signal.throwIfAborted();
39058
39261
  const mismatch = settled.find((item) => item.status === "rejected" && item.reason instanceof KnowledgeError && item.reason.code === "scope-mismatch");
39059
39262
  if (mismatch?.status === "rejected") throw mismatch.reason;
@@ -39061,7 +39264,7 @@ function createMaterialCatalog(config, maxResults, invoke, readMetadata, head =
39061
39264
  const failed = settled.find((item) => item.status === "rejected");
39062
39265
  if (!checked.length && failed?.status === "rejected") throw failed.reason;
39063
39266
  } else checked = await candidates(query);
39064
- if (!checked.length && query.length <= 3900) {
39267
+ if (!checked.length && (!calibrated || originalHasEvidence) && query.length <= 3900) {
39065
39268
  const formatHint = constraints.comparison && !constraints.kind ? "\u6309\u7248\u672C\u5BF9\u7167\u7684\u64CD\u4F5C\u624B\u518C PDF \u6307\u5357" : constraints.kind === "video" ? "\u89C6\u9891\u6559\u7A0B \u64CD\u4F5C\u6F14\u793A" : constraints.kind === "document" ? "\u64CD\u4F5C\u624B\u518C PDF \u6307\u5357" : constraints.kind === "image" ? "\u754C\u9762\u622A\u56FE \u56FE\u7247\u53C2\u8003" : void 0;
39066
39269
  if (formatHint) checked = await candidates(query + "\n" + formatHint);
39067
39270
  }
@@ -39069,24 +39272,36 @@ function createMaterialCatalog(config, maxResults, invoke, readMetadata, head =
39069
39272
  if (!checked.length) return { status: "empty" };
39070
39273
  const requestId = randomUUID17();
39071
39274
  if (grants.size >= 128) grants.delete(grants.keys().next().value);
39072
- grants.set(requestId, { owner, expires: Date.now() + 12e4, constraints, urls: new Map(checked.map((item) => [item.candidate.id, item.url])), remaining: 3 });
39275
+ grants.set(requestId, { owner, expires: Date.now() + 12e4, constraints, items: new Map(checked.map((item) => [item.candidate.id, { url: item.url, evidence: item.candidate.evidence }])), remaining: 3 });
39073
39276
  return { status: "candidates", requestId, candidates: checked.map((item) => item.candidate) };
39074
39277
  },
39075
39278
  async resolve(requestId, id2, owner, signal) {
39076
39279
  const grant = grants.get(requestId);
39077
- const authorizedUrl = grant?.urls.get(id2);
39078
- if (!grant || grant.owner !== owner || grant.expires <= Date.now() || !authorizedUrl) return { status: "empty" };
39079
- grant.urls.delete(id2);
39080
- if (--grant.remaining === 0 || !grant.urls.size) grants.delete(requestId);
39280
+ const authorized = grant?.items.get(id2);
39281
+ if (!grant || grant.owner !== owner || grant.expires <= Date.now() || !authorized) return { status: "empty" };
39282
+ grant.items.delete(id2);
39283
+ if (--grant.remaining === 0 || !grant.items.size) grants.delete(requestId);
39081
39284
  const item = await available(id2, grant.constraints, signal);
39082
39285
  signal.throwIfAborted();
39083
- return item && item.url === authorizedUrl && await readable(item.url, item.candidate.format, signal) ? { status: "matched", id: id2, title: item.candidate.title, url: item.url, scope: item.candidate.scope, format: item.candidate.format, ...item.location ? { location: item.location } : {} } : { status: "empty" };
39286
+ if (!item || item.url !== authorized.url || !await readable(item.url, item.candidate.format, signal)) return { status: "empty" };
39287
+ if (item.operation && await readEvidence(id2, signal) !== authorized.evidence) return { status: "empty" };
39288
+ return {
39289
+ status: "matched",
39290
+ id: id2,
39291
+ title: item.candidate.title,
39292
+ url: item.url,
39293
+ scope: item.candidate.scope,
39294
+ format: item.candidate.format,
39295
+ ...item.location ? { location: item.location } : {},
39296
+ ...item.candidate.deliveryNote ? { deliveryNote: item.candidate.deliveryNote } : {},
39297
+ ...item.operation ? { operationEvidence: authorized.evidence } : {}
39298
+ };
39084
39299
  }
39085
39300
  };
39086
39301
  }
39087
39302
 
39088
39303
  // src/material-metadata.ts
39089
- function createMaterialMetadataReader(connection, requestTimeoutMs) {
39304
+ function createMaterialMetadataReader(connection, requestTimeoutMs, record3) {
39090
39305
  const headers = new Headers({ Accept: "application/json", "X-API-Key": connection.apiKey });
39091
39306
  if (connection.tenantId) headers.set("X-Tenant-ID", connection.tenantId);
39092
39307
  return async (id2, signal) => {
@@ -39094,19 +39309,34 @@ function createMaterialMetadataReader(connection, requestTimeoutMs) {
39094
39309
  signal.throwIfAborted();
39095
39310
  const timeout = AbortSignal.timeout(requestTimeoutMs);
39096
39311
  const fused = AbortSignal.any([signal, timeout]);
39312
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString(), started = performance.now();
39313
+ let status = "error";
39097
39314
  try {
39098
39315
  const response = await fetch(connection.baseUrl + "/knowledge/" + id2, { method: "GET", headers, signal: fused, redirect: "error" });
39099
39316
  const value = await readWeKnoraData(response);
39100
39317
  fused.throwIfAborted();
39318
+ status = "success";
39101
39319
  return value;
39102
39320
  } catch (error) {
39321
+ if (signal.aborted) status = "cancelled";
39103
39322
  signal.throwIfAborted();
39104
- if (timeout.aborted) throw new KnowledgeError("timeout");
39323
+ if (timeout.aborted) {
39324
+ status = "timeout";
39325
+ throw new KnowledgeError("timeout");
39326
+ }
39105
39327
  if (error instanceof KnowledgeError) {
39106
- if (error.code === "not-found") return void 0;
39328
+ if (error.code === "not-found") {
39329
+ status = "empty";
39330
+ return void 0;
39331
+ }
39107
39332
  throw error;
39108
39333
  }
39109
39334
  throw new KnowledgeError("service-unreachable");
39335
+ } finally {
39336
+ try {
39337
+ record3?.(startedAt, Math.round(performance.now() - started), status);
39338
+ } catch {
39339
+ }
39110
39340
  }
39111
39341
  };
39112
39342
  }
@@ -39114,32 +39344,6 @@ function createMaterialMetadataReader(connection, requestTimeoutMs) {
39114
39344
  // src/material-retrieval.ts
39115
39345
  import { readFile as readFile11 } from "node:fs/promises";
39116
39346
  import { createHash as createHash9 } from "node:crypto";
39117
-
39118
- // src/customer-materials.ts
39119
- var MATERIAL_KB_ID = "1f93aee2-6d66-42d7-8b7a-b5fe5d094550";
39120
- var materialKinds = ["video", "document", "image", "any"];
39121
- var materialEditions2 = ["\u95E8\u5E97\u7248", "\u4E13\u4E1A\u7248", "\u6807\u51C6\u7248", "unknown"];
39122
- function assetUrl(value, sha) {
39123
- const u2 = new URL(value);
39124
- if (u2.protocol !== "https:" || u2.hostname !== "im-wanji.oss-cn-shanghai.aliyuncs.com" || u2.port || u2.username || u2.password || u2.search || u2.hash || !/^([a-f0-9]{64})$/.test(sha) || !u2.pathname.includes("/knowledge-assets/test/") || !new RegExp("/" + sha + "\\.(?:mp4|pdf|png|jpe?g)$", "i").test(u2.pathname)) throw Error("MATERIAL_URL_INVALID");
39125
- return u2.href;
39126
- }
39127
- function parseCustomerMaterials(value) {
39128
- if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("\u7D20\u6750\u8FD4\u56DE\u683C\u5F0F\u65E0\u6548\u3002");
39129
- const v2 = value;
39130
- if (!["available", "not_found", "unavailable", "edition_required"].includes(v2.status) || v2.knowledgeBaseId !== MATERIAL_KB_ID || !Number.isFinite(Date.parse(v2.checkedAt)) || !Array.isArray(v2.items) || v2.items.length > 6) throw Error("\u7D20\u6750\u8FD4\u56DE\u8303\u56F4\u65E0\u6548\u3002");
39131
- const seen = /* @__PURE__ */ new Set();
39132
- for (const m2 of v2.items) {
39133
- if (!m2 || typeof m2.id !== "string" || seen.has(m2.id) || typeof m2.title !== "string" || !m2.title.trim() || !["video", "document", "image"].includes(m2.kind) || !["\u95E8\u5E97\u7248", "\u4E13\u4E1A\u7248", "\u6807\u51C6\u7248"].includes(m2.edition) || typeof m2.knowledgeId !== "string" || typeof m2.assetId !== "string" || typeof m2.version !== "string" || !m2.version || typeof m2.text !== "string" || m2.text.length > 12e3 || typeof m2.boundary !== "string") throw Error("\u7D20\u6750\u8EAB\u4EFD\u65E0\u6548\u3002");
39134
- const file = assetUrl(m2.fileUrl, m2.fileSha256), url = file + (m2.kind === "document" && m2.page ? `#page=${m2.page}` : "");
39135
- if (m2.page !== void 0 && (!Number.isInteger(m2.page) || m2.page < 1 || m2.page > 1e4) || m2.url !== url) throw Error("\u7D20\u6750\u9875\u7801\u6216\u94FE\u63A5\u65E0\u6548\u3002");
39136
- seen.add(m2.id);
39137
- }
39138
- if (v2.status === "available" && !v2.items.length || v2.status !== "available" && v2.items.length) throw Error("\u7D20\u6750\u72B6\u6001\u4E0E\u6761\u76EE\u4E0D\u4E00\u81F4\u3002");
39139
- return v2;
39140
- }
39141
-
39142
- // src/material-retrieval.ts
39143
39347
  var identityFields = ["source_key", "asset_id", "asset_kind", "asset_version", "file_url", "file_sha256", "access_mode", "asset_status", "customer_use", "product_edition", "release_version", "page", "privacy_status"];
39144
39348
  function bindCustomerMaterial(hit, catalog, edition, kind) {
39145
39349
  if (hit.truncated || hit.chunk_type !== "text" || /^# Summary\b/.test(hit.content)) return;
@@ -39320,12 +39524,12 @@ function inputFields(payload, allowed2) {
39320
39524
  if (Object.keys(p2).some((key) => !allowed2.includes(key))) throw new KnowledgeError("bad-request");
39321
39525
  return p2;
39322
39526
  }
39323
- function createKnowledgeHost(tools, config, lifetime = new AbortController().signal, outbox, evaluationOrWorkspaces, injectedObserver, rerank, materialOverride, expandQuery) {
39527
+ function createKnowledgeHost(tools, config, lifetime = new AbortController().signal, outbox, evaluationOrWorkspaces, injectedObserver, rerank, materialOverride, expandQuery, recordMaterialMetadata) {
39324
39528
  const workspaceList = typeof evaluationOrWorkspaces === "function" ? evaluationOrWorkspaces : void 0;
39325
39529
  const evaluationService = typeof evaluationOrWorkspaces === "function" ? void 0 : evaluationOrWorkspaces;
39326
39530
  const contexts = /* @__PURE__ */ new WeakMap();
39327
39531
  const materialConfig = resolveMaterialConfig(config.materialKnowledgeBaseId, config.materialAssetBaseUrl);
39328
- const material = materialConfig && config.materialMetadata ? createMaterialCatalog(materialConfig, config.maxResults, (suffix, args, signal) => invoke(suffix, args, signal, config.materialToolPrefix ?? config.toolPrefix), createMaterialMetadataReader(config.materialMetadata, config.requestTimeoutMs)) : void 0;
39532
+ const material = materialConfig && config.materialMetadata ? createMaterialCatalog(materialConfig, config.maxResults, (suffix, args, signal) => invoke(suffix, args, signal, config.materialToolPrefix ?? config.toolPrefix), createMaterialMetadataReader(config.materialMetadata, config.requestTimeoutMs, recordMaterialMetadata)) : void 0;
39329
39533
  const materialContexts = /* @__PURE__ */ new WeakMap();
39330
39534
  const materials = config.materialRetrievalEnabled ? materialOverride ?? new MaterialRetriever(tools, config.materialToolPrefix, void 0, config.evaluationMaterialIds, config.semanticRerank ? rerank : void 0) : void 0;
39331
39535
  const grants = /* @__PURE__ */ new WeakMap();
@@ -39602,11 +39806,11 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
39602
39806
  };
39603
39807
  return handle;
39604
39808
  }
39605
- function apply2(ctx, config, agentStatus, rerank, expandQuery, recordQuestion) {
39809
+ function apply2(ctx, config, agentStatus, rerank, expandQuery, recordQuestion, recordMaterialMetadata) {
39606
39810
  const lifetime = new AbortController();
39607
39811
  const resolved = resolveKnowledgeConfig(config);
39608
39812
  const outbox = resolved.knowledgeTestEnabled ? new EvaluationOutbox(join11(homedir5(), ".local", "state", "wanji-sales", `${resolved.toolPrefix}-${resolved.knowledgeBaseIds[0]}`)) : void 0;
39609
- const handler = createKnowledgeHost(ctx.tools, resolved, lifetime.signal, outbox, ctx.workspaceRegistry ? () => ctx.workspaceRegistry.list() : void 0, void 0, rerank, void 0, expandQuery);
39813
+ const handler = createKnowledgeHost(ctx.tools, resolved, lifetime.signal, outbox, ctx.workspaceRegistry ? () => ctx.workspaceRegistry.list() : void 0, void 0, rerank, void 0, expandQuery, recordMaterialMetadata);
39610
39814
  const owner = { principal: { kind: "owner" } };
39611
39815
  for (const endpoint of ["info", "cases", "search", "read", "evaluation", "context", "validate-context", "workspaces", "render-reply", "materials", "validate-materials"]) {
39612
39816
  const method = KNOWLEDGE_ENDPOINT_PREFIX + endpoint;
@@ -43743,8 +43947,15 @@ function apply3(ctx, rawConfig = {}) {
43743
43947
  ctx.effect(() => dispose);
43744
43948
  }
43745
43949
  let observer;
43950
+ const tracedMaterialId = config.materialKnowledgeBaseId ?? config.materialKnowledgeBaseIds?.[0];
43746
43951
  if (config.agentKnowledgeTracing && config.langfuseConfigFile && ctx.on) {
43747
- const active = new AgentKnowledgeObserver({ configFile: config.langfuseConfigFile, directory: join14(homedir6(), ".local", "state", "wanji-sales", "langfuse-agent"), knowledgeBaseId: config.knowledgeBaseIds[0], toolPrefix: config.toolPrefix });
43952
+ const active = new AgentKnowledgeObserver({
43953
+ configFile: config.langfuseConfigFile,
43954
+ directory: join14(homedir6(), ".local", "state", "wanji-sales", "langfuse-agent"),
43955
+ knowledgeBaseId: config.knowledgeBaseIds[0],
43956
+ toolPrefix: config.toolPrefix,
43957
+ ...tracedMaterialId ? { material: { knowledgeBaseId: tracedMaterialId, toolPrefix: config.materialToolPrefix ?? config.toolPrefix } } : {}
43958
+ });
43748
43959
  observer = active;
43749
43960
  const offExecute = ctx.on("tools/execute", async (exec, next) => {
43750
43961
  await active.start(exec);
@@ -43790,7 +44001,7 @@ function apply3(ctx, rawConfig = {}) {
43790
44001
  if (!selected?.provider || selected.model !== "deepseek-v4.1-flash") throw Error("QUERY_FLASH_UNAVAILABLE");
43791
44002
  const value = await runModel(ctx.llm, { ...selected, maxTokens: 240 }, { system: "\u53EA\u63D0\u70BC\u53EA\u8BFB\u68C0\u7D22\u77ED\u8BED\uFF0C\u4E0D\u4F5C\u7B54\u3001\u4E0D\u6279\u51C6\u4E8B\u5B9E\u3002", text: queryExpansionPrompt(query) }, signal);
43792
44003
  return parseQueryExpansion(value);
43793
- }, questions?.finish.bind(questions));
44004
+ }, questions?.finish.bind(questions), observer && tracedMaterialId ? (startedAt, elapsedMs, status) => observer?.recordMaterialMetadata(tracedMaterialId, startedAt, elapsedMs, status) : void 0);
43794
44005
  registerQuestionRoute(child, questions);
43795
44006
  let generationRuntime;
43796
44007
  child.effect(() => async () => {