@wanji_dsh/dsh-sales 0.11.1 → 0.11.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/host.js CHANGED
@@ -9579,22 +9579,22 @@ var require_common_serializer = __commonJS({
9579
9579
  }
9580
9580
  }
9581
9581
  exports.writeAnyValue = writeAnyValue;
9582
- function writeInstrumentationScope(writer, scope, fieldNumber) {
9582
+ function writeInstrumentationScope(writer, scope2, fieldNumber) {
9583
9583
  writer.writeTag(fieldNumber, 2);
9584
9584
  const start = writer.startLengthDelimited();
9585
9585
  const startPos = writer.pos;
9586
9586
  writer.writeTag(1, 2);
9587
- writer.writeString(scope.name);
9588
- if (scope.version) {
9587
+ writer.writeString(scope2.name);
9588
+ if (scope2.version) {
9589
9589
  writer.writeTag(2, 2);
9590
- writer.writeString(scope.version);
9590
+ writer.writeString(scope2.version);
9591
9591
  }
9592
- if (scope.attributes) {
9593
- writeAttributes(writer, scope.attributes, 3);
9592
+ if (scope2.attributes) {
9593
+ writeAttributes(writer, scope2.attributes, 3);
9594
9594
  }
9595
- if (scope.droppedAttributesCount) {
9595
+ if (scope2.droppedAttributesCount) {
9596
9596
  writer.writeTag(4, 0);
9597
- writer.writeVarint(scope.droppedAttributesCount);
9597
+ writer.writeVarint(scope2.droppedAttributesCount);
9598
9598
  }
9599
9599
  writer.finishLengthDelimited(start, writer.pos - startPos);
9600
9600
  }
@@ -9738,17 +9738,17 @@ var require_logs_serializer = __commonJS({
9738
9738
  }
9739
9739
  writer.finishLengthDelimited(logStart, writer.pos - logStartPos);
9740
9740
  }
9741
- function serializeScopeLogs(writer, scope, logRecords) {
9741
+ function serializeScopeLogs(writer, scope2, logRecords) {
9742
9742
  const scopeLogsStart = writer.startLengthDelimited();
9743
9743
  const scopeLogsStartPos = writer.pos;
9744
- (0, common_serializer_1.writeInstrumentationScope)(writer, scope, 1);
9744
+ (0, common_serializer_1.writeInstrumentationScope)(writer, scope2, 1);
9745
9745
  for (const logRecord of logRecords) {
9746
9746
  writer.writeTag(2, 2);
9747
9747
  serializeLogRecord(writer, logRecord);
9748
9748
  }
9749
- if (scope.schemaUrl) {
9749
+ if (scope2.schemaUrl) {
9750
9750
  writer.writeTag(3, 2);
9751
- writer.writeString(scope.schemaUrl);
9751
+ writer.writeString(scope2.schemaUrl);
9752
9752
  }
9753
9753
  writer.finishLengthDelimited(scopeLogsStart, writer.pos - scopeLogsStartPos);
9754
9754
  }
@@ -9758,8 +9758,8 @@ var require_logs_serializer = __commonJS({
9758
9758
  (0, common_serializer_1.writeResource)(writer, resource, 1);
9759
9759
  for (const scopeLogs of scopeMap.values()) {
9760
9760
  writer.writeTag(2, 2);
9761
- const scope = scopeLogs[0].instrumentationScope;
9762
- serializeScopeLogs(writer, scope, scopeLogs);
9761
+ const scope2 = scopeLogs[0].instrumentationScope;
9762
+ serializeScopeLogs(writer, scope2, scopeLogs);
9763
9763
  }
9764
9764
  if (resource.schemaUrl) {
9765
9765
  writer.writeTag(3, 2);
@@ -9771,16 +9771,16 @@ var require_logs_serializer = __commonJS({
9771
9771
  const resourceMap = /* @__PURE__ */ new Map();
9772
9772
  for (const record3 of logRecords) {
9773
9773
  const resource = record3.resource;
9774
- const scope = record3.instrumentationScope;
9774
+ const scope2 = record3.instrumentationScope;
9775
9775
  let ismMap = resourceMap.get(resource);
9776
9776
  if (!ismMap) {
9777
9777
  ismMap = /* @__PURE__ */ new Map();
9778
9778
  resourceMap.set(resource, ismMap);
9779
9779
  }
9780
- let records = ismMap.get(scope);
9780
+ let records = ismMap.get(scope2);
9781
9781
  if (!records) {
9782
9782
  records = [];
9783
- ismMap.set(scope, records);
9783
+ ismMap.set(scope2, records);
9784
9784
  }
9785
9785
  records.push(record3);
9786
9786
  }
@@ -14339,17 +14339,17 @@ var require_trace_serializer = __commonJS({
14339
14339
  }
14340
14340
  writer.finishLengthDelimited(spanStart, writer.pos - spanStartPos);
14341
14341
  }
14342
- function serializeScopeSpans(writer, scope, spans) {
14342
+ function serializeScopeSpans(writer, scope2, spans) {
14343
14343
  const scopeSpansStart = writer.startLengthDelimited();
14344
14344
  const scopeSpansStartPos = writer.pos;
14345
- (0, common_serializer_1.writeInstrumentationScope)(writer, scope, 1);
14345
+ (0, common_serializer_1.writeInstrumentationScope)(writer, scope2, 1);
14346
14346
  for (const span of spans) {
14347
14347
  writer.writeTag(2, 2);
14348
14348
  serializeSpan(writer, span);
14349
14349
  }
14350
- if (scope.schemaUrl) {
14350
+ if (scope2.schemaUrl) {
14351
14351
  writer.writeTag(3, 2);
14352
- writer.writeString(scope.schemaUrl);
14352
+ writer.writeString(scope2.schemaUrl);
14353
14353
  }
14354
14354
  writer.finishLengthDelimited(scopeSpansStart, writer.pos - scopeSpansStartPos);
14355
14355
  }
@@ -14359,8 +14359,8 @@ var require_trace_serializer = __commonJS({
14359
14359
  (0, common_serializer_1.writeResource)(writer, resource, 1);
14360
14360
  for (const scopeSpans of scopeMap.values()) {
14361
14361
  writer.writeTag(2, 2);
14362
- const scope = scopeSpans[0].instrumentationScope;
14363
- serializeScopeSpans(writer, scope, scopeSpans);
14362
+ const scope2 = scopeSpans[0].instrumentationScope;
14363
+ serializeScopeSpans(writer, scope2, scopeSpans);
14364
14364
  }
14365
14365
  if (resource.schemaUrl) {
14366
14366
  writer.writeTag(3, 2);
@@ -14372,16 +14372,16 @@ var require_trace_serializer = __commonJS({
14372
14372
  const resourceMap = /* @__PURE__ */ new Map();
14373
14373
  for (const span of spans) {
14374
14374
  const resource = span.resource;
14375
- const scope = span.instrumentationScope;
14375
+ const scope2 = span.instrumentationScope;
14376
14376
  let scopeMap = resourceMap.get(resource);
14377
14377
  if (!scopeMap) {
14378
14378
  scopeMap = /* @__PURE__ */ new Map();
14379
14379
  resourceMap.set(resource, scopeMap);
14380
14380
  }
14381
- let records = scopeMap.get(scope);
14381
+ let records = scopeMap.get(scope2);
14382
14382
  if (!records) {
14383
14383
  records = [];
14384
- scopeMap.set(scope, records);
14384
+ scopeMap.set(scope2, records);
14385
14385
  }
14386
14386
  records.push(span);
14387
14387
  }
@@ -14512,14 +14512,14 @@ var require_internal = __commonJS({
14512
14512
  return result;
14513
14513
  }
14514
14514
  exports.createResource = createResource;
14515
- function createInstrumentationScope(scope, encoder) {
14515
+ function createInstrumentationScope(scope2, encoder) {
14516
14516
  const result = {
14517
- name: scope.name,
14518
- version: scope.version
14517
+ name: scope2.name,
14518
+ version: scope2.version
14519
14519
  };
14520
- if (scope.attributes && Object.keys(scope.attributes).length > 0) {
14521
- result.attributes = toAttributes(scope.attributes, encoder);
14522
- result.droppedAttributesCount = scope.droppedAttributesCount ?? 0;
14520
+ if (scope2.attributes && Object.keys(scope2.attributes).length > 0) {
14521
+ result.attributes = toAttributes(scope2.attributes, encoder);
14522
+ result.droppedAttributesCount = scope2.droppedAttributesCount ?? 0;
14523
14523
  }
14524
14524
  return result;
14525
14525
  }
@@ -15811,8 +15811,186 @@ var require_src7 = __commonJS({
15811
15811
  }
15812
15812
  });
15813
15813
 
15814
- // src/wechat/cua-approval.ts
15814
+ // src/diagnostics.ts
15815
+ import { AsyncLocalStorage } from "node:async_hooks";
15815
15816
  import { randomUUID } from "node:crypto";
15817
+ import { appendFile, lstat, mkdir, readdir, unlink } from "node:fs/promises";
15818
+ import { homedir, release } from "node:os";
15819
+ import { isAbsolute, join } from "node:path";
15820
+
15821
+ // src/update/version.ts
15822
+ var RUNNING_VERSION = true ? "0.11.3" : "0.0.0-dev";
15823
+
15824
+ // src/diagnostics.ts
15825
+ var MAX_FILE_BYTES = 512 * 1024;
15826
+ var MAX_FILES = 8;
15827
+ var RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
15828
+ var FILE_NAME = /^host-(\d{13})-[a-f0-9-]{36}\.jsonl$/;
15829
+ var safeCodes = new Set(`
15830
+ ERR_MODULE_NOT_FOUND ERR_DLOPEN_FAILED MODULE_NOT_FOUND
15831
+ EACCES EADDRINUSE ECONNABORTED ECONNREFUSED ECONNRESET EHOSTDOWN EHOSTUNREACH
15832
+ EAI_AGAIN EBUSY EEXIST EIO ENETUNREACH ENOENT ENOSPC ENOTDIR ENOTEMPTY
15833
+ ENOTFOUND EPERM EPIPE EROFS ETIMEDOUT UND_ERR_CONNECT_TIMEOUT
15834
+ UND_ERR_HEADERS_TIMEOUT UND_ERR_BODY_TIMEOUT UND_ERR_SOCKET
15835
+ UNABLE_TO_VERIFY_LEAF_SIGNATURE SELF_SIGNED_CERT_IN_CHAIN DEPTH_ZERO_SELF_SIGNED_CERT CERT_HAS_EXPIRED
15836
+ TimeoutError AbortError SyntaxError TypeError ABORT_ERR
15837
+ UNKNOWN_TOOL TOOL_TIMEOUT TOOL_ERROR CANCELLED INVALID_CONFIG INVALID_INPUT INVALID_JSON
15838
+ MODEL_NOT_CONFIGURED MODEL_QUOTA_EXHAUSTED MODEL_INCOMPLETE MODEL_INVALID_STREAM MODEL_OUTPUT_TOO_LARGE INVALID_MODEL_OUTPUT
15839
+ MATERIAL_SCOPE_INVALID MATERIAL_QUERY_INVALID MATERIAL_RANK_INVALID
15840
+ RESPONSE_TOO_LARGE CRM_INTENT_UNAVAILABLE CRM_UNAVAILABLE CRM_NOT_FOUND CRM_AMBIGUOUS CRM_INVALID_INPUT CRM_INVALID_RESPONSE
15841
+ WECHAT_COMMIT_UNCONFIRMED WECHAT_COMPONENT_UNAVAILABLE WECHAT_RECONNECT_REQUIRED
15842
+ WECHAT_WORKSPACE_SCOPE WECHAT_INVALID_REQUEST WECHAT_CUA_UNAVAILABLE WECHAT_BUSY
15843
+ WECHAT_RUNTIME_UNSUPPORTED WECHAT_RUNTIME_MANIFEST WECHAT_RUNTIME_URL WECHAT_RUNTIME_CACHE
15844
+ WECHAT_RUNTIME_NETWORK WECHAT_RUNTIME_HTTP WECHAT_RUNTIME_TIMEOUT WECHAT_RUNTIME_ABORTED
15845
+ WECHAT_RUNTIME_ARCHIVE WECHAT_RUNTIME_COMPONENT WECHAT_RUNTIME_CHECKSUM WECHAT_RUNTIME_LIMIT
15846
+ WECHAT_RUNTIME_SELF_TEST WECHAT_RUNTIME_SELF_TEST_TIMEOUT WECHAT_RUNTIME_NOT_READY
15847
+ UPDATE_PREPARING UPDATE_BUSY UPDATE_NETWORK UPDATE_FAILED UPDATE_RESULT_UNKNOWN UPDATE_VERSION_QUERY_FAILED
15848
+ UPDATE_WINDOW_NOT_READY UPDATE_TARGET_CHANGED UPDATE_STATE_CHANGED
15849
+ operation-error package-manager-error validation-error
15850
+ bad-request disabled stale-context material-unavailable forbidden not-found invalid-response service-error service-unreachable scope-mismatch
15851
+ unavailable not-configured missing-tools timeout cancelled tool-failed recording-unavailable
15852
+ configuration-unavailable credentials-unavailable authentication-failed upload-rejected
15853
+ upload-failed invalid-event queue-full invalid-receipt invalid-config invalid-target invalid-target-url connection-failed
15854
+ unsupported-server-version project-mismatch agent-evaluators-not-ready
15855
+ production-target-mismatch test-target-required redaction-unavailable knowledge-environment-mismatch
15856
+ question-relay-unavailable invalid-question-receipt invalid-question-event
15857
+ `.trim().split(/\s+/));
15858
+ function safeCode(value) {
15859
+ return typeof value === "string" && safeCodes.has(value) ? value : void 0;
15860
+ }
15861
+ function errorFacts(error) {
15862
+ if (!error || typeof error !== "object") return {};
15863
+ const value = error;
15864
+ return {
15865
+ code: safeCode(value.code) ?? safeCode(value.message) ?? safeCode(value.name),
15866
+ causeCode: safeCode(value.cause?.code) ?? safeCode(value.cause?.name),
15867
+ httpStatus: typeof value.status === "number" && Number.isInteger(value.status) && value.status >= 100 && value.status <= 599 ? value.status : void 0
15868
+ };
15869
+ }
15870
+ function diagnosticsDirectory() {
15871
+ if (process.platform === "win32") {
15872
+ const local = process.env.LOCALAPPDATA;
15873
+ return join(local && isAbsolute(local) ? local : join(homedir(), "AppData", "Local"), "DSHSales", "Logs");
15874
+ }
15875
+ return join(homedir(), "Library", "Logs", "DSHSales");
15876
+ }
15877
+ var DiagnosticJournal = class {
15878
+ hostId = randomUUID();
15879
+ pending = 0;
15880
+ dropped = 0;
15881
+ writes = Promise.resolve();
15882
+ file;
15883
+ directory;
15884
+ constructor(directory = diagnosticsDirectory()) {
15885
+ this.directory = directory;
15886
+ }
15887
+ // Callers supply static component/operation labels. Numeric fields and
15888
+ // booleans are copied explicitly rather than serializing arbitrary metadata.
15889
+ record(operation, outcome, facts, error, operationId) {
15890
+ if (process.env.WANJI_DIAGNOSTICS_ENABLED === "false") return;
15891
+ if (this.pending >= 256) {
15892
+ this.dropped++;
15893
+ return;
15894
+ }
15895
+ let details = {};
15896
+ try {
15897
+ details = errorFacts(error);
15898
+ } catch {
15899
+ }
15900
+ const { elapsedMs, httpStatus, count, bytes, configured, enabled } = facts;
15901
+ const time = Date.now();
15902
+ this.pending++;
15903
+ this.writes = this.writes.then(async () => {
15904
+ const line = JSON.stringify({
15905
+ schema: 1,
15906
+ source: "sales-host",
15907
+ time: new Date(time).toISOString(),
15908
+ hostId: this.hostId,
15909
+ operationId,
15910
+ pluginVersion: RUNNING_VERSION,
15911
+ nodeVersion: process.versions.node,
15912
+ platform: process.platform,
15913
+ architecture: process.arch,
15914
+ osRelease: release(),
15915
+ operation,
15916
+ outcome,
15917
+ code: details.code ?? (outcome === "failed" ? "unknown-error" : void 0),
15918
+ causeCode: details.causeCode,
15919
+ elapsedMs,
15920
+ httpStatus: httpStatus ?? details.httpStatus,
15921
+ count,
15922
+ bytes,
15923
+ configured,
15924
+ enabled,
15925
+ dropped: this.dropped
15926
+ }) + "\n";
15927
+ await this.append(time, line);
15928
+ }).catch(() => {
15929
+ this.file = void 0;
15930
+ this.dropped++;
15931
+ }).finally(() => {
15932
+ this.pending--;
15933
+ });
15934
+ }
15935
+ flush() {
15936
+ return this.writes;
15937
+ }
15938
+ async append(time, line) {
15939
+ const size = Buffer.byteLength(line);
15940
+ if (!this.file || this.file.bytes + size > MAX_FILE_BYTES || time - this.file.opened >= 864e5) {
15941
+ await mkdir(this.directory, { recursive: true, mode: 448 });
15942
+ if (!(await lstat(this.directory)).isDirectory()) throw Error("unsafe diagnostic directory");
15943
+ const entries = (await readdir(this.directory, { withFileTypes: true })).filter((entry) => entry.isFile() && FILE_NAME.test(entry.name)).map((entry) => entry.name).sort().reverse();
15944
+ const expired = entries.filter((name2, index2) => index2 >= MAX_FILES - 1 || time - Number(FILE_NAME.exec(name2)[1]) > RETENTION_MS);
15945
+ for (const name2 of expired) await unlink(join(this.directory, name2)).catch(() => {
15946
+ });
15947
+ const path3 = join(this.directory, `host-${time}-${randomUUID()}.jsonl`);
15948
+ await appendFile(path3, line, { flag: "wx", mode: 384 });
15949
+ this.file = { path: path3, bytes: size, opened: time };
15950
+ return;
15951
+ }
15952
+ if (!(await lstat(this.file.path)).isFile()) throw Error("unsafe diagnostic file");
15953
+ await appendFile(this.file.path, line, { flag: "a", mode: 384 });
15954
+ this.file.bytes += size;
15955
+ }
15956
+ };
15957
+ var scope = new AsyncLocalStorage();
15958
+ var journal;
15959
+ function withDiagnostics(run, target) {
15960
+ return scope.getStore() && !target ? run() : scope.run({ journal: target ?? (journal ??= new DiagnosticJournal()) }, run);
15961
+ }
15962
+ function diagnostic(operation, outcome, facts = {}, error) {
15963
+ const current = scope.getStore();
15964
+ current?.journal.record(operation, outcome, facts, error, current.operationId);
15965
+ }
15966
+ function diagnosticOperation(run, operationId) {
15967
+ const current = scope.getStore();
15968
+ if (!current) return run();
15969
+ return scope.run({ journal: current.journal, operationId: operationId ?? randomUUID() }, run);
15970
+ }
15971
+ function diagnosticCallback(run) {
15972
+ const current = scope.getStore();
15973
+ return current ? (...args) => scope.run({ journal: current.journal }, () => run(...args)) : run;
15974
+ }
15975
+ async function diagnosticHttp(operation, send, signal) {
15976
+ const started = performance.now();
15977
+ try {
15978
+ const response = await send();
15979
+ diagnostic(operation, response.ok ? "ok" : response.status >= 300 && response.status < 400 ? "pending" : "failed", { httpStatus: response.status, elapsedMs: Math.round(performance.now() - started) });
15980
+ return response;
15981
+ } catch (error) {
15982
+ diagnostic(
15983
+ operation,
15984
+ signal?.aborted && signal.reason?.name !== "TimeoutError" ? "cancelled" : "failed",
15985
+ { elapsedMs: Math.round(performance.now() - started) },
15986
+ signal?.aborted ? signal.reason : error
15987
+ );
15988
+ throw error;
15989
+ }
15990
+ }
15991
+
15992
+ // src/wechat/cua-approval.ts
15993
+ import { randomUUID as randomUUID2 } from "node:crypto";
15816
15994
  var CuaApprovalBroker = class {
15817
15995
  pending = /* @__PURE__ */ new Map();
15818
15996
  view(workspaceId) {
@@ -15833,7 +16011,7 @@ var CuaApprovalBroker = class {
15833
16011
  };
15834
16012
  try {
15835
16013
  return await new Promise((resolve4, reject) => {
15836
- const requestId = randomUUID(), cancel = () => reject(Error("WECHAT_DELIVERY_APPROVAL_ABORTED"));
16014
+ const requestId = randomUUID2(), cancel = () => reject(Error("WECHAT_DELIVERY_APPROVAL_ABORTED"));
15837
16015
  cleanup = () => {
15838
16016
  request2.signal?.removeEventListener("abort", cancel);
15839
16017
  if (this.pending.get(workspaceId)?.view.requestId === requestId) this.pending.delete(workspaceId);
@@ -15852,7 +16030,7 @@ var CuaApprovalBroker = class {
15852
16030
  };
15853
16031
 
15854
16032
  // src/wechat/cua-sender.ts
15855
- import { randomUUID as randomUUID2 } from "node:crypto";
16033
+ import { randomUUID as randomUUID3 } from "node:crypto";
15856
16034
 
15857
16035
  // src/wechat/cua-vision.ts
15858
16036
  import { spawn } from "node:child_process";
@@ -15867,9 +16045,9 @@ function screenHasIdentity(screen, identity) {
15867
16045
  const values = screen.regions.filter((r) => r.confidence >= 0.25);
15868
16046
  return values.some((r) => /^微信号\s*[::]/.test(r.text) && r.text.replace(/^微信号\s*[::]\s*/, "").trim() === identity) || values.some((label) => label.text.replace(/[::\s]/g, "") === "\u5FAE\u4FE1\u53F7" && values.some((value) => value.text.trim() === identity && value.x > label.x + label.width && Math.abs(value.y - label.y) < Math.max(value.height, label.height)));
15869
16047
  }
15870
- function profileAnchor(screen, name2, text7) {
16048
+ function profileAnchor(screen, name2, text6) {
15871
16049
  const header = chatHeading(screen, name2);
15872
- const messages = screen.regions.filter((r2) => r2.text === text7 && r2.x > header.x && r2.y > header.y + header.height * 2).sort((a, b2) => b2.y - a.y);
16050
+ const messages = screen.regions.filter((r2) => r2.text === text6 && r2.x > header.x && r2.y > header.y + header.height * 2).sort((a, b2) => b2.y - a.y);
15873
16051
  const message = messages[0];
15874
16052
  if (!message) throw Error("WECHAT_DELIVERY_CHAT_MISMATCH");
15875
16053
  const candidates = (screen.rectangles ?? []).filter((r2) => r2.confidence >= 0.9 && r2.x + r2.width / 2 >= header.x && r2.x + r2.width < message.x && message.x - r2.x < message.height * 6 && Math.abs(r2.y + r2.height / 2 - message.y - message.height / 2) < message.height * 2 && r2.width >= message.height && r2.width < message.height * 5 && r2.height >= message.height && r2.height < message.height * 5);
@@ -15913,7 +16091,7 @@ async function recognizeWechatScreen(binary, data, signal) {
15913
16091
  async function dispatchCua(services, agent, method, params, signal) {
15914
16092
  const prefix = "__WANJI_CUA__";
15915
16093
  const code4 = `var r=await tools.cua(${JSON.stringify({ method, params })});console.log(${JSON.stringify(prefix)}+JSON.stringify(${method === "screenshot" ? "{attachmentId:r.attachmentId,path:r.path,width:r.width,height:r.height}" : "r"}))`;
15916
- const result = await services.tools.execute({ agent, calls: [{ type: "tool-call", id: randomUUID2(), name: "run_code", arguments: JSON.stringify({ code: code4, description: "\u4E07\u673A\u5FAE\u4FE1\u754C\u9762\u64CD\u4F5C" }) }], signal });
16094
+ const result = await services.tools.execute({ agent, calls: [{ type: "tool-call", id: randomUUID3(), name: "run_code", arguments: JSON.stringify({ code: code4, description: "\u4E07\u673A\u5FAE\u4FE1\u754C\u9762\u64CD\u4F5C" }) }], signal });
15917
16095
  const r = result.results[0]?.result;
15918
16096
  if (!r || r.isError) throw Error(r?.error?.message ?? "WECHAT_CUA_FAILED");
15919
16097
  const value = r.value;
@@ -16023,9 +16201,9 @@ var DshWechatSender = class {
16023
16201
  if (!services) throw Error("WECHAT_CUA_UNAVAILABLE");
16024
16202
  let handle = this.sessions.get(workspaceId);
16025
16203
  if (!handle) {
16026
- handle = services.agents.create({ sessionId: randomUUID2(), meta: { cwd, agentPreset: "ptc" }, setup: async (scope) => {
16027
- await services.mountPreset(scope);
16028
- services.registerApproval(scope, (request2, next) => this.approvals.ask(workspaceId, request2, next));
16204
+ handle = services.agents.create({ sessionId: randomUUID3(), meta: { cwd, agentPreset: "ptc" }, setup: async (scope2) => {
16205
+ await services.mountPreset(scope2);
16206
+ services.registerApproval(scope2, (request2, next) => this.approvals.ask(workspaceId, request2, next));
16029
16207
  } });
16030
16208
  this.sessions.set(workspaceId, handle);
16031
16209
  void handle.catch(() => this.sessions.delete(workspaceId));
@@ -16099,9 +16277,9 @@ var DshWechatSender = class {
16099
16277
  if (!services) throw Error("WECHAT_CUA_UNAVAILABLE");
16100
16278
  let handle = this.sessions.get(input.workspaceId);
16101
16279
  if (!handle) {
16102
- handle = services.agents.create({ sessionId: randomUUID2(), meta: { cwd, agentPreset: "ptc" }, setup: async (scope) => {
16103
- await services.mountPreset(scope);
16104
- services.registerApproval(scope, (request2, next) => this.approvals.ask(input.workspaceId, request2, next));
16280
+ handle = services.agents.create({ sessionId: randomUUID3(), meta: { cwd, agentPreset: "ptc" }, setup: async (scope2) => {
16281
+ await services.mountPreset(scope2);
16282
+ services.registerApproval(scope2, (request2, next) => this.approvals.ask(input.workspaceId, request2, next));
16105
16283
  } });
16106
16284
  this.sessions.set(input.workspaceId, handle);
16107
16285
  void handle.catch(() => {
@@ -16167,7 +16345,7 @@ var DshWechatSender = class {
16167
16345
  import { readFile as readFile14, stat as stat3 } from "node:fs/promises";
16168
16346
 
16169
16347
  // src/update/activity.ts
16170
- import { AsyncLocalStorage } from "node:async_hooks";
16348
+ import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
16171
16349
  var pause = (signal, ms2 = 25) => new Promise((resolve4, reject) => {
16172
16350
  if (signal.aborted) {
16173
16351
  reject(signal.reason);
@@ -16183,7 +16361,7 @@ var pause = (signal, ms2 = 25) => new Promise((resolve4, reject) => {
16183
16361
  signal.addEventListener("abort", abort, { once: true });
16184
16362
  });
16185
16363
  var UpdateActivity = class {
16186
- scope = new AsyncLocalStorage();
16364
+ scope = new AsyncLocalStorage2();
16187
16365
  pending = 0;
16188
16366
  draining = false;
16189
16367
  async run(work, continuation = false) {
@@ -16251,9 +16429,9 @@ var deliveryCompletions = /* @__PURE__ */ new Set(["delivery-status", "delivery-
16251
16429
  async function deliveryCompletion(request2) {
16252
16430
  if (new URL(request2.url).pathname !== "/api/" + WECHAT_METHOD || request2.method !== "POST") return false;
16253
16431
  try {
16254
- const text7 = await request2.clone().text();
16255
- if (text7.length > 1e5) return false;
16256
- const envelope = JSON.parse(text7);
16432
+ const text6 = await request2.clone().text();
16433
+ if (text6.length > 1e5) return false;
16434
+ const envelope = JSON.parse(text6);
16257
16435
  return envelope?.type === "client-request" && envelope.method === WECHAT_METHOD && deliveryCompletions.has(envelope.payload?.operation);
16258
16436
  } catch {
16259
16437
  return false;
@@ -16268,13 +16446,38 @@ function guardSalesActivity(context2, activity) {
16268
16446
  }
16269
16447
  };
16270
16448
  const tools = optional("tools"), connection = optional("connection");
16449
+ const inDiagnostics = diagnosticCallback((work) => diagnosticOperation(work));
16450
+ const guardedTool = (definition) => (...args) => inDiagnostics(async () => {
16451
+ const start = performance.now(), operation = "tool." + definition.name;
16452
+ diagnostic(operation, "started");
16453
+ try {
16454
+ const value = await activity.run(() => definition.execute(...args));
16455
+ diagnostic(operation, "ok", { elapsedMs: Math.round(performance.now() - start) });
16456
+ return value;
16457
+ } catch (error) {
16458
+ diagnostic(operation, args[1]?.signal?.aborted ? "cancelled" : "failed", { elapsedMs: Math.round(performance.now() - start) }, error);
16459
+ throw error;
16460
+ }
16461
+ });
16271
16462
  const guardedTools = tools && new Proxy(tools, { get(target, key) {
16272
- if (key === "register") return (definition) => target.register({ ...definition, execute: (...args) => activity.run(() => definition.execute(...args)) });
16463
+ if (key === "register") return (definition) => target.register({ ...definition, execute: guardedTool(definition) });
16273
16464
  if (key === "execute") return (...args) => activity.run(() => target.execute(...args));
16274
16465
  const value = Reflect.get(target, key, target);
16275
16466
  return typeof value === "function" ? value.bind(target) : value;
16276
16467
  } });
16277
- const guardedFetch = connection && { register: (route) => connection.fetch.register({ ...route, fetch: async (request2) => activity.run(() => route.fetch(request2), await deliveryCompletion(request2)) }) };
16468
+ const guardedFetch = connection && { register: (route) => connection.fetch.register({ ...route, fetch: diagnosticCallback(
16469
+ (request2) => diagnosticOperation(async () => {
16470
+ const start = performance.now();
16471
+ try {
16472
+ const response = await activity.run(() => route.fetch(request2), await deliveryCompletion(request2));
16473
+ if (response instanceof Response && !response.ok) diagnostic("rpc" + route.path, "failed", { httpStatus: response.status, elapsedMs: Math.round(performance.now() - start) });
16474
+ return response;
16475
+ } catch (error) {
16476
+ diagnostic("rpc" + route.path, request2.signal.aborted ? "cancelled" : "failed", { elapsedMs: Math.round(performance.now() - start) }, error);
16477
+ throw error;
16478
+ }
16479
+ })
16480
+ ) }) };
16278
16481
  const guardedConnection = connection && new Proxy(connection, { get(target, key) {
16279
16482
  if (key === "fetch") return guardedFetch;
16280
16483
  const value = Reflect.get(target, key, target);
@@ -16289,10 +16492,11 @@ function guardSalesActivity(context2, activity) {
16289
16492
  }
16290
16493
 
16291
16494
  // src/update/integration.ts
16495
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "node:async_hooks";
16292
16496
  import { realpathSync } from "node:fs";
16293
16497
 
16294
16498
  // src/update/coordinator.ts
16295
- import { randomUUID as randomUUID3 } from "node:crypto";
16499
+ import { randomUUID as randomUUID4 } from "node:crypto";
16296
16500
 
16297
16501
  // src/update/types.ts
16298
16502
  var PACKAGE_NAME = "@wanji_dsh/dsh-sales";
@@ -16350,6 +16554,7 @@ function resultFacts(result) {
16350
16554
  return { from: result.from, to: result.to, step: result.step, result: clean2(result.result), ...result.restore ? { restore: clean2(result.restore) } : {} };
16351
16555
  }
16352
16556
  var UpdateCoordinator = class {
16557
+ runDiagnostic = diagnosticCallback((work) => diagnosticOperation(work));
16353
16558
  options;
16354
16559
  view;
16355
16560
  record = { schema: 1, phase: "idle", automatic: DEFAULT_AUTOMATIC };
@@ -16392,15 +16597,15 @@ var UpdateCoordinator = class {
16392
16597
  }
16393
16598
  }
16394
16599
  async reconcile() {
16395
- const release = await this.options.state.acquire();
16396
- if (!release) {
16600
+ const release2 = await this.options.state.acquire();
16601
+ if (!release2) {
16397
16602
  this.view.phase = "installing";
16398
16603
  return;
16399
16604
  }
16400
16605
  try {
16401
16606
  await this.reconcileOwned();
16402
16607
  } finally {
16403
- await release();
16608
+ await release2();
16404
16609
  }
16405
16610
  }
16406
16611
  async reconcileOwned() {
@@ -16474,12 +16679,12 @@ var UpdateCoordinator = class {
16474
16679
  if (this.options.companyMarket) {
16475
16680
  this.record = shared;
16476
16681
  if (!shared.resume) return;
16477
- const release = await this.options.state.acquire();
16478
- if (release) try {
16682
+ const release2 = await this.options.state.acquire();
16683
+ if (release2) try {
16479
16684
  this.record = await this.options.state.read();
16480
16685
  await this.resumeSync();
16481
16686
  } finally {
16482
- await release();
16687
+ await release2();
16483
16688
  }
16484
16689
  return;
16485
16690
  }
@@ -16503,7 +16708,7 @@ var UpdateCoordinator = class {
16503
16708
  }
16504
16709
  }
16505
16710
  check() {
16506
- return this.checking ??= (async () => {
16711
+ return this.checking ??= this.runDiagnostic(async () => {
16507
16712
  await this.initialize();
16508
16713
  if (this.disposed || this.invalid || this.job) return;
16509
16714
  if (this.options.companyMarket) {
@@ -16512,7 +16717,8 @@ var UpdateCoordinator = class {
16512
16717
  const version = await companyInstalledVersion(this.options.manager());
16513
16718
  this.view.installedVersion = version;
16514
16719
  this.view.phase = !version ? "migration-required" : version === this.options.version ? "idle" : "restart-required";
16515
- } catch {
16720
+ } catch (error) {
16721
+ diagnostic("install.market-status", "failed", {}, error);
16516
16722
  this.view.installedVersion = void 0;
16517
16723
  this.view.phase = "failed";
16518
16724
  }
@@ -16530,6 +16736,7 @@ var UpdateCoordinator = class {
16530
16736
  }
16531
16737
  const cap = await probeUpdateCapability(this.options.manager());
16532
16738
  if (cap.status !== "ready") {
16739
+ diagnostic("install.update-check", "unavailable", {}, { code: cap.reason });
16533
16740
  this.view.phase = cap.status;
16534
16741
  this.view.error = cap.reason;
16535
16742
  return;
@@ -16545,20 +16752,25 @@ var UpdateCoordinator = class {
16545
16752
  const list3 = await cap.manager.listVersions(PACKAGE_NAME, { registry: REGISTRY }, AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(3e4)]));
16546
16753
  if (this.disposed) return;
16547
16754
  if (list3.status !== "listed") throw Error(list3.problem === "network" ? "UPDATE_NETWORK" : "UPDATE_VERSION_QUERY_FAILED");
16548
- this.view.candidate = selectCandidate(list3, this.options.version);
16549
- this.view.phase = this.view.candidate ? "available" : "idle";
16755
+ const candidate = selectCandidate(list3, this.options.version);
16756
+ this.view.candidate = candidate;
16757
+ if (candidate && candidate.version === this.record.failedTarget) {
16758
+ this.view.phase = "failed";
16759
+ this.view.error = this.record.result?.result.error?.code ?? "UPDATE_FAILED";
16760
+ } else this.view.phase = candidate ? "available" : "idle";
16550
16761
  this.view.checkedAt = Date.now();
16551
16762
  this.record.checkedAt = this.view.checkedAt;
16552
16763
  this.nextCheck = Date.now() + CHECK_INTERVAL_MS;
16553
16764
  this.failures = 0;
16554
16765
  } catch (error) {
16555
16766
  if (!this.disposed) {
16767
+ diagnostic("install.update-check", "failed", {}, error);
16556
16768
  this.view.phase = "failed";
16557
16769
  this.view.error = code(error);
16558
16770
  this.nextCheck = Date.now() + CHECK_RETRY_MS[Math.min(this.failures++, CHECK_RETRY_MS.length - 1)];
16559
16771
  }
16560
16772
  }
16561
- })().finally(() => {
16773
+ }).finally(() => {
16562
16774
  this.checking = void 0;
16563
16775
  });
16564
16776
  }
@@ -16566,15 +16778,15 @@ var UpdateCoordinator = class {
16566
16778
  if (this.options.companyMarket) throw Error("UPDATE_MANAGED_BY_COMPANY");
16567
16779
  await this.initialize();
16568
16780
  if (this.invalid || this.job || this.disposed) throw Error("UPDATE_BUSY");
16569
- const release = await this.options.state.acquire();
16570
- if (!release) throw Error("UPDATE_BUSY");
16781
+ const release2 = await this.options.state.acquire();
16782
+ if (!release2) throw Error("UPDATE_BUSY");
16571
16783
  try {
16572
16784
  this.record = await this.options.state.read();
16573
16785
  this.record.automatic = enabled;
16574
16786
  await this.options.state.write(this.record);
16575
16787
  this.view.automatic = enabled;
16576
16788
  } finally {
16577
- await release();
16789
+ await release2();
16578
16790
  }
16579
16791
  }
16580
16792
  async requestInstall(manual = true) {
@@ -16587,7 +16799,7 @@ var UpdateCoordinator = class {
16587
16799
  const candidate = this.view.candidate;
16588
16800
  if (!candidate || ["restart-required", "recovery-required", "installing"].includes(this.view.phase)) return;
16589
16801
  if (!manual && (!this.view.automatic || !candidate.automatic || candidate.version === this.record.failedTarget || !this.options.clients.idle())) return;
16590
- this.job = this.install(candidate.version, candidate.registry, manual).catch((error) => {
16802
+ this.job = this.runDiagnostic(() => this.install(candidate.version, candidate.registry, manual)).catch((error) => {
16591
16803
  this.view.phase = "failed";
16592
16804
  this.view.error = code(error);
16593
16805
  }).finally(() => {
@@ -16595,14 +16807,15 @@ var UpdateCoordinator = class {
16595
16807
  });
16596
16808
  }
16597
16809
  async install(version, registry, manual) {
16598
- const release = await this.options.state.acquire();
16599
- if (!release) {
16810
+ const release2 = await this.options.state.acquire();
16811
+ if (!release2) {
16600
16812
  this.view.blocked = "UPDATE_BUSY";
16601
16813
  return;
16602
16814
  }
16603
- const requestId = randomUUID3();
16815
+ const requestId = randomUUID4();
16604
16816
  let terminal = "waiting-idle";
16605
16817
  let releaseActivity, resume, handed = false, recorded = false;
16818
+ diagnostic("install.update", "started");
16606
16819
  const preparation = AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(3e4)]);
16607
16820
  try {
16608
16821
  this.record = await this.options.state.read();
@@ -16642,12 +16855,14 @@ var UpdateCoordinator = class {
16642
16855
  if (result.from !== this.record.from || result.to !== version) throw Error("UPDATE_STATE_CHANGED");
16643
16856
  this.record.result = result;
16644
16857
  const failed = ["failed", "cancelled", "overridden"].includes(result.result.application);
16858
+ diagnostic("install.update.handoff", failed ? "failed" : "ok", {}, result.result.error);
16645
16859
  this.record.phase = failed ? result.restore && ["failed", "cancelled"].includes(result.restore.application) ? "recovery-required" : "failed" : "verifying";
16646
16860
  if (failed) this.record.failedTarget = version;
16647
16861
  terminal = this.record.phase;
16648
16862
  this.view.error = failed ? result.result.error?.code ?? "UPDATE_FAILED" : void 0;
16649
16863
  await this.options.state.write(this.record);
16650
16864
  } catch (error) {
16865
+ diagnostic("install.update", "failed", {}, error);
16651
16866
  terminal = handed ? "recovery-required" : "waiting-idle";
16652
16867
  this.view.error = code(error);
16653
16868
  if (recorded) {
@@ -16670,7 +16885,7 @@ var UpdateCoordinator = class {
16670
16885
  terminal = "failed";
16671
16886
  this.view.error = code(error);
16672
16887
  }
16673
- await release();
16888
+ await release2();
16674
16889
  this.view.phase = terminal;
16675
16890
  if (!this.disposed && handed && this.record.phase === "verifying") await this.reconcile();
16676
16891
  }
@@ -16684,9 +16899,9 @@ var UpdateCoordinator = class {
16684
16899
  };
16685
16900
 
16686
16901
  // src/update/state.ts
16687
- import { mkdir, open, readFile, rename, unlink, writeFile } from "node:fs/promises";
16688
- import { join } from "node:path";
16689
- import { createHash, randomUUID as randomUUID4 } from "node:crypto";
16902
+ import { mkdir as mkdir2, open, readFile, rename, unlink as unlink2, writeFile } from "node:fs/promises";
16903
+ import { join as join2 } from "node:path";
16904
+ import { createHash, randomUUID as randomUUID5 } from "node:crypto";
16690
16905
  var phases = /* @__PURE__ */ new Set(["idle", "checking", "available", "waiting-idle", "preparing", "installing", "verifying", "restart-required", "updated", "failed", "recovery-required", "unsupported", "migration-required"]);
16691
16906
  var absent = (e) => e.code === "ENOENT";
16692
16907
  var alive = (pid) => {
@@ -16702,12 +16917,12 @@ var UpdateState = class {
16702
16917
  filename;
16703
16918
  lockfile;
16704
16919
  constructor(storageDir, profile3) {
16705
- this.directory = join(storageDir, "updates", createHash("sha256").update(profile3).digest("hex").slice(0, 24));
16706
- this.filename = join(this.directory, "state.json");
16707
- this.lockfile = join(this.directory, "install.lock");
16920
+ this.directory = join2(storageDir, "updates", createHash("sha256").update(profile3).digest("hex").slice(0, 24));
16921
+ this.filename = join2(this.directory, "state.json");
16922
+ this.lockfile = join2(this.directory, "install.lock");
16708
16923
  }
16709
16924
  async directoryReady() {
16710
- await mkdir(this.directory, { recursive: true, mode: 448 });
16925
+ await mkdir2(this.directory, { recursive: true, mode: 448 });
16711
16926
  }
16712
16927
  async read() {
16713
16928
  let raw;
@@ -16729,12 +16944,12 @@ var UpdateState = class {
16729
16944
  }
16730
16945
  async write(value) {
16731
16946
  await this.directoryReady();
16732
- const temp = this.filename + "." + randomUUID4() + ".tmp";
16947
+ const temp = this.filename + "." + randomUUID5() + ".tmp";
16733
16948
  try {
16734
16949
  await writeFile(temp, JSON.stringify(value), { mode: 384, flag: "wx" });
16735
16950
  await rename(temp, this.filename);
16736
16951
  } finally {
16737
- await unlink(temp).catch((e) => {
16952
+ await unlink2(temp).catch((e) => {
16738
16953
  if (!absent(e)) throw e;
16739
16954
  });
16740
16955
  }
@@ -16749,7 +16964,7 @@ var UpdateState = class {
16749
16964
  }
16750
16965
  async acquire() {
16751
16966
  await this.directoryReady();
16752
- const id2 = randomUUID4();
16967
+ const id2 = randomUUID5();
16753
16968
  const attempt = async () => {
16754
16969
  try {
16755
16970
  const file = await open(this.lockfile, "wx", 384);
@@ -16772,12 +16987,12 @@ var UpdateState = class {
16772
16987
  }
16773
16988
  try {
16774
16989
  if (await this.held()) return;
16775
- await unlink(this.lockfile).catch((e) => {
16990
+ await unlink2(this.lockfile).catch((e) => {
16776
16991
  if (!absent(e)) throw e;
16777
16992
  });
16778
16993
  } finally {
16779
16994
  await guard.close();
16780
- await unlink(this.lockfile + ".reap");
16995
+ await unlink2(this.lockfile + ".reap");
16781
16996
  }
16782
16997
  if (!await attempt()) return;
16783
16998
  }
@@ -16787,7 +17002,7 @@ var UpdateState = class {
16787
17002
  released = true;
16788
17003
  try {
16789
17004
  const owner = JSON.parse(await readFile(this.lockfile, "utf8"));
16790
- if (owner.id === id2) await unlink(this.lockfile);
17005
+ if (owner.id === id2) await unlink2(this.lockfile);
16791
17006
  } catch (e) {
16792
17007
  if (!absent(e)) throw e;
16793
17008
  }
@@ -16841,9 +17056,6 @@ function registerUpdateRoutes(ctx, coordinator, clients) {
16841
17056
  });
16842
17057
  }
16843
17058
 
16844
- // src/update/version.ts
16845
- var RUNNING_VERSION = true ? "0.11.1" : "0.0.0-dev";
16846
-
16847
17059
  // src/update/integration.ts
16848
17060
  function mountUpdates(ctx, storageDir, activity, sync) {
16849
17061
  const optional = (name2) => {
@@ -16874,10 +17086,12 @@ function mountUpdates(ctx, storageDir, activity, sync) {
16874
17086
  }
16875
17087
  });
16876
17088
  registerUpdateRoutes(ctx, coordinator, clients);
16877
- ctx.effect(() => {
16878
- coordinator.start();
17089
+ ctx.effect(diagnosticCallback(() => {
17090
+ const transaction = optional("hmr")?.executing;
17091
+ if (transaction instanceof AsyncLocalStorage3) transaction.exit(() => coordinator.start());
17092
+ else coordinator.start();
16879
17093
  return () => coordinator.dispose();
16880
- });
17094
+ }));
16881
17095
  return coordinator;
16882
17096
  }
16883
17097
 
@@ -16900,8 +17114,8 @@ var formats = [
16900
17114
  ["mp4", "video", /\bmp4\b/i],
16901
17115
  ["mov", "video", /\bmov\b/i]
16902
17116
  ];
16903
- function mentionedProductEditions(text7) {
16904
- const normalized = text7.normalize("NFKC");
17117
+ function mentionedProductEditions(text6) {
17118
+ const normalized = text6.normalize("NFKC");
16905
17119
  const matches = normalized.matchAll(/门店版|标准版|专业版|企业版|私域商城\s*1\.0|万机助手\s*2\.0/g);
16906
17120
  return [...new Set([...matches].filter((match) => !/(?:不是|不用|不要|别用|别给|排除)\s*$/.test(normalized.slice(0, match.index))).map((match) => match[0].replace(/\s/g, "")))];
16907
17121
  }
@@ -16944,10 +17158,10 @@ function wantsMultipleMaterials(query) {
16944
17158
  return /(?:两|二|2|多|各一)\s*[段份张种套部个].{0,22}(?:视频|录屏|教程|资料|截图|文件|文档)|分别.{0,14}(?:视频|教程|资料|截图|文档)/.test(requestedMaterialText(query));
16945
17159
  }
16946
17160
  function materialTopicQueries(query) {
16947
- const text7 = requestedMaterialText(query);
16948
- if (!wantsMultipleMaterials(text7) || !/(?:拍照)?录入|入库/.test(text7) || !/出库|卖出|买走/.test(text7)) return [];
16949
- const editions = mentionedProductEditions(text7).join(" ");
16950
- const product2 = /万机管家/.test(text7) ? "\u4E07\u673A\u7BA1\u5BB6" : "";
17161
+ const text6 = requestedMaterialText(query);
17162
+ if (!wantsMultipleMaterials(text6) || !/(?:拍照)?录入|入库/.test(text6) || !/出库|卖出|买走/.test(text6)) return [];
17163
+ const editions = mentionedProductEditions(text6).join(" ");
17164
+ const product2 = /万机管家/.test(text6) ? "\u4E07\u673A\u7BA1\u5BB6" : "";
16951
17165
  return ["\u673A\u5668\u5165\u5E93 \u62CD\u7167 \u5F55\u5165", "\u9500\u552E\u51FA\u5E93 \u9500\u552E\u660E\u7EC6"].map((topic) => [product2, editions, topic, "\u89C6\u9891\u6559\u7A0B"].filter(Boolean).join(" "));
16952
17166
  }
16953
17167
 
@@ -16996,14 +17210,14 @@ function parseSavedProgress(raw) {
16996
17210
  }
16997
17211
 
16998
17212
  // src/server/conversation-journal.ts
16999
- import { mkdir as mkdir3, chmod as chmod2, readdir, readFile as readFile3, writeFile as writeFile3, link, rm as rm2 } from "node:fs/promises";
17000
- import { join as join3 } from "node:path";
17001
- import { randomUUID as randomUUID6 } from "node:crypto";
17213
+ import { mkdir as mkdir4, chmod as chmod2, readdir as readdir2, readFile as readFile3, writeFile as writeFile3, link, rm as rm2 } from "node:fs/promises";
17214
+ import { join as join4 } from "node:path";
17215
+ import { randomUUID as randomUUID7 } from "node:crypto";
17002
17216
 
17003
17217
  // src/server/store.ts
17004
- import { createHash as createHash2, randomUUID as randomUUID5 } from "node:crypto";
17005
- import { mkdir as mkdir2, readFile as readFile2, rename as rename2, rm, writeFile as writeFile2, chmod } from "node:fs/promises";
17006
- import { join as join2 } from "node:path";
17218
+ import { createHash as createHash2, randomUUID as randomUUID6 } from "node:crypto";
17219
+ import { mkdir as mkdir3, readFile as readFile2, rename as rename2, rm, writeFile as writeFile2, chmod } from "node:fs/promises";
17220
+ import { join as join3 } from "node:path";
17007
17221
 
17008
17222
  // src/server/contracts.ts
17009
17223
  var ProfileError = class extends Error {
@@ -17035,7 +17249,7 @@ var ProfileStore = class {
17035
17249
  this.directory = directory;
17036
17250
  }
17037
17251
  path(category, key) {
17038
- return join2(this.directory, category, `${digest(key)}.json`);
17252
+ return join3(this.directory, category, `${digest(key)}.json`);
17039
17253
  }
17040
17254
  async read(category, key) {
17041
17255
  try {
@@ -17046,13 +17260,13 @@ var ProfileStore = class {
17046
17260
  }
17047
17261
  }
17048
17262
  async write(category, key, value) {
17049
- await mkdir2(this.directory, { recursive: true, mode: 448 });
17263
+ await mkdir3(this.directory, { recursive: true, mode: 448 });
17050
17264
  await chmod(this.directory, 448);
17051
- const directory = join2(this.directory, category);
17052
- await mkdir2(directory, { recursive: true, mode: 448 });
17265
+ const directory = join3(this.directory, category);
17266
+ await mkdir3(directory, { recursive: true, mode: 448 });
17053
17267
  await chmod(directory, 448);
17054
17268
  const target = this.path(category, key);
17055
- const temp = `${target}.${randomUUID5()}.tmp`;
17269
+ const temp = `${target}.${randomUUID6()}.tmp`;
17056
17270
  try {
17057
17271
  await writeFile2(temp, JSON.stringify(value), { mode: 384, flag: "wx" });
17058
17272
  await rename2(temp, target);
@@ -17062,10 +17276,10 @@ var ProfileStore = class {
17062
17276
  }
17063
17277
  /** Exclusive durable claim precedes external reads, including across Host restarts. */
17064
17278
  async claimConversation(key, value) {
17065
- await mkdir2(this.directory, { recursive: true, mode: 448 });
17279
+ await mkdir3(this.directory, { recursive: true, mode: 448 });
17066
17280
  await chmod(this.directory, 448);
17067
- const directory = join2(this.directory, "conversations");
17068
- await mkdir2(directory, { recursive: true, mode: 448 });
17281
+ const directory = join3(this.directory, "conversations");
17282
+ await mkdir3(directory, { recursive: true, mode: 448 });
17069
17283
  await chmod(directory, 448);
17070
17284
  try {
17071
17285
  await writeFile2(this.path("conversations", key), JSON.stringify(value), { flag: "wx", mode: 384 });
@@ -17085,13 +17299,13 @@ var ProfileStore = class {
17085
17299
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(limit) || limit < 1 || limit > 2e4) throw new ProfileError("INVALID_INPUT", "Invalid evidence window");
17086
17300
  let record3;
17087
17301
  try {
17088
- record3 = object(JSON.parse(await readFile2(join2(this.directory, "evidence", `${ref}.json`), "utf8")), "INVALID_EVIDENCE");
17302
+ record3 = object(JSON.parse(await readFile2(join3(this.directory, "evidence", `${ref}.json`), "utf8")), "INVALID_EVIDENCE");
17089
17303
  } catch {
17090
17304
  throw new ProfileError("EVIDENCE_NOT_FOUND", "Transcript artifact is unavailable");
17091
17305
  }
17092
- const text7 = string(record3.text, "INVALID_EVIDENCE");
17093
- const end = Math.min(text7.length, offset + limit);
17094
- return { callId: string(record3.callId, "INVALID_EVIDENCE"), text: text7.slice(offset, end), offset, nextOffset: Math.max(offset, end), totalChars: text7.length, hasMore: end < text7.length, speakerAttribution: string(record3.speakerAttribution, "INVALID_EVIDENCE"), channelId: typeof record3.channelId === "number" ? record3.channelId : null, startMs: typeof record3.startMs === "number" ? record3.startMs : null, endMs: typeof record3.endMs === "number" ? record3.endMs : null };
17306
+ const text6 = string(record3.text, "INVALID_EVIDENCE");
17307
+ const end = Math.min(text6.length, offset + limit);
17308
+ return { callId: string(record3.callId, "INVALID_EVIDENCE"), text: text6.slice(offset, end), offset, nextOffset: Math.max(offset, end), totalChars: text6.length, hasMore: end < text6.length, speakerAttribution: string(record3.speakerAttribution, "INVALID_EVIDENCE"), channelId: typeof record3.channelId === "number" ? record3.channelId : null, startMs: typeof record3.startMs === "number" ? record3.startMs : null, endMs: typeof record3.endMs === "number" ? record3.endMs : null };
17095
17309
  }
17096
17310
  };
17097
17311
 
@@ -17120,36 +17334,36 @@ var ConversationJournal = class {
17120
17334
  }
17121
17335
  directory(s3) {
17122
17336
  if (!s3 || Object.keys(s3).sort().join(",") !== "conversationId,identity,workspaceId" || [s3.workspaceId, s3.conversationId, s3.identity].some((x) => typeof x !== "string" || !x.trim() || x.length > 1e3)) throw Error("JOURNAL_INVALID");
17123
- return join3(this.root, "dialogue-journals", digest([s3.workspaceId, s3.conversationId]));
17337
+ return join4(this.root, "dialogue-journals", digest([s3.workspaceId, s3.conversationId]));
17124
17338
  }
17125
- async load(scope) {
17126
- const dir = this.directory(scope);
17339
+ async load(scope2) {
17340
+ const dir = this.directory(scope2);
17127
17341
  let names2;
17128
17342
  try {
17129
- names2 = await readdir(dir);
17343
+ names2 = await readdir2(dir);
17130
17344
  } catch (e) {
17131
17345
  if (e.code === "ENOENT") return { revision: 0, document: { messages: [] } };
17132
17346
  throw e;
17133
17347
  }
17134
17348
  const revision = Math.max(0, ...names2.filter((n) => /^\d+\.json$/.test(n)).map((n) => Number(n.slice(0, -5))));
17135
17349
  if (!revision) return { revision: 0, document: { messages: [] } };
17136
- const saved = JSON.parse(await readFile3(join3(dir, revision + ".json"), "utf8"));
17137
- if (saved.identity !== digest(scope.identity)) throw Error("CONVERSATION_IDENTITY_CHANGED");
17350
+ const saved = JSON.parse(await readFile3(join4(dir, revision + ".json"), "utf8"));
17351
+ if (saved.identity !== digest(scope2.identity)) throw Error("CONVERSATION_IDENTITY_CHANGED");
17138
17352
  return { revision, document: validDocument(saved.document) };
17139
17353
  }
17140
- async save(scope, expectedRevision, raw) {
17354
+ async save(scope2, expectedRevision, raw) {
17141
17355
  if (!Number.isSafeInteger(expectedRevision) || expectedRevision < 0) throw Error("JOURNAL_INVALID");
17142
- const document = validDocument(raw), dir = this.directory(scope), current = await this.load(scope);
17356
+ const document = validDocument(raw), dir = this.directory(scope2), current = await this.load(scope2);
17143
17357
  if (current.revision !== expectedRevision) throw Error("JOURNAL_CONFLICT");
17144
- await mkdir3(this.root, { recursive: true, mode: 448 });
17358
+ await mkdir4(this.root, { recursive: true, mode: 448 });
17145
17359
  await chmod2(this.root, 448);
17146
- await mkdir3(dir, { recursive: true, mode: 448 });
17360
+ await mkdir4(dir, { recursive: true, mode: 448 });
17147
17361
  await chmod2(dir, 448);
17148
- const temp = join3(dir, randomUUID6() + ".tmp"), revision = expectedRevision + 1;
17362
+ const temp = join4(dir, randomUUID7() + ".tmp"), revision = expectedRevision + 1;
17149
17363
  try {
17150
- await writeFile3(temp, JSON.stringify({ identity: digest(scope.identity), document }), { flag: "wx", mode: 384 });
17364
+ await writeFile3(temp, JSON.stringify({ identity: digest(scope2.identity), document }), { flag: "wx", mode: 384 });
17151
17365
  try {
17152
- await link(temp, join3(dir, revision + ".json"));
17366
+ await link(temp, join4(dir, revision + ".json"));
17153
17367
  } catch (e) {
17154
17368
  if (e.code === "EEXIST") throw Error("JOURNAL_CONFLICT");
17155
17369
  throw e;
@@ -17164,13 +17378,13 @@ var ConversationJournal = class {
17164
17378
  // src/server/journal-route.ts
17165
17379
  var JOURNAL_ENDPOINT = "wanji-sales-conversation/journal";
17166
17380
  function registerJournalRoute(ctx, storageDir) {
17167
- const journal = new ConversationJournal(storageDir);
17381
+ const journal2 = new ConversationJournal(storageDir);
17168
17382
  const dispose = ctx.connection.fetch.register({ path: "/api/" + JOURNAL_ENDPOINT, methods: ["POST"], requestBody: "buffered", async fetch(request2) {
17169
17383
  let envelope;
17170
17384
  try {
17171
- const text7 = await request2.text();
17172
- if (text7.length > 55e4) throw Error();
17173
- envelope = JSON.parse(text7);
17385
+ const text6 = await request2.text();
17386
+ if (text6.length > 55e4) throw Error();
17387
+ envelope = JSON.parse(text6);
17174
17388
  } catch {
17175
17389
  return Response.json({ error: "bad-request" }, { status: 400 });
17176
17390
  }
@@ -17179,9 +17393,9 @@ function registerJournalRoute(ctx, storageDir) {
17179
17393
  try {
17180
17394
  const p2 = envelope.payload;
17181
17395
  if (!p2 || Object.keys(p2).some((k2) => !["operation", "scope", "expectedRevision", "document"].includes(k2)) || !["load", "save"].includes(p2.operation)) throw Error("JOURNAL_INVALID");
17182
- const scope = p2.scope;
17183
- if (!ctx.workspaceRegistry?.list().some((w2) => w2.id === scope?.workspaceId)) throw Error("WORKSPACE_UNAVAILABLE");
17184
- result = { ok: true, value: p2.operation === "load" ? await journal.load(scope) : await journal.save(scope, p2.expectedRevision, p2.document) };
17396
+ const scope2 = p2.scope;
17397
+ if (!ctx.workspaceRegistry?.list().some((w2) => w2.id === scope2?.workspaceId)) throw Error("WORKSPACE_UNAVAILABLE");
17398
+ result = { ok: true, value: p2.operation === "load" ? await journal2.load(scope2) : await journal2.save(scope2, p2.expectedRevision, p2.document) };
17185
17399
  } catch (e) {
17186
17400
  const code4 = e instanceof Error && /^(?:JOURNAL_|CONVERSATION_IDENTITY_|WORKSPACE_)/.test(e.message) ? e.message : "JOURNAL_UNAVAILABLE";
17187
17401
  result = { ok: false, error: { code: code4, message: "\u5BF9\u8BDD\u5386\u53F2\u6682\u672A\u4FDD\u5B58\u6216\u5DF2\u88AB\u5176\u4ED6\u7A97\u53E3\u66F4\u65B0\uFF0C\u5F53\u524D\u5185\u5BB9\u4FDD\u7559\uFF1B\u8BF7\u91CD\u65B0\u8F7D\u5165\u540E\u6838\u5BF9\u3002", details: {} } };
@@ -17197,11 +17411,11 @@ function registerJournalRoute(ctx, storageDir) {
17197
17411
  var wechatSendingEnabled = false;
17198
17412
 
17199
17413
  // src/wechat/routes.ts
17200
- import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
17201
- import { join as join4 } from "node:path";
17414
+ import { mkdirSync, writeFileSync } from "node:fs";
17415
+ import { join as join5 } from "node:path";
17202
17416
 
17203
17417
  // src/wechat/delivery.ts
17204
- import { randomUUID as randomUUID7 } from "node:crypto";
17418
+ import { randomUUID as randomUUID8 } from "node:crypto";
17205
17419
  var DeliveryCoordinator = class {
17206
17420
  active;
17207
17421
  queue = Promise.resolve();
@@ -17215,7 +17429,7 @@ var DeliveryCoordinator = class {
17215
17429
  }
17216
17430
  async open(workspaceId, contactId, enabled) {
17217
17431
  this.close();
17218
- const controller = new AbortController(), lease = randomUUID7();
17432
+ const controller = new AbortController(), lease = randomUUID8();
17219
17433
  this.active = { workspaceId, contactId, enabled, baseline: "", lease, expires: Date.now() + 12e3, controller };
17220
17434
  const source = await this.deps.read(workspaceId, contactId);
17221
17435
  if (this.active?.lease !== lease) throw Error("WECHAT_DELIVERY_SCOPE");
@@ -17241,10 +17455,10 @@ var DeliveryCoordinator = class {
17241
17455
  this.inFlight.set(pendingKey, (this.inFlight.get(pendingKey) ?? 0) + 1);
17242
17456
  const job = this.queue.catch(() => {
17243
17457
  }).then(async () => {
17244
- const scope = this.active;
17458
+ const scope2 = this.active;
17245
17459
  const check = async () => {
17246
- if (!scope || this.active !== scope || scope.lease !== input.lease || scope.workspaceId !== input.workspaceId || scope.contactId !== input.contactId || scope.expires < Math.max(now, Date.now()) || scope.controller.signal.aborted || input.automatic && !scope.enabled) throw Error("WECHAT_DELIVERY_SCOPE");
17247
- if (input.automatic && scope.baseline === input.messageId) throw Error("WECHAT_DELIVERY_BASELINE");
17460
+ if (!scope2 || this.active !== scope2 || scope2.lease !== input.lease || scope2.workspaceId !== input.workspaceId || scope2.contactId !== input.contactId || scope2.expires < Math.max(now, Date.now()) || scope2.controller.signal.aborted || input.automatic && !scope2.enabled) throw Error("WECHAT_DELIVERY_SCOPE");
17461
+ if (input.automatic && scope2.baseline === input.messageId) throw Error("WECHAT_DELIVERY_BASELINE");
17248
17462
  const source2 = await this.deps.read(input.workspaceId, input.contactId);
17249
17463
  if (source2.version !== input.version || source2.messageId !== input.messageId || !source2.pending || source2.draft !== input.text || !input.text.trim() || input.automatic && source2.kind !== "agent") throw Error("WECHAT_DELIVERY_STALE");
17250
17464
  return source2;
@@ -17257,13 +17471,13 @@ var DeliveryCoordinator = class {
17257
17471
  enteredDesktop = true;
17258
17472
  await this.deps.send({ ...input, source }, async () => {
17259
17473
  await check();
17260
- }, scope.controller.signal);
17474
+ }, scope2.controller.signal);
17261
17475
  await this.deps.settle(key, "awaiting-receipt");
17262
17476
  return { status: "awaiting-receipt" };
17263
17477
  } catch (error) {
17264
17478
  const status = !enteredDesktop || error instanceof Error && "deliveryOutcome" in error && error.deliveryOutcome === "blocked" ? "blocked" : "unknown";
17265
17479
  await this.deps.settle(key, status);
17266
- if (this.active === scope) this.close();
17480
+ if (this.active === scope2) this.close();
17267
17481
  throw error;
17268
17482
  }
17269
17483
  });
@@ -17277,7 +17491,7 @@ var DeliveryCoordinator = class {
17277
17491
  };
17278
17492
 
17279
17493
  // src/wechat/service.ts
17280
- import { randomUUID as randomUUID9 } from "node:crypto";
17494
+ import { randomUUID as randomUUID10 } from "node:crypto";
17281
17495
 
17282
17496
  // src/wechat/repository-client.ts
17283
17497
  import { Worker } from "node:worker_threads";
@@ -17342,7 +17556,7 @@ function isFocusedTextBatch(raw) {
17342
17556
  }
17343
17557
 
17344
17558
  // src/wechat/receiver.ts
17345
- import { randomUUID as randomUUID8 } from "node:crypto";
17559
+ import { randomUUID as randomUUID9 } from "node:crypto";
17346
17560
  import { request as httpRequest } from "node:http";
17347
17561
  import { createGunzip } from "node:zlib";
17348
17562
  var LoopbackReceiver = class {
@@ -17364,7 +17578,7 @@ var LoopbackReceiver = class {
17364
17578
  if (!/^[a-f0-9]{64}$/.test(options.token) || !Number.isInteger(this.pairingPort) || this.pairingPort < 1 || this.pairingPort > 65535) throw Error("WECHAT_PAIRING_INVALID");
17365
17579
  const origin = `http://127.0.0.1:${this.pairingPort}`;
17366
17580
  this.address = origin + "/#wanji-local-sync=" + options.token;
17367
- this.headers = { "Origin": origin, "X-Wanji-Sync": options.token, "X-Wanji-Browser": randomUUID8(), "X-Wanji-Connection": randomUUID8() };
17581
+ this.headers = { "Origin": origin, "X-Wanji-Sync": options.token, "X-Wanji-Browser": randomUUID9(), "X-Wanji-Connection": randomUUID9() };
17368
17582
  }
17369
17583
  async request(port, signal, name2, body) {
17370
17584
  const encoded = body === void 0 ? void 0 : JSON.stringify(body), limit = 65 * 1024 * 1024;
@@ -17521,22 +17735,22 @@ var LoopbackReceiver = class {
17521
17735
 
17522
17736
  // src/wechat/watcher.ts
17523
17737
  import { watch } from "node:fs";
17524
- import { lstat, realpath } from "node:fs/promises";
17525
- import { homedir } from "node:os";
17526
- import { basename, isAbsolute, relative, resolve, dirname } from "node:path";
17738
+ import { lstat as lstat2, realpath } from "node:fs/promises";
17739
+ import { homedir as homedir2 } from "node:os";
17740
+ import { basename, isAbsolute as isAbsolute2, relative, resolve, dirname } from "node:path";
17527
17741
  async function validateRoots(roots) {
17528
17742
  const valid = [];
17529
17743
  for (const root of roots.slice(0, 8)) {
17530
17744
  try {
17531
- if (!isAbsolute(root) || basename(root) !== "db_storage" || relative(homedir(), root).startsWith("..") || await realpath(root) !== resolve(root)) continue;
17745
+ if (!isAbsolute2(root) || basename(root) !== "db_storage" || relative(homedir2(), root).startsWith("..") || await realpath(root) !== resolve(root)) continue;
17532
17746
  let ancestor = root;
17533
17747
  while (true) {
17534
- if ((await lstat(ancestor)).isSymbolicLink()) throw Error();
17748
+ if ((await lstat2(ancestor)).isSymbolicLink()) throw Error();
17535
17749
  const parent = dirname(ancestor);
17536
17750
  if (parent === ancestor) break;
17537
17751
  ancestor = parent;
17538
17752
  }
17539
- if ((await lstat(root)).isDirectory()) valid.push(root);
17753
+ if ((await lstat2(root)).isDirectory()) valid.push(root);
17540
17754
  } catch {
17541
17755
  }
17542
17756
  }
@@ -17604,8 +17818,8 @@ var SourceWatcher = class {
17604
17818
  import { spawn as spawn2 } from "node:child_process";
17605
17819
  import { createServer } from "node:net";
17606
17820
  import { createHash as createHash3, randomBytes, timingSafeEqual } from "node:crypto";
17607
- import { lstat as lstat2, readFile as readFile4, readdir as readdir2, realpath as realpath2 } from "node:fs/promises";
17608
- import { homedir as homedir2, userInfo } from "node:os";
17821
+ import { lstat as lstat3, readFile as readFile4, readdir as readdir3, realpath as realpath2 } from "node:fs/promises";
17822
+ import { homedir as homedir3, userInfo } from "node:os";
17609
17823
  import path from "node:path";
17610
17824
  var pendingLoginMessages = /* @__PURE__ */ new Set([
17611
17825
  "\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",
@@ -17620,16 +17834,16 @@ async function verifyComponent(root, platform = process.platform, arch = process
17620
17834
  if (!path.isAbsolute(root) || await realpath2(root) !== root)
17621
17835
  throw Error("Component root must be canonical");
17622
17836
  for (let p2 = root; ; p2 = path.dirname(p2)) {
17623
- if ((await lstat2(p2)).isSymbolicLink())
17837
+ if ((await lstat3(p2)).isSymbolicLink())
17624
17838
  throw Error("Component links forbidden");
17625
17839
  if (path.dirname(p2) === p2)
17626
17840
  break;
17627
17841
  }
17628
17842
  const dir = path.join(root, `${platform}-${arch}`);
17629
- if (!(await lstat2(dir)).isDirectory() || (await lstat2(dir)).isSymbolicLink())
17843
+ if (!(await lstat3(dir)).isDirectory() || (await lstat3(dir)).isSymbolicLink())
17630
17844
  throw Error("Component directory invalid");
17631
17845
  const manifestPath = path.join(dir, "component.json");
17632
- if (!(await lstat2(manifestPath)).isFile() || (await lstat2(manifestPath)).isSymbolicLink())
17846
+ if (!(await lstat3(manifestPath)).isFile() || (await lstat3(manifestPath)).isSymbolicLink())
17633
17847
  throw Error("Invalid manifest");
17634
17848
  const manifest = JSON.parse(await readFile4(manifestPath, "utf8"));
17635
17849
  if (manifest.platform !== platform || manifest.arch !== arch || typeof manifest.version !== "string" || !/^\d+\.\d+\.\d+(?:[-+][\w.-]+)?$/.test(manifest.version) || !manifest.files || typeof manifest.files !== "object" || Array.isArray(manifest.files))
@@ -17642,10 +17856,10 @@ async function verifyComponent(root, platform = process.platform, arch = process
17642
17856
  throw Error("Invalid component file entry");
17643
17857
  }
17644
17858
  async function walk(base, prefix = "") {
17645
- for (const entry of await readdir2(base)) {
17859
+ for (const entry of await readdir3(base)) {
17646
17860
  const name2 = prefix + entry;
17647
17861
  const file = path.join(base, entry);
17648
- const st2 = await lstat2(file);
17862
+ const st2 = await lstat3(file);
17649
17863
  if (st2.isSymbolicLink())
17650
17864
  throw Error("Component links forbidden");
17651
17865
  if (st2.isDirectory()) {
@@ -17786,7 +18000,7 @@ function createNativeBackend({ componentRoot }) {
17786
18000
  throw Error("Native sync aborted");
17787
18001
  if (process.platform === "darwin") {
17788
18002
  dynamicBridge = manifest.dynamicBridge === true;
17789
- child = spawn2(path.join(dir, names.worker), ["--serve"], { cwd: dir, stdio: ["pipe", "pipe", "ignore"], detached: true, env: { ...process.env, HOME: homedir2() } });
18003
+ child = spawn2(path.join(dir, names.worker), ["--serve"], { cwd: dir, stdio: ["pipe", "pipe", "ignore"], detached: true, env: { ...process.env, HOME: homedir3() } });
17790
18004
  const current = child;
17791
18005
  stream = current.stdin;
17792
18006
  stream.on("error", (e) => {
@@ -18312,19 +18526,27 @@ var WechatSyncService = class {
18312
18526
  }, delay2);
18313
18527
  this.timer.unref();
18314
18528
  }
18315
- async cycle(fullSync, allowStart = false, loginAttempt = 0) {
18529
+ runDiagnostic = diagnosticCallback((run, operationId) => diagnosticOperation(run, operationId));
18530
+ cycle(fullSync, allowStart = false, loginAttempt = 0) {
18531
+ const requestId = randomUUID10();
18532
+ return this.runDiagnostic(() => this.syncCycle(requestId, fullSync, allowStart, loginAttempt), requestId);
18533
+ }
18534
+ async syncCycle(requestId, fullSync, allowStart, loginAttempt) {
18535
+ const operation = fullSync ? "wechat.sync.full" : "wechat.sync.incremental", started = performance.now();
18316
18536
  if (!allowStart && !this.native.isConnected()) {
18317
18537
  if (this.state.capabilities?.dynamicBridge) this.receiver?.suspend();
18318
18538
  this.state.running = false;
18319
18539
  this.state.automatic = false;
18320
18540
  this.state.phase = "paused";
18321
18541
  this.state.message = "WECHAT_RECONNECT_REQUIRED";
18542
+ diagnostic(operation, "unavailable", {}, new Error("WECHAT_RECONNECT_REQUIRED"));
18322
18543
  return;
18323
18544
  }
18324
18545
  let retryLoginIn;
18325
18546
  let retryCapture = false;
18326
18547
  this.initialImport = fullSync;
18327
- const workspace = this.state.workspaceId, requestId = randomUUID9();
18548
+ if (fullSync) diagnostic(operation, "started");
18549
+ const workspace = this.state.workspaceId;
18328
18550
  this.dirty = false;
18329
18551
  this.committedRequest = void 0;
18330
18552
  this.mediaCommittedRequest = void 0;
@@ -18363,6 +18585,7 @@ var WechatSyncService = class {
18363
18585
  this.failures = 0;
18364
18586
  this.interval = result.fast_sync_supported === true && Number.isInteger(result.next_interval_seconds) && result.next_interval_seconds >= 2 && result.next_interval_seconds <= 30 ? result.next_interval_seconds * 1e3 : 3e4;
18365
18587
  await this.watcher.setRoots(result.source_watch_roots ?? []);
18588
+ if (fullSync || !unchanged) diagnostic(operation, "ok", { elapsedMs: Math.round(performance.now() - started), count: Number(result.stats.message_count) || 0 });
18366
18589
  this.progress(100, "complete");
18367
18590
  this.state.phase = this.state.automatic ? "waiting" : "paused";
18368
18591
  this.state.message = "";
@@ -18375,6 +18598,8 @@ var WechatSyncService = class {
18375
18598
  retryCapture = e instanceof WechatCaptureBusyError && this.state.automatic;
18376
18599
  const loginPending = e instanceof WechatLoginPendingError && this.state.phase === "collecting" && (this.state.progress?.percent ?? 0) <= 1;
18377
18600
  if (loginPending && this.state.automatic) retryLoginIn = loginRetryDelays[loginAttempt];
18601
+ const stage = loginPending ? "wechat.sync.login" : retryCapture ? "wechat.sync.capture-busy" : operation;
18602
+ diagnostic(stage, retryLoginIn !== void 0 || retryCapture ? "pending" : "failed", { elapsedMs: Math.round(performance.now() - started) }, e);
18378
18603
  if (retryLoginIn !== void 0) {
18379
18604
  this.state.phase = "awaiting-login";
18380
18605
  this.state.message = "";
@@ -18590,9 +18815,9 @@ function registerWechatRoutes(ctx, options, injected, desktop) {
18590
18815
  if (!desktop?.available() || !w2) throw Error("WECHAT_CUA_UNAVAILABLE");
18591
18816
  value = await desktop.sender.check(ws2, w2.path, request2.signal, source);
18592
18817
  try {
18593
- const directory = join4(options.storageDir, "wechat");
18818
+ const directory = join5(options.storageDir, "wechat");
18594
18819
  mkdirSync(directory, { recursive: true, mode: 448 });
18595
- writeFileSync(join4(directory, "delivery-check.json"), JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), result: value }), { mode: 384 });
18820
+ writeFileSync(join5(directory, "delivery-check.json"), JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), result: value }), { mode: 384 });
18596
18821
  } catch {
18597
18822
  }
18598
18823
  break;
@@ -18644,15 +18869,13 @@ function registerWechatRoutes(ctx, options, injected, desktop) {
18644
18869
  }
18645
18870
  result = { ok: true, value };
18646
18871
  } catch (e) {
18647
- if (envelope.payload?.operation === "delivery-check" && !(e instanceof Error && e.message === "WECHAT_SENDING_DISABLED")) {
18648
- try {
18649
- const directory = join4(options.storageDir, "wechat");
18650
- mkdirSync(directory, { recursive: true, mode: 448 });
18651
- const first = (e instanceof Error ? e.message : String(e)).split("\n")[0].replace(/https?:\/\/\S+/g, "[url]").replace(/(?:token|secret|api.?key|password)\s*[:=]\s*\S+/gi, "[redacted]").slice(0, 180);
18652
- appendFileSync(join4(directory, "delivery-diagnostics.jsonl"), JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), operation: "delivery-check", name: e instanceof Error ? e.name : "Error", message: first }) + "\n", { mode: 384 });
18653
- } catch {
18654
- }
18655
- }
18872
+ const operation = envelope.payload?.operation;
18873
+ diagnostic(
18874
+ typeof operation === "string" && Object.hasOwn(fields2, operation) ? "wechat.rpc." + operation : "wechat.rpc.invalid",
18875
+ request2.signal.aborted ? "cancelled" : "failed",
18876
+ {},
18877
+ e
18878
+ );
18656
18879
  const code4 = e instanceof Error && /^(?:WECHAT_|WORKSPACE_|CONVERSATION_)/.test(e.message) ? e.message : envelope.payload?.operation?.startsWith("delivery-") ? "WECHAT_DELIVERY_CUA_FAILED" : "WECHAT_UNAVAILABLE";
18657
18880
  result = { ok: false, error: { code: code4, message: code4 === "WECHAT_SENDING_DISABLED" ? "\u5FAE\u4FE1\u53D1\u9001\u529F\u80FD\u5DF2\u6682\u505C\uFF0C\u8BF7\u590D\u5236\u56DE\u590D\u540E\u81EA\u884C\u53D1\u9001\u3002" : code4 === "WECHAT_CUA_UNAVAILABLE" ? "\u8BF7\u5148\u66F4\u65B0\u4E07\u673A\u5927\u8111\u5E76\u542F\u7528\u5B98\u65B9 Computer Use\u3002" : code4.startsWith("WECHAT_DELIVERY_") ? "\u5FAE\u4FE1\u53D1\u9001\u5DF2\u505C\u6B62\u3002\u8BF7\u68C0\u67E5\u5F53\u524D\u8054\u7CFB\u4EBA\u3001\u8349\u7A3F\u548C\u5FAE\u4FE1\u754C\u9762\uFF1B\u7ED3\u679C\u4E0D\u660E\u786E\u65F6\u8BF7\u5148\u6838\u5BF9\u5FAE\u4FE1\uFF0C\u7CFB\u7EDF\u4E0D\u4F1A\u81EA\u52A8\u91CD\u53D1\u3002" : code4 === "WECHAT_BUSY" ? "\u5FAE\u4FE1\u540C\u6B65\u6B63\u5728\u8FDB\u884C\uFF0C\u8BF7\u7B49\u5F85\u5F53\u524D\u4EFB\u52A1\u5B8C\u6210\u3002" : code4 === "WECHAT_COMPONENT_UNAVAILABLE" ? "\u672C\u673A\u5FAE\u4FE1\u91C7\u96C6\u7EC4\u4EF6\u672A\u5C31\u7EEA\uFF0C\u8BF7\u68C0\u67E5\u5E73\u53F0\u7EC4\u4EF6\u3002" : "\u5FAE\u4FE1\u540C\u6B65\u8BF7\u6C42\u672A\u5B8C\u6210\uFF0C\u8BF7\u68C0\u67E5\u5F53\u524D\u5DE5\u4F5C\u533A\u3001\u7EC4\u4EF6\u53CA\u8D26\u53F7\u72B6\u6001\u3002", details: {} } };
18658
18881
  }
@@ -18683,7 +18906,7 @@ function registerBundledSalesSkill(registry) {
18683
18906
  }
18684
18907
 
18685
18908
  // src/host.ts
18686
- import { dirname as dirname4, isAbsolute as isAbsolute5 } from "node:path";
18909
+ import { dirname as dirname4, isAbsolute as isAbsolute7 } from "node:path";
18687
18910
  import { fileURLToPath as fileURLToPath4 } from "node:url";
18688
18911
 
18689
18912
  // ../../../../../../Users/imac/Code/万机/wanji_dazi_dsh/node_modules/@deepseek-ai/cosmokit/lib/index.js
@@ -19553,8 +19776,8 @@ defineMethod("transform", [
19553
19776
  ], ({ inner }, isInner) => inner.toString(isInner));
19554
19777
 
19555
19778
  // src/agent-knowledge.ts
19556
- import { randomUUID as randomUUID12 } from "node:crypto";
19557
- import { join as join8 } from "node:path";
19779
+ import { randomUUID as randomUUID13 } from "node:crypto";
19780
+ import { join as join9 } from "node:path";
19558
19781
  import { readFile as readFile7 } from "node:fs/promises";
19559
19782
 
19560
19783
  // src/knowledge-judgments.ts
@@ -19652,12 +19875,15 @@ var KnowledgeTurns = class {
19652
19875
 
19653
19876
  // src/knowledge-privacy.ts
19654
19877
  import { createHmac } from "node:crypto";
19655
- import { open as open2, lstat as lstat3 } from "node:fs/promises";
19878
+ import { open as open2, lstat as lstat4 } from "node:fs/promises";
19656
19879
  import { constants } from "node:fs";
19657
- import { dirname as dirname3, isAbsolute as isAbsolute2 } from "node:path";
19658
- async function readEvaluationPrivacy(path3) {
19659
- if (typeof path3 !== "string" || !isAbsolute2(path3)) throw Error("redaction-unavailable");
19660
- const parent = await lstat3(dirname3(path3));
19880
+ import { dirname as dirname3, isAbsolute as isAbsolute3 } from "node:path";
19881
+ async function readEvaluationPrivacy(path3, environment) {
19882
+ if (environment === "production" && process.env.WANJI_SALES_LANGFUSE_REDACTION_KEY !== void 0) {
19883
+ return createEvaluationPrivacy(process.env.WANJI_SALES_LANGFUSE_REDACTION_KEY);
19884
+ }
19885
+ if (typeof path3 !== "string" || !isAbsolute3(path3)) throw Error("redaction-unavailable");
19886
+ const parent = await lstat4(dirname3(path3));
19661
19887
  if (!parent.isDirectory() || (parent.mode & 63) !== 0 || parent.uid !== process.getuid?.()) throw Error("redaction-unavailable");
19662
19888
  const file = await open2(path3, constants.O_RDONLY | constants.O_NOFOLLOW);
19663
19889
  let key;
@@ -19668,11 +19894,16 @@ async function readEvaluationPrivacy(path3) {
19668
19894
  } finally {
19669
19895
  await file.close();
19670
19896
  }
19671
- if (key.length < 32) throw Error("redaction-unavailable");
19897
+ return createEvaluationPrivacy(key);
19898
+ }
19899
+ function createEvaluationPrivacy(secret) {
19900
+ const key = secret.trim();
19901
+ if (key.length < 32 || Buffer.byteLength(key) > 4096) throw Error("redaction-unavailable");
19672
19902
  const mask = (s3) => "[\u79C1\u5BC6:" + createHmac("sha256", key).update(s3).digest("hex").slice(0, 12) + "]";
19673
19903
  const clean2 = (v2) => typeof v2 === "string" ? v2.replace(/\b1[3-9]\d{9}\b/g, mask).replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, mask) : Array.isArray(v2) ? v2.map(clean2) : v2 && typeof v2 === "object" ? Object.fromEntries(Object.entries(v2).map(([k2, x]) => [k2, /^(api[-_]?key|secret|password|authorization|token)$/i.test(k2) ? "[\u5DF2\u9690\u85CF]" : clean2(x)])) : v2;
19674
19904
  return clean2;
19675
19905
  }
19906
+ var maskObservationText = (value, limit) => value.replace(/https?:\/\/[^\s<>",。!?;)]+/giu, "[\u94FE\u63A5]").replace(/\b(?:sk|pk|ghp|glpat)-[A-Za-z0-9_.-]{10,}/gu, "[\u51ED\u636E]").replace(/\bBearer\s+[A-Za-z0-9_.-]+/giu, "[\u51ED\u636E]").replace(/(?:\b(?:api[-_ ]?key|secret|password|authorization|token)\b|密码|密钥)["']?\s*[:=:]\s*["']?[^\s,"',。;]+/giu, "[\u51ED\u636E]").replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/giu, "[\u90AE\u7BB1]").replace(/\+?\d[\d -]{8,}\d/gu, "[\u53F7\u7801]").trim().slice(0, limit);
19676
19907
 
19677
19908
  // src/langfuse-config.ts
19678
19909
  import { execFile } from "node:child_process";
@@ -19682,11 +19913,30 @@ import { promisify, isDeepStrictEqual } from "node:util";
19682
19913
  var relevanceFormat = "scoreExplanation\u5FC5\u987B\u662FJSON\u5B57\u7B26\u4E32\u3002\u5916\u5C42\u8FD4\u56DE\u683C\u5F0F\u793A\u4F8B\uFF08\u793A\u4F8B\u6570\u636E\u4E0D\u662F\u5F85\u8BC4\u8BC1\u636E\uFF09\uFF1A" + JSON.stringify({ score: 0.5, scoreExplanation: JSON.stringify({ chunks: [{ id: "example:chunk", score: 0.5, quote: "\u793A\u4F8B\u539F\u6587" }] }) }) + "\u3002\u5BF9\u5B9E\u9645\u8F93\u5165\u66FF\u6362\u5168\u90E8\u793A\u4F8BID\u3001\u5206\u6570\u3001\u5F15\u6587\uFF0C\u8986\u76D6\u6240\u6709\u771F\u5B9E\u7247\u6BB5\u3002";
19683
19914
 
19684
19915
  // src/langfuse-config.ts
19685
- import { readFile as readFile5, writeFile as writeFile4, rename as rename3, unlink as unlink2 } from "node:fs/promises";
19686
- import { createHash as createHash4, randomUUID as randomUUID10 } from "node:crypto";
19687
- import { homedir as homedir3 } from "node:os";
19688
- import { join as join5 } from "node:path";
19689
- var defaultConfigFile = join5(homedir3(), ".config", "wanji-sales", "langfuse.json");
19916
+ import { readFile as readFile5, writeFile as writeFile4, rename as rename3, unlink as unlink3 } from "node:fs/promises";
19917
+ import { createHash as createHash4, randomUUID as randomUUID11 } from "node:crypto";
19918
+ import { homedir as homedir4 } from "node:os";
19919
+ import { join as join6 } from "node:path";
19920
+
19921
+ // src/production-endpoints.ts
19922
+ var PRODUCTION_WEKNORA_BASE_URL = "https://wanjidazi.com/sales-kb/api/v1";
19923
+ function weknoraEnvironment(value) {
19924
+ if (!value || typeof value !== "object" || !("baseUrl" in value) || typeof value.baseUrl !== "string") return;
19925
+ const url = URL.parse(value.baseUrl.trim());
19926
+ if (!url) return;
19927
+ if (url.hostname === "test-wjdz.wanjisaas.com") return "test";
19928
+ if (["wanjidazi.com", "www.wanjidazi.com"].includes(url.hostname) && /^\/sales-kb(?:\/|$)/.test(url.pathname)) return "production";
19929
+ }
19930
+ var PRODUCTION_LANGFUSE_BASE_URL = "https://wanjidazi.com/langfuse";
19931
+ var PRODUCTION_LANGFUSE_PROJECT_ID = "wanji-sales-test";
19932
+ var PRODUCTION_LANGFUSE_CREDENTIALS_REF = "wanji-langfuse-api-production";
19933
+ function isProductionLangfuse(target) {
19934
+ const host = new URL(target.baseUrl).hostname;
19935
+ return ["wanjidazi.com", "www.wanjidazi.com"].includes(host);
19936
+ }
19937
+
19938
+ // src/langfuse-config.ts
19939
+ var defaultConfigFile = join6(homedir4(), ".config", "wanji-sales", "langfuse.json");
19690
19940
  function resolveTarget(name2, value) {
19691
19941
  const v2 = value;
19692
19942
  if (!/^[a-zA-Z0-9_-]{1,40}$/.test(name2) || !v2 || typeof v2.baseUrl !== "string" || typeof v2.projectId !== "string" || !/^[a-zA-Z0-9_-]{1,160}$/.test(v2.projectId) || typeof v2.credentialsRef !== "string" || !/^wanji-langfuse-api-[a-zA-Z0-9_-]{1,80}$/.test(v2.credentialsRef)) throw new Error("invalid-target");
@@ -19699,14 +19949,28 @@ function resolveTarget(name2, value) {
19699
19949
  function destinationId(target) {
19700
19950
  return createHash4("sha256").update(JSON.stringify([target.baseUrl, target.projectId, target.credentialsRef])).digest("hex").slice(0, 24);
19701
19951
  }
19702
- async function readTarget(path3 = defaultConfigFile) {
19952
+ function requireTargetEnvironment(target, environment) {
19953
+ if (environment === "production") {
19954
+ if (target.baseUrl !== PRODUCTION_LANGFUSE_BASE_URL || target.projectId !== PRODUCTION_LANGFUSE_PROJECT_ID || target.credentialsRef !== PRODUCTION_LANGFUSE_CREDENTIALS_REF) throw new Error("production-target-mismatch");
19955
+ } else if (isProductionLangfuse(target)) {
19956
+ throw new Error("test-target-required");
19957
+ }
19958
+ return target;
19959
+ }
19960
+ async function readTarget(path3 = defaultConfigFile, environment = "test") {
19703
19961
  const config = JSON.parse(await readFile5(path3, "utf8"));
19704
19962
  if (config.enabled === false) return void 0;
19705
19963
  if (config.enabled !== true || typeof config.activeTarget !== "string") throw new Error("invalid-config");
19706
- return resolveTarget(config.activeTarget, config.targets?.[config.activeTarget]);
19964
+ return requireTargetEnvironment(resolveTarget(config.activeTarget, config.targets?.[config.activeTarget]), environment);
19707
19965
  }
19708
19966
  var keychainCredentials = async (target) => {
19709
19967
  try {
19968
+ if (target.credentialsRef === PRODUCTION_LANGFUSE_CREDENTIALS_REF && target.baseUrl === PRODUCTION_LANGFUSE_BASE_URL) {
19969
+ const publicKey = process.env.WANJI_SALES_LANGFUSE_PUBLIC_KEY?.trim();
19970
+ const secretKey = process.env.WANJI_SALES_LANGFUSE_SECRET_KEY?.trim();
19971
+ if (publicKey && secretKey) return { publicKey, secretKey };
19972
+ if (publicKey || secretKey) throw new Error();
19973
+ }
19710
19974
  const { stdout } = await promisify(execFile)("/usr/bin/security", ["find-generic-password", "-a", "Harness", "-s", target.credentialsRef, "-w"], { timeout: 5e3, maxBuffer: 16384 });
19711
19975
  const v2 = JSON.parse(stdout);
19712
19976
  if (typeof v2.publicKey !== "string" || !v2.publicKey || typeof v2.secretKey !== "string" || !v2.secretKey) throw new Error();
@@ -19719,9 +19983,18 @@ function authorization(keys) {
19719
19983
  return "Basic " + Buffer.from(`${keys.publicKey}:${keys.secretKey}`).toString("base64");
19720
19984
  }
19721
19985
  async function api(target, keys, path3, body, request2 = fetch) {
19986
+ const headers = { Authorization: authorization(keys) };
19987
+ if (body !== void 0) headers["Content-Type"] = "application/json";
19988
+ if (path3 === "/api/public/otel/v1/traces") {
19989
+ headers["x-langfuse-ingestion-version"] = "4";
19990
+ headers["x-langfuse-sdk-name"] = "python";
19991
+ headers["x-langfuse-sdk-version"] = "4.0.0";
19992
+ }
19722
19993
  let response;
19994
+ const signal = AbortSignal.timeout(1e4);
19995
+ const stage = path3 === "/api/public/health" ? "health" : path3 === "/api/public/projects" ? "projects" : path3 === "/api/public/otel/v1/traces" ? "trace-upload" : "api";
19723
19996
  try {
19724
- response = await request2(target.baseUrl + path3, { method: body === void 0 ? "GET" : "POST", redirect: "error", signal: AbortSignal.timeout(1e4), headers: { Authorization: authorization(keys), ...body === void 0 ? {} : { "Content-Type": "application/json" } }, ...body === void 0 ? {} : { body: JSON.stringify(body) } });
19997
+ response = await diagnosticHttp("langfuse.http." + stage, () => request2(target.baseUrl + path3, { method: body === void 0 ? "GET" : "POST", redirect: "error", signal, headers, ...body === void 0 ? {} : { body: JSON.stringify(body) } }), signal);
19725
19998
  } catch {
19726
19999
  throw new Error("connection-failed");
19727
20000
  }
@@ -19734,7 +20007,10 @@ async function api(target, keys, path3, body, request2 = fetch) {
19734
20007
  return value;
19735
20008
  }
19736
20009
  async function preflight(target, secrets = keychainCredentials, request2 = fetch) {
19737
- const keys = await secrets(target);
20010
+ const keys = await secrets(target).catch((error) => {
20011
+ diagnostic("langfuse.credentials", "failed", {}, error);
20012
+ throw error;
20013
+ });
19738
20014
  const health = await api(target, keys, "/api/public/health", void 0, request2);
19739
20015
  if (typeof health.version !== "string" || Number(health.version.split(".")[0]) !== 4) throw new Error("unsupported-server-version");
19740
20016
  const projects = await api(target, keys, "/api/public/projects", void 0, request2);
@@ -20253,8 +20529,8 @@ var ScoreDataType = {
20253
20529
  var toJson = (value, replacer, space) => {
20254
20530
  return JSON.stringify(value, replacer, space);
20255
20531
  };
20256
- function fromJson(text7, reviver) {
20257
- return JSON.parse(text7, reviver);
20532
+ function fromJson(text6, reviver) {
20533
+ return JSON.parse(text6, reviver);
20258
20534
  }
20259
20535
  var LangfuseAPIError = class _LangfuseAPIError extends Error {
20260
20536
  statusCode;
@@ -21052,10 +21328,10 @@ async function getResponseBody(response, responseType) {
21052
21328
  case "text":
21053
21329
  return await response.text();
21054
21330
  }
21055
- const text7 = await response.text();
21056
- if (text7.length > 0) {
21331
+ const text6 = await response.text();
21332
+ if (text6.length > 0) {
21057
21333
  try {
21058
- let responseBody = fromJson(text7);
21334
+ let responseBody = fromJson(text6);
21059
21335
  return responseBody;
21060
21336
  } catch (err) {
21061
21337
  return {
@@ -21063,7 +21339,7 @@ async function getResponseBody(response, responseType) {
21063
21339
  error: {
21064
21340
  reason: "non-json",
21065
21341
  statusCode: response.status,
21066
- rawBody: text7
21342
+ rawBody: text6
21067
21343
  }
21068
21344
  };
21069
21345
  }
@@ -21085,8 +21361,8 @@ async function getErrorResponseBody(response) {
21085
21361
  case "application/problem+json":
21086
21362
  case "application/vnd.api+json":
21087
21363
  case "text/json":
21088
- const text7 = await response.text();
21089
- return text7.length > 0 ? fromJson(text7) : void 0;
21364
+ const text6 = await response.text();
21365
+ return text6.length > 0 ? fromJson(text6) : void 0;
21090
21366
  default:
21091
21367
  if (contentType.startsWith("application/vnd.") && contentType.endsWith("+json")) {
21092
21368
  const text22 = await response.text();
@@ -21516,10 +21792,10 @@ var HttpResponsePromise = class _HttpResponsePromise extends Promise {
21516
21792
  };
21517
21793
  var url_exports = {};
21518
21794
  __export2(url_exports, {
21519
- join: () => join6,
21795
+ join: () => join7,
21520
21796
  toQueryString: () => toQueryString
21521
21797
  });
21522
- function join6(base, ...segments) {
21798
+ function join7(base, ...segments) {
21523
21799
  if (!base) {
21524
21800
  return "";
21525
21801
  }
@@ -36543,9 +36819,9 @@ function isGenAISpan(span) {
36543
36819
  );
36544
36820
  }
36545
36821
  function isKnownLLMInstrumentor(span) {
36546
- const scope = span.instrumentationScope.name;
36822
+ const scope2 = span.instrumentationScope.name;
36547
36823
  return KNOWN_LLM_INSTRUMENTATION_SCOPE_PREFIXES.some(
36548
- (prefix) => scope === prefix || !EXACT_LLM_INSTRUMENTATION_SCOPES.has(prefix) && scope.startsWith(`${prefix}.`)
36824
+ (prefix) => scope2 === prefix || !EXACT_LLM_INSTRUMENTATION_SCOPES.has(prefix) && scope2.startsWith(`${prefix}.`)
36549
36825
  );
36550
36826
  }
36551
36827
  function isDefaultExportSpan(span) {
@@ -36965,8 +37241,9 @@ async function exportObservation(event, keys, extra2) {
36965
37241
  void api(event.target, keys, "/api/public/otel/v1/traces", { resourceSpans: spans.map(serialize) }).then(() => {
36966
37242
  acknowledged = true;
36967
37243
  callback({ code: import_core10.ExportResultCode.SUCCESS });
36968
- }, () => {
37244
+ }, (error) => {
36969
37245
  failed = true;
37246
+ diagnostic("langfuse.trace-receipt", "failed", {}, error);
36970
37247
  callback({ code: import_core10.ExportResultCode.FAILED });
36971
37248
  });
36972
37249
  },
@@ -36974,7 +37251,8 @@ async function exportObservation(event, keys, extra2) {
36974
37251
  }
36975
37252
  };
36976
37253
  const ids = identities(event);
36977
- 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 });
37254
+ const environment = event.target.baseUrl === PRODUCTION_LANGFUSE_BASE_URL ? "production" : event.agent || event.question || event.knowledgeCall ? "knowledge-agent" : "knowledge-test";
37255
+ const processor = new LangfuseSpanProcessor({ exporter, baseUrl: event.target.baseUrl, publicKey: keys.publicKey, secretKey: keys.secretKey, environment, mediaUploadEnabled: false, shouldExportSpan: () => true, flushAt: 1e3, flushInterval: 3600 });
36978
37256
  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 } });
36979
37257
  try {
36980
37258
  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;
@@ -37053,9 +37331,9 @@ async function deliverKnowledgeJudgment(event, request2) {
37053
37331
  }
37054
37332
 
37055
37333
  // src/langfuse-outbox.ts
37056
- import { mkdir as mkdir4, readdir as readdir3, readFile as readFile6, rename as rename4, stat, unlink as unlink3, writeFile as writeFile5 } from "node:fs/promises";
37057
- import { join as join7 } from "node:path";
37058
- import { randomUUID as randomUUID11 } from "node:crypto";
37334
+ import { mkdir as mkdir5, readdir as readdir4, readFile as readFile6, rename as rename4, stat, unlink as unlink4, writeFile as writeFile5 } from "node:fs/promises";
37335
+ import { join as join8 } from "node:path";
37336
+ import { randomUUID as randomUUID12 } from "node:crypto";
37059
37337
  var maxBytes = 2 * 1024 * 1024;
37060
37338
  function validEvent(event) {
37061
37339
  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));
@@ -37071,13 +37349,13 @@ var LangfuseOutbox = class {
37071
37349
  }
37072
37350
  async remove(event) {
37073
37351
  await this.writes;
37074
- await unlink3(join7(this.directory, destinationId(event.target) + "--" + event.id + ".json")).catch((e) => {
37352
+ await unlink4(join8(this.directory, destinationId(event.target) + "--" + event.id + ".json")).catch((e) => {
37075
37353
  if (e.code !== "ENOENT") throw e;
37076
37354
  });
37077
37355
  }
37078
37356
  async files() {
37079
37357
  try {
37080
- return (await readdir3(this.directory)).sort();
37358
+ return (await readdir4(this.directory)).sort();
37081
37359
  } catch (e) {
37082
37360
  if (e.code === "ENOENT") return [];
37083
37361
  throw e;
@@ -37088,12 +37366,12 @@ var LangfuseOutbox = class {
37088
37366
  return { pending: pending.filter((n) => !active || n.startsWith(active + "--")).length, otherPending: active ? pending.filter((n) => !n.startsWith(active + "--")).length : 0, blocked: names2.filter((n) => n.endsWith(".corrupt")).length };
37089
37367
  }
37090
37368
  put(value) {
37091
- const text7 = JSON.stringify(value), event = JSON.parse(text7);
37369
+ const text6 = JSON.stringify(value), event = JSON.parse(text6);
37092
37370
  const work = this.writes.then(async () => {
37093
37371
  const target = resolveTarget(event.target.name, event.target);
37094
- if (!validEvent(event) || Buffer.byteLength(text7) > maxBytes) throw new Error("invalid-event");
37095
- await mkdir4(this.directory, { recursive: true, mode: 448 });
37096
- const path3 = join7(this.directory, destinationId(target) + "--" + event.id + ".json");
37372
+ if (!validEvent(event) || Buffer.byteLength(text6) > maxBytes) throw new Error("invalid-event");
37373
+ await mkdir5(this.directory, { recursive: true, mode: 448 });
37374
+ const path3 = join8(this.directory, destinationId(target) + "--" + event.id + ".json");
37097
37375
  try {
37098
37376
  await stat(path3);
37099
37377
  return;
@@ -37101,16 +37379,17 @@ var LangfuseOutbox = class {
37101
37379
  if (e.code !== "ENOENT") throw e;
37102
37380
  }
37103
37381
  if ((await this.files()).length >= 1e3) throw new Error("queue-full");
37104
- const tmp = path3 + "." + randomUUID11() + ".tmp";
37382
+ const tmp = path3 + "." + randomUUID12() + ".tmp";
37105
37383
  try {
37106
- await writeFile5(tmp, text7, { flag: "wx", mode: 384, flush: true });
37384
+ await writeFile5(tmp, text6, { flag: "wx", mode: 384, flush: true });
37107
37385
  await rename4(tmp, path3);
37108
37386
  } finally {
37109
- await unlink3(tmp).catch(() => {
37387
+ await unlink4(tmp).catch(() => {
37110
37388
  });
37111
37389
  }
37112
37390
  });
37113
- this.writes = work.catch(() => {
37391
+ this.writes = work.catch((error) => {
37392
+ diagnostic("langfuse.outbox.write", "failed", {}, error);
37114
37393
  });
37115
37394
  return work;
37116
37395
  }
@@ -37129,7 +37408,7 @@ var LangfuseOutbox = class {
37129
37408
  for (const name2 of names2) {
37130
37409
  signal.throwIfAborted();
37131
37410
  if (attempts >= 20) break;
37132
- const path3 = join7(this.directory, name2);
37411
+ const path3 = join8(this.directory, name2);
37133
37412
  let value;
37134
37413
  try {
37135
37414
  if ((await stat(path3)).size > maxBytes) throw new Error();
@@ -37137,7 +37416,8 @@ var LangfuseOutbox = class {
37137
37416
  const target = resolveTarget(value.target.name, value.target);
37138
37417
  if (name2 !== destinationId(target) + "--" + value.id + ".json" || !validEvent(value)) throw new Error();
37139
37418
  } catch {
37140
- await rename4(path3, path3 + "." + randomUUID11() + ".corrupt");
37419
+ await rename4(path3, path3 + "." + randomUUID12() + ".corrupt");
37420
+ diagnostic("langfuse.outbox.quarantine", "failed", {}, new Error("invalid-event"));
37141
37421
  continue;
37142
37422
  }
37143
37423
  const destination = destinationId(value.target);
@@ -37145,14 +37425,19 @@ var LangfuseOutbox = class {
37145
37425
  if (failedTargets.has(destination)) continue;
37146
37426
  attempts++;
37147
37427
  this.lastAttempted = name2;
37148
- try {
37149
- await send(value);
37150
- await unlink3(path3);
37151
- } catch (error) {
37152
- if (options.independentPending && error instanceof Error && error.message === "judge-pending") continue;
37153
- failedTargets.add(destination);
37154
- firstError ??= error;
37155
- }
37428
+ await diagnosticOperation(async () => {
37429
+ const started = performance.now();
37430
+ try {
37431
+ await send(value);
37432
+ await unlink4(path3);
37433
+ diagnostic("langfuse.outbox.delivery", "ok", { elapsedMs: Math.round(performance.now() - started) });
37434
+ } catch (error) {
37435
+ if (options.independentPending && error instanceof Error && error.message === "judge-pending") return;
37436
+ diagnostic("langfuse.outbox.delivery", signal.aborted ? "cancelled" : "pending", { elapsedMs: Math.round(performance.now() - started) }, error);
37437
+ failedTargets.add(destination);
37438
+ firstError ??= error;
37439
+ }
37440
+ });
37156
37441
  }
37157
37442
  if (firstError) throw firstError;
37158
37443
  } finally {
@@ -37189,12 +37474,13 @@ async function deliverAgentEvent(event) {
37189
37474
  }
37190
37475
  var AgentKnowledgeObserver = class {
37191
37476
  options;
37477
+ production;
37192
37478
  started;
37193
37479
  outbox;
37194
37480
  judgments;
37195
37481
  ready;
37196
37482
  lifetime = new AbortController();
37197
- instanceId = randomUUID12();
37483
+ instanceId = randomUUID13();
37198
37484
  timer;
37199
37485
  entries = /* @__PURE__ */ new Map();
37200
37486
  finished = /* @__PURE__ */ new Set();
@@ -37212,19 +37498,21 @@ var AgentKnowledgeObserver = class {
37212
37498
  v2 = false;
37213
37499
  sanitize = (value) => value;
37214
37500
  constructor(options) {
37501
+ this.production = options.environment === "production";
37215
37502
  this.options = options;
37216
- this.outbox = new LangfuseOutbox(join8(options.directory, "completed"));
37217
- this.started = new LangfuseOutbox(join8(options.directory, "started"));
37218
- this.judgments = new LangfuseOutbox(join8(options.directory, "judgments"));
37219
- this.ready = readTarget(options.configFile).then(async (target) => {
37503
+ this.outbox = new LangfuseOutbox(join9(options.directory, "completed"));
37504
+ this.started = new LangfuseOutbox(join9(options.directory, "started"));
37505
+ this.judgments = new LangfuseOutbox(join9(options.directory, "judgments"));
37506
+ this.ready = readTarget(options.configFile, options.environment).then(async (target) => {
37220
37507
  const config = JSON.parse(await readFile7(options.configFile, "utf8"));
37221
- this.v2 = config.knowledgeEvaluationV2 === true;
37508
+ this.v2 = !this.production && config.knowledgeEvaluationV2 === true;
37222
37509
  if (this.v2 && target?.projectId !== "wanji-sales-test") throw Error("test-project-required");
37223
- if (this.v2) this.sanitize = await readEvaluationPrivacy(config.redactionKeyFile);
37510
+ if ((this.v2 || this.production) && target) this.sanitize = await readEvaluationPrivacy(config.redactionKeyFile, options.environment);
37224
37511
  this.target = target;
37225
37512
  if (target) await this.recover();
37226
- }).catch(() => {
37513
+ }).catch((error) => {
37227
37514
  this.error = "configuration-unavailable";
37515
+ diagnostic("langfuse.agent.config", "failed", {}, error);
37228
37516
  }).finally(() => {
37229
37517
  this.initialized = true;
37230
37518
  });
@@ -37234,7 +37522,7 @@ var AgentKnowledgeObserver = class {
37234
37522
  this.timer.unref();
37235
37523
  }
37236
37524
  eligible(exec) {
37237
- if (!exec.agent?.id || this.lifetime.signal.aborted) return;
37525
+ if (this.production || !exec.agent?.id || this.lifetime.signal.aborted) return;
37238
37526
  const a = object2(exec.arguments), kb = this.options.knowledgeBaseId;
37239
37527
  if (exec.name === this.options.toolPrefix + "_search") {
37240
37528
  if (a.knowledge_ids !== void 0) return;
@@ -37267,6 +37555,28 @@ var AgentKnowledgeObserver = class {
37267
37555
  }
37268
37556
  while (this.documentScopes.size > 2e3) this.documentScopes.delete(this.documentScopes.keys().next().value);
37269
37557
  }
37558
+ productionSearchOutput(value, knowledgeBaseId, status) {
37559
+ const ids = list(value.knowledge_base_ids), hits = list(value.results), documents = list(value.documents);
37560
+ if (ids.length !== 1 || ids[0] !== knowledgeBaseId || [...hits, ...documents].some((row) => row?.knowledge_base_id !== void 0 && row.knowledge_base_id !== knowledgeBaseId)) return { status: "scope-mismatch" };
37561
+ return {
37562
+ status,
37563
+ returned_chunks: hits.length,
37564
+ hits: hits.slice(0, 8).map((raw, index2) => {
37565
+ const hit = object2(raw);
37566
+ return {
37567
+ rank: Number.isFinite(hit.rank) ? hit.rank : index2 + 1,
37568
+ ...typeof hit.knowledge_id === "string" ? { knowledge_id: hit.knowledge_id.slice(0, 128) } : {},
37569
+ ...typeof hit.chunk_id === "string" ? { chunk_id: hit.chunk_id.slice(0, 128) } : {},
37570
+ ...typeof hit.document === "string" ? { title: maskObservationText(this.sanitize(hit.document), 250) } : {},
37571
+ ...typeof hit.score === "number" && Number.isFinite(hit.score) ? { score: hit.score } : {},
37572
+ ...typeof hit.content === "string" ? { excerpt: maskObservationText(this.sanitize(hit.content), 350) } : {}
37573
+ };
37574
+ })
37575
+ };
37576
+ }
37577
+ ownsDestination(event) {
37578
+ return !this.production || !!this.target && destinationId(event.target) === destinationId(this.target);
37579
+ }
37270
37580
  begin(exec, dispatched) {
37271
37581
  if (this.finished.has(exec.token)) return;
37272
37582
  const existing = this.entries.get(exec.token);
@@ -37281,14 +37591,18 @@ var AgentKnowledgeObserver = class {
37281
37591
  this.error = "capture-capacity";
37282
37592
  return;
37283
37593
  }
37284
- const input = detailed ? this.sanitize(JSON.parse(JSON.stringify(object2(exec.arguments)))) : {};
37594
+ const args = object2(exec.arguments);
37595
+ const input = detailed ? this.sanitize(JSON.parse(JSON.stringify(args))) : this.production && exec.name.endsWith("_search") && typeof args.query === "string" ? {
37596
+ query: maskObservationText(this.sanitize(args.query), 4e3),
37597
+ ...Number.isSafeInteger(args.max_results) ? { max_results: args.max_results } : {}
37598
+ } : {};
37285
37599
  if (Buffer.byteLength(JSON.stringify(input)) > 32e3) {
37286
37600
  this.dropped++;
37287
37601
  this.error = "input-too-large";
37288
37602
  return;
37289
37603
  }
37290
37604
  const entry = { turn: exec.agent ? this.turns.current(exec.agent.id)?.turn : void 0, since: performance.now(), event: {
37291
- id: randomUUID12(),
37605
+ id: randomUUID13(),
37292
37606
  target: this.target,
37293
37607
  kind,
37294
37608
  knowledgeBaseId,
@@ -37363,7 +37677,7 @@ var AgentKnowledgeObserver = class {
37363
37677
  const empty = value.returned_chunks === 0 || exec.name.endsWith("_search") && !list(value.results).length && !list(value.documents).length;
37364
37678
  const status2 = result.isError ? code4 === "TOOL_TIMEOUT" ? "timeout" : exec.signal.aborted ? "cancelled" : "error" : empty ? "empty" : "success";
37365
37679
  if (!result.isError && exec.name.endsWith("_search")) this.rememberDocumentScopes(value, event.knowledgeBaseId);
37366
- event.output = { status: status2 };
37680
+ event.output = this.production && !result.isError && exec.name.endsWith("_search") ? this.productionSearchOutput(value, event.knowledgeBaseId, status2) : { status: status2 };
37367
37681
  void this.queue(async () => {
37368
37682
  await this.outbox.put(event);
37369
37683
  await this.started.remove(event);
@@ -37401,9 +37715,9 @@ var AgentKnowledgeObserver = class {
37401
37715
  }
37402
37716
  } else if (typeof value.content === "string") this.turns.evidence(exec.agent.id, { results: [{ knowledge_id: value.knowledge_id, chunk_id: "read-" + String(value.page ?? 1), content: value.content, truncated: value.truncated === true }] }, true);
37403
37717
  }
37404
- const text7 = JSON.stringify(output);
37718
+ const text6 = JSON.stringify(output);
37405
37719
  event.input = this.sanitize(event.input);
37406
- event.output = Buffer.byteLength(text7) > 15e5 ? { status: "capture-truncated", judge_eligible: false, outcome_known: true } : this.sanitize(JSON.parse(text7));
37720
+ event.output = Buffer.byteLength(text6) > 15e5 ? { status: "capture-truncated", judge_eligible: false, outcome_known: true } : this.sanitize(JSON.parse(text6));
37407
37721
  if (event.output.status === "capture-truncated") this.turns.invalidate(exec.agent.id);
37408
37722
  void this.queue(async () => {
37409
37723
  await this.outbox.put(event);
@@ -37416,7 +37730,7 @@ var AgentKnowledgeObserver = class {
37416
37730
  }
37417
37731
  }
37418
37732
  recordMaterialMetadata(knowledgeBaseId, startedAt, elapsedMs, status) {
37419
- const callId = randomUUID12();
37733
+ const callId = randomUUID13();
37420
37734
  void this.ready.then(() => {
37421
37735
  if (!this.target || this.lifetime.signal.aborted || knowledgeBaseId !== this.options.material?.knowledgeBaseId) return;
37422
37736
  const event = {
@@ -37442,7 +37756,7 @@ var AgentKnowledgeObserver = class {
37442
37756
  try {
37443
37757
  const turn = this.turns.accept(sessionId, event);
37444
37758
  if (!turn) return;
37445
- const id2 = randomUUID12(), value = { id: id2, target: this.target, kind: "answer", knowledgeBaseId: this.options.knowledgeBaseId, startedAt: turn.startedAt, elapsedMs: Math.max(0, Date.now() - Date.parse(turn.startedAt)), input: { user_question: turn.question }, output: { status: "success", judge_eligible: false, judge_v2_eligible: true, evaluation: { user_question: turn.question, answer: turn.answer, evidence: turn.evidence, observed_at: turn.startedAt } }, agent: { sessionId, callId: "answer-" + turn.turn, rootCallId: "answer-" + turn.turn, nested: false, dispatched: true, instanceId: this.instanceId } };
37759
+ const id2 = randomUUID13(), value = { id: id2, target: this.target, kind: "answer", knowledgeBaseId: this.options.knowledgeBaseId, startedAt: turn.startedAt, elapsedMs: Math.max(0, Date.now() - Date.parse(turn.startedAt)), input: { user_question: turn.question }, output: { status: "success", judge_eligible: false, judge_v2_eligible: true, evaluation: { user_question: turn.question, answer: turn.answer, evidence: turn.evidence, observed_at: turn.startedAt } }, agent: { sessionId, callId: "answer-" + turn.turn, rootCallId: "answer-" + turn.turn, nested: false, dispatched: true, instanceId: this.instanceId } };
37446
37760
  if (Buffer.byteLength(JSON.stringify(value)) > 15e5 || this.pendingWrites >= 1e3) return;
37447
37761
  value.input = this.sanitize(value.input);
37448
37762
  value.output = this.sanitize(value.output);
@@ -37456,7 +37770,7 @@ var AgentKnowledgeObserver = class {
37456
37770
  try {
37457
37771
  await this.started.flush(async (event) => {
37458
37772
  await this.outbox.put({ ...event, output: { status: "interrupted", judge_eligible: false, outcome_known: false } });
37459
- }, this.lifetime.signal, (event) => (event.agent?.instanceId ?? event.knowledgeCall?.instanceId) !== this.instanceId);
37773
+ }, this.lifetime.signal, (event) => this.ownsDestination(event) && (event.agent?.instanceId ?? event.knowledgeCall?.instanceId) !== this.instanceId);
37460
37774
  this.recoveryError = void 0;
37461
37775
  } catch {
37462
37776
  this.recoveryError = "journal-recovery-pending";
@@ -37469,14 +37783,14 @@ var AgentKnowledgeObserver = class {
37469
37783
  await this.drain();
37470
37784
  if (!this.target || this.lifetime.signal.aborted) return;
37471
37785
  await this.recover();
37472
- const validate = this.options.validate ?? (!this.options.send ? deliverKnowledgeJudgment : void 0);
37786
+ const validate = this.production ? void 0 : this.options.validate ?? (!this.options.send ? deliverKnowledgeJudgment : void 0);
37473
37787
  if (validate) await this.judgments.flush(validate, this.lifetime.signal, () => true, { independentPending: true }).catch(() => {
37474
37788
  this.error = "judgment-validation-pending";
37475
37789
  });
37476
37790
  await this.outbox.flush(async (event) => {
37477
37791
  await (this.options.send ?? deliverAgentEvent)(event);
37478
37792
  if (validate && event.kind === "search" && event.output.judge_v2_eligible === true) await this.judgments.put(event);
37479
- }, this.lifetime.signal);
37793
+ }, this.lifetime.signal, (event) => this.ownsDestination(event));
37480
37794
  if (this.error === "delivery-pending") this.error = void 0;
37481
37795
  await this.recover();
37482
37796
  } catch {
@@ -37506,8 +37820,8 @@ var AgentKnowledgeObserver = class {
37506
37820
  };
37507
37821
 
37508
37822
  // src/host.ts
37509
- import { homedir as homedir6 } from "node:os";
37510
- import { join as join14 } from "node:path";
37823
+ import { homedir as homedir7 } from "node:os";
37824
+ import { join as join15 } from "node:path";
37511
37825
 
37512
37826
  // src/server/audio.ts
37513
37827
  import { spawn as spawn3 } from "node:child_process";
@@ -37561,9 +37875,9 @@ function parseCrm(value) {
37561
37875
  const name2 = string(rawLead.name, code4);
37562
37876
  if (!Array.isArray(data.recordings) || !Number.isSafeInteger(data.recordingTotal) || data.recordingTotal !== data.recordings.length) throw new ProfileError(code4, "Recording count does not match the complete list");
37563
37877
  const date2 = (v2) => {
37564
- const text7 = string(v2, code4);
37565
- if (!Number.isFinite(Date.parse(text7))) throw new ProfileError(code4, "Invalid recording timestamp");
37566
- return text7;
37878
+ const text6 = string(v2, code4);
37879
+ if (!Number.isFinite(Date.parse(text6))) throw new ProfileError(code4, "Invalid recording timestamp");
37880
+ return text6;
37567
37881
  };
37568
37882
  const ids = /* @__PURE__ */ new Set();
37569
37883
  const recordings = data.recordings.map((value2) => {
@@ -37594,7 +37908,7 @@ async function lookupCrm(input, config, parent, fetcher2 = fetch) {
37594
37908
  const { refresh: _refresh, ...body } = input;
37595
37909
  let response;
37596
37910
  try {
37597
- response = await fetcher2(`${config.crmBaseUrl}/api/v1/integrations/leads/context`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body), redirect: "error", signal });
37911
+ response = await diagnosticHttp("crm.http.lookup", () => fetcher2(`${config.crmBaseUrl}/api/v1/integrations/leads/context`, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body), redirect: "error", signal }), signal);
37598
37912
  } catch {
37599
37913
  parent.throwIfAborted();
37600
37914
  throw new ProfileError("CRM_UNAVAILABLE", "CRM request failed or timed out");
@@ -37740,8 +38054,8 @@ function createStructuredTranscriber(config, speech, fetcher2 = fetch) {
37740
38054
  }
37741
38055
 
37742
38056
  // src/server/config.ts
37743
- import { homedir as homedir4 } from "node:os";
37744
- import { isAbsolute as isAbsolute3, join as join9 } from "node:path";
38057
+ import { homedir as homedir5 } from "node:os";
38058
+ import { isAbsolute as isAbsolute4, join as join10 } from "node:path";
37745
38059
  function phone(value) {
37746
38060
  const normalized = string(value).normalize("NFKC").trim().replace(/[\s()-]/gu, "");
37747
38061
  if (!/^\+?\d{7,15}$/u.test(normalized)) throw new ProfileError("INVALID_INPUT", "A complete phone number is required");
@@ -37781,13 +38095,13 @@ function resolveConfig(value = {}) {
37781
38095
  const asr = object(input.asr ?? {}, "INVALID_CONFIG");
37782
38096
  if (Object.keys(asr).some((k2) => !["provider", "language"].includes(k2))) throw new ProfileError("INVALID_CONFIG", "Configure speech services in DSH; asr accepts only provider and language");
37783
38097
  const optional = (v2) => v2 === void 0 ? void 0 : string(v2, "INVALID_CONFIG").trim();
37784
- const storageDir = String(input.storageDir ?? process.env.WANJI_SALES_STORAGE_DIR ?? join9(homedir4(), ".dsh", "wanji-sales"));
37785
- if (!isAbsolute3(storageDir)) throw new ProfileError("INVALID_CONFIG", "storageDir must be absolute");
38098
+ const storageDir = String(input.storageDir ?? process.env.WANJI_SALES_STORAGE_DIR ?? join10(homedir5(), ".dsh", "wanji-sales"));
38099
+ if (!isAbsolute4(storageDir)) throw new ProfileError("INVALID_CONFIG", "storageDir must be absolute");
37786
38100
  const provider = optional(input.modelProvider);
37787
38101
  const model = optional(input.model);
37788
38102
  if (Boolean(provider) !== Boolean(model)) throw new ProfileError("INVALID_CONFIG", "modelProvider and model must be supplied together");
37789
38103
  return {
37790
- crmBaseUrl: httpUrl(input.crmBaseUrl ?? process.env.WANJI_SALES_CRM_BASE_URL ?? "http://192.168.3.145:18081"),
38104
+ crmBaseUrl: httpUrl(input.crmBaseUrl ?? process.env.WANJI_SALES_CRM_BASE_URL ?? "https://group.wanjivip.com/crm"),
37791
38105
  storageDir,
37792
38106
  requestTimeoutMs: integer3("requestTimeoutMs", 12e4),
37793
38107
  analysisTimeoutMs: integer3("analysisTimeoutMs", 18e4),
@@ -37806,7 +38120,7 @@ function resolveConfig(value = {}) {
37806
38120
  }
37807
38121
  var positive = (fallback) => Schema.natural().min(1).max(Number.MAX_SAFE_INTEGER).default(fallback);
37808
38122
  var profileSettings = Schema.object({
37809
- crmBaseUrl: Schema.string().min(1).description("CRM HTTP(S) root. Defaults to WANJI_SALES_CRM_BASE_URL or the test CRM."),
38123
+ crmBaseUrl: Schema.string().min(1).description("CRM HTTP(S) root. Defaults to WANJI_SALES_CRM_BASE_URL or https://group.wanjivip.com/crm (production)."),
37810
38124
  storageDir: Schema.string().min(1).description("Absolute private artifact directory. Defaults to WANJI_SALES_STORAGE_DIR or ~/.dsh/wanji-sales."),
37811
38125
  requestTimeoutMs: positive(12e4).max(2147483647).description("CRM/download/transcription deadline in milliseconds."),
37812
38126
  analysisTimeoutMs: positive(18e4).max(2147483647).description("Profile-model request deadline in milliseconds."),
@@ -37862,16 +38176,16 @@ async function runModel(llm, route, input, signal) {
37862
38176
  }
37863
38177
  signal.throwIfAborted();
37864
38178
  if (!finished) throw new ProfileError("MODEL_INCOMPLETE", "Profile model stream ended without a terminal finish");
37865
- const text7 = [...blocks.entries()].sort(([a], [b2]) => a - b2).map(([, value]) => value).join("").trim().replace(/^```(?:json)?\s*/u, "").replace(/\s*```$/u, "");
38179
+ const text6 = [...blocks.entries()].sort(([a], [b2]) => a - b2).map(([, value]) => value).join("").trim().replace(/^```(?:json)?\s*/u, "").replace(/\s*```$/u, "");
37866
38180
  try {
37867
- return JSON.parse(text7);
38181
+ return JSON.parse(text6);
37868
38182
  } catch {
37869
38183
  throw new ProfileError("INVALID_MODEL_OUTPUT", "Profile model did not return JSON");
37870
38184
  }
37871
38185
  }
37872
38186
 
37873
38187
  // src/server/profile-v2.ts
37874
- import { randomUUID as randomUUID13 } from "node:crypto";
38188
+ import { randomUUID as randomUUID14 } from "node:crypto";
37875
38189
 
37876
38190
  // src/server/analysis.ts
37877
38191
  var ANALYSIS_VERSION = "crm-dual-products-roles-timeline-v6-product-context";
@@ -37883,9 +38197,9 @@ function fail(message) {
37883
38197
  throw new ProfileError(code2, message);
37884
38198
  }
37885
38199
  function txt(value, max = 2e3) {
37886
- const text7 = string(value, code2);
37887
- if (text7.length > max) fail("Analysis text exceeds limit");
37888
- return text7;
38200
+ const text6 = string(value, code2);
38201
+ if (text6.length > max) fail("Analysis text exceeds limit");
38202
+ return text6;
37889
38203
  }
37890
38204
  function choice(value, values) {
37891
38205
  if (typeof value !== "string" || !values.includes(value)) fail("Invalid analysis enum");
@@ -38059,13 +38373,13 @@ function createProductProfileService(deps) {
38059
38373
  let modelChars = 0, renewed = false, allCached = true;
38060
38374
  const request2 = async (stage, payload) => {
38061
38375
  signal.throwIfAborted();
38062
- const system = stage === "extract" ? EXTRACT_SYSTEM : REVIEW_SYSTEM, text7 = JSON.stringify(payload);
38063
- modelChars += system.length + text7.length;
38376
+ const system = stage === "extract" ? EXTRACT_SYSTEM : REVIEW_SYSTEM, text6 = JSON.stringify(payload);
38377
+ modelChars += system.length + text6.length;
38064
38378
  if (modelChars > config.maxModelInputChars) throw new ProfileError("MODEL_INPUT_TOO_LARGE", "Aggregate analysis-input budget exceeded");
38065
- const traceId = randomUUID13(), entry = { version: ANALYSIS_VERSION, stage, system, text: text7, model: execution.modelKey, traceId, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
38379
+ const traceId = randomUUID14(), entry = { version: ANALYSIS_VERSION, stage, system, text: text6, model: execution.modelKey, traceId, createdAt: (/* @__PURE__ */ new Date()).toISOString() };
38066
38380
  await store.write("requests", traceId, entry);
38067
38381
  await execution.audit?.("profile-request", entry);
38068
- const result = await deps.analyze({ system, text: text7 }, signal);
38382
+ const result = await deps.analyze({ system, text: text6 }, signal);
38069
38383
  signal.throwIfAborted();
38070
38384
  await store.write("requests", traceId, { ...entry, response: result });
38071
38385
  await execution.audit?.("profile-response", { traceId, stage, response: result });
@@ -38418,8 +38732,8 @@ function parseDocument(value) {
38418
38732
  }
38419
38733
 
38420
38734
  // src/source-plan.ts
38421
- function parseSourcePlan(text7) {
38422
- const cleaned = text7.trim().replace(/^```(?:json)?\s*\n([\s\S]*?)\n```$/, "$1");
38735
+ function parseSourcePlan(text6) {
38736
+ const cleaned = text6.trim().replace(/^```(?:json)?\s*\n([\s\S]*?)\n```$/, "$1");
38423
38737
  const v2 = JSON.parse(cleaned);
38424
38738
  if (!v2 || typeof v2 !== "object" || Array.isArray(v2) || Object.keys(v2).sort().join(",") !== "action_id,deal_id,source_ids" || typeof v2.deal_id !== "string" || typeof v2.action_id !== "string" || !Array.isArray(v2.source_ids) || v2.source_ids.length > 16 || v2.source_ids.some((s3) => typeof s3 !== "string") || new Set(v2.source_ids).size !== v2.source_ids.length) throw Error("\u53EA\u63A5\u53D7\u5F53\u524D\u5546\u673A\u7684\u6765\u6E90\u4E0E\u52A8\u4F5CID\uFF0C\u4E0D\u63A5\u53D7\u6A21\u578B\u64B0\u5199\u7684\u627F\u8BFA\u3002");
38425
38739
  return v2;
@@ -38476,18 +38790,18 @@ async function resolvePolicyCatalog(input, signal) {
38476
38790
  stage = "process";
38477
38791
  const output = await new Promise((resolve4, reject) => {
38478
38792
  const child = spawn5("python3", ["-B", fileURLToPath3(script), "--catalog", "-"], { signal: AbortSignal.any([signal, AbortSignal.timeout(1e4)]), stdio: ["pipe", "pipe", "pipe"] });
38479
- let text7 = "";
38793
+ let text6 = "";
38480
38794
  child.stdout.setEncoding("utf8");
38481
38795
  child.stdout.on("data", (chunk) => {
38482
- text7 += chunk;
38483
- if (text7.length > 1e6) {
38796
+ text6 += chunk;
38797
+ if (text6.length > 1e6) {
38484
38798
  child.kill();
38485
38799
  reject(new KnowledgeError("policy-filter-failed"));
38486
38800
  }
38487
38801
  });
38488
38802
  child.stderr.resume();
38489
38803
  child.on("error", () => reject(new KnowledgeError(signal.aborted ? "cancelled" : "policy-filter-failed")));
38490
- child.on("close", (code4) => code4 === 0 ? resolve4(text7) : reject(new KnowledgeError("policy-filter-failed")));
38804
+ child.on("close", (code4) => code4 === 0 ? resolve4(text6) : reject(new KnowledgeError("policy-filter-failed")));
38491
38805
  child.stdin.on("error", () => {
38492
38806
  });
38493
38807
  child.stdin.end(body);
@@ -38518,8 +38832,8 @@ async function productReference(hit) {
38518
38832
  const catalog = JSON.parse(await readFile8(new URL("../runtime/product-references.json", import.meta.url), "utf8"));
38519
38833
  const entry = catalog.find((e) => e.sourceKey === m2.source_key && e.version === m2.source_version && e.sha256 === m2.source_file_sha256 && e.status === m2.content_status);
38520
38834
  if (!entry || createHash6("sha256").update(entry.text).digest("hex") !== entry.sha256) return;
38521
- const text7 = hit.content.replace(/\r\n/g, "\n").trim();
38522
- if (text7.length < 40 || !entry.text.replace(/\r\n/g, "\n").includes(text7)) return;
38835
+ const text6 = hit.content.replace(/\r\n/g, "\n").trim();
38836
+ if (text6.length < 40 || !entry.text.replace(/\r\n/g, "\n").includes(text6)) return;
38523
38837
  return { knowledge_id: hit.knowledge_id, chunk_id: hit.chunk_id, sourceKey: entry.sourceKey, version: entry.version, text: hit.content, boundary: entry.boundary };
38524
38838
  }
38525
38839
 
@@ -38542,8 +38856,8 @@ async function operationReference(hit) {
38542
38856
  const catalog = JSON.parse(await readFile9(new URL("../runtime/operation-references.json", import.meta.url), "utf8"));
38543
38857
  const entry = catalog.find((e) => e.knowledgeId === hit.knowledge_id && e.sourceKey === m2.source_key && e.version === m2.release_version && e.edition === m2.product_edition && e.sha256 === m2.source_body_sha256 && e.status === m2.content_status);
38544
38858
  if (!entry || createHash7("sha256").update(entry.text).digest("hex") !== entry.sha256) return documentedOperation(hit);
38545
- const text7 = hit.content.replace(/\r\n/g, "\n").trim();
38546
- if (text7.length < 40 || !entry.text.replace(/\r\n/g, "\n").includes(text7)) return documentedOperation(hit);
38859
+ const text6 = hit.content.replace(/\r\n/g, "\n").trim();
38860
+ if (text6.length < 40 || !entry.text.replace(/\r\n/g, "\n").includes(text6)) return documentedOperation(hit);
38547
38861
  return { knowledge_id: hit.knowledge_id, chunk_id: hit.chunk_id, sourceKey: entry.sourceKey, version: entry.version, edition: entry.edition, text: hit.content, boundary: entry.boundary };
38548
38862
  }
38549
38863
 
@@ -38598,7 +38912,7 @@ async function validateSalesContext(context2, signal) {
38598
38912
  }
38599
38913
 
38600
38914
  // src/langfuse-collector.ts
38601
- import { createHash as createHash8, randomUUID as randomUUID14 } from "node:crypto";
38915
+ import { createHash as createHash8, randomUUID as randomUUID15 } from "node:crypto";
38602
38916
 
38603
38917
  // src/evaluation-types.ts
38604
38918
  function nullable2(v2) {
@@ -38665,8 +38979,8 @@ function parseRun(value) {
38665
38979
  }
38666
38980
 
38667
38981
  // src/langfuse-collector.ts
38668
- function uuid5(text7) {
38669
- const namespace = Buffer.from("6ba7b8119dad11d180b400c04fd430c8", "hex"), bytes = createHash8("sha1").update(namespace).update(text7).digest().subarray(0, 16);
38982
+ function uuid5(text6) {
38983
+ const namespace = Buffer.from("6ba7b8119dad11d180b400c04fd430c8", "hex"), bytes = createHash8("sha1").update(namespace).update(text6).digest().subarray(0, 16);
38670
38984
  bytes[6] = bytes[6] & 15 | 80;
38671
38985
  bytes[8] = bytes[8] & 63 | 128;
38672
38986
  const s3 = bytes.toString("hex");
@@ -38693,8 +39007,9 @@ var LangfuseCollector = class {
38693
39007
  this.outbox = new LangfuseOutbox(options.directory);
38694
39008
  this.ready = readTarget(options.configFile).then((target) => {
38695
39009
  this.target = target;
38696
- }, () => {
39010
+ }, (error) => {
38697
39011
  this.error = "configuration-unavailable";
39012
+ diagnostic("langfuse.config", "failed", {}, error);
38698
39013
  });
38699
39014
  const timer = setInterval(() => {
38700
39015
  void this.flush();
@@ -38723,7 +39038,7 @@ var LangfuseCollector = class {
38723
39038
  async read(value) {
38724
39039
  await this.ready;
38725
39040
  if (!this.target) return;
38726
- await this.enqueue({ ...value, id: randomUUID14(), target: this.target, kind: "read", knowledgeBaseId: this.options.knowledgeBaseId });
39041
+ await this.enqueue({ ...value, id: randomUUID15(), target: this.target, kind: "read", knowledgeBaseId: this.options.knowledgeBaseId });
38727
39042
  }
38728
39043
  async enqueue(event) {
38729
39044
  try {
@@ -38794,14 +39109,14 @@ var LangfuseCollector = class {
38794
39109
  };
38795
39110
 
38796
39111
  // src/knowledge-host.ts
38797
- import { randomUUID as randomUUID18 } from "node:crypto";
38798
- import { homedir as homedir5 } from "node:os";
38799
- import { join as join11 } from "node:path";
39112
+ import { randomUUID as randomUUID19 } from "node:crypto";
39113
+ import { homedir as homedir6 } from "node:os";
39114
+ import { isAbsolute as isAbsolute6, join as join12 } from "node:path";
38800
39115
 
38801
39116
  // src/evaluation-outbox.ts
38802
- import { mkdir as mkdir5, readdir as readdir4, readFile as readFile10, rename as rename5, stat as stat2, unlink as unlink4, writeFile as writeFile6 } from "node:fs/promises";
38803
- import { randomUUID as randomUUID15 } from "node:crypto";
38804
- import { join as join10 } from "node:path";
39117
+ import { mkdir as mkdir6, readdir as readdir5, readFile as readFile10, rename as rename5, stat as stat2, unlink as unlink5, writeFile as writeFile6 } from "node:fs/promises";
39118
+ import { randomUUID as randomUUID16 } from "node:crypto";
39119
+ import { join as join11 } from "node:path";
38805
39120
  var MAX_EVENT_BYTES = 512 * 1024;
38806
39121
  var EvaluationOutbox = class {
38807
39122
  flushing = false;
@@ -38813,7 +39128,7 @@ var EvaluationOutbox = class {
38813
39128
  async files(extension = "json") {
38814
39129
  const pattern2 = extension === "json" ? /^[a-zA-Z0-9_-]+\.json$/ : extension === "corrupt" ? /^[a-zA-Z0-9_-]+\.corrupt$/ : /^[a-zA-Z0-9_-]+\.rejected$/;
38815
39130
  try {
38816
- return (await readdir4(this.directory)).filter((name2) => pattern2.test(name2)).sort();
39131
+ return (await readdir5(this.directory)).filter((name2) => pattern2.test(name2)).sort();
38817
39132
  } catch (error) {
38818
39133
  if (error.code === "ENOENT") return [];
38819
39134
  throw error;
@@ -38830,7 +39145,7 @@ var EvaluationOutbox = class {
38830
39145
  }
38831
39146
  async acknowledge(id2) {
38832
39147
  if (!/^[a-zA-Z0-9_-]{1,160}$/.test(id2)) throw new Error("Invalid evaluation event ID");
38833
- await unlink4(join10(this.directory, id2 + ".json")).catch((error) => {
39148
+ await unlink5(join11(this.directory, id2 + ".json")).catch((error) => {
38834
39149
  if (error.code !== "ENOENT") throw error;
38835
39150
  });
38836
39151
  }
@@ -38843,20 +39158,20 @@ var EvaluationOutbox = class {
38843
39158
  async persist(event) {
38844
39159
  if (!/^[a-zA-Z0-9_-]{1,160}$/.test(event.event_id) || event.query.length > 4e3 || Buffer.byteLength(JSON.stringify(event)) > MAX_EVENT_BYTES) throw new Error("Invalid client evaluation event");
38845
39160
  if (await this.pending() + await this.blocked() >= 1e3) throw new Error("Evaluation outbox capacity exceeded");
38846
- await mkdir5(this.directory, { recursive: true, mode: 448 });
38847
- const final = join10(this.directory, event.event_id + ".json");
39161
+ await mkdir6(this.directory, { recursive: true, mode: 448 });
39162
+ const final = join11(this.directory, event.event_id + ".json");
38848
39163
  try {
38849
39164
  await stat2(final);
38850
39165
  return;
38851
39166
  } catch (error) {
38852
39167
  if (error.code !== "ENOENT") throw error;
38853
39168
  }
38854
- const temporary = join10(this.directory, `.${event.event_id}-${randomUUID15()}.tmp`);
39169
+ const temporary = join11(this.directory, `.${event.event_id}-${randomUUID16()}.tmp`);
38855
39170
  try {
38856
39171
  await writeFile6(temporary, JSON.stringify(event), { encoding: "utf8", mode: 384, flag: "wx", flush: true });
38857
39172
  await rename5(temporary, final);
38858
39173
  } finally {
38859
- await unlink4(temporary).catch((error) => {
39174
+ await unlink5(temporary).catch((error) => {
38860
39175
  if (error.code !== "ENOENT") throw error;
38861
39176
  });
38862
39177
  }
@@ -38869,7 +39184,7 @@ var EvaluationOutbox = class {
38869
39184
  for (const filename of (await this.files()).slice(0, 20)) {
38870
39185
  signal.throwIfAborted();
38871
39186
  let event;
38872
- const path3 = join10(this.directory, filename);
39187
+ const path3 = join11(this.directory, filename);
38873
39188
  let content;
38874
39189
  try {
38875
39190
  if ((await stat2(path3)).size > MAX_EVENT_BYTES) content = "";
@@ -38884,14 +39199,14 @@ var EvaluationOutbox = class {
38884
39199
  if (!event || filename !== event.event_id + ".json" || typeof event.query !== "string" || event.query.length > 4e3 || typeof event.error_code !== "string" || !statuses.includes(event.status) || typeof event.source !== "string") throw new Error("Invalid stored client evaluation event");
38885
39200
  if (event.tool_result && (event.tool_result.event_id !== event.event_id || event.tool_result.query !== event.query || event.tool_result.status !== event.status || !Array.isArray(event.tool_result.hits) || event.tool_result.hits.length > 8)) throw new Error("Invalid stored tool evidence");
38886
39201
  } catch {
38887
- await rename5(path3, join10(this.directory, `${filename.slice(0, -5)}-${randomUUID15()}.corrupt`));
39202
+ await rename5(path3, join11(this.directory, `${filename.slice(0, -5)}-${randomUUID16()}.corrupt`));
38888
39203
  continue;
38889
39204
  }
38890
39205
  try {
38891
39206
  await send(event);
38892
39207
  } catch (error) {
38893
39208
  if (error?.permanent === true) {
38894
- await rename5(path3, join10(this.directory, `${filename.slice(0, -5)}-${randomUUID15()}.rejected`));
39209
+ await rename5(path3, join11(this.directory, `${filename.slice(0, -5)}-${randomUUID16()}.rejected`));
38895
39210
  continue;
38896
39211
  }
38897
39212
  throw error;
@@ -38905,7 +39220,7 @@ var EvaluationOutbox = class {
38905
39220
  };
38906
39221
 
38907
39222
  // src/tool-evaluation.ts
38908
- import { randomUUID as randomUUID16 } from "node:crypto";
39223
+ import { randomUUID as randomUUID17 } from "node:crypto";
38909
39224
  var ToolEvaluation = class {
38910
39225
  options;
38911
39226
  runs = /* @__PURE__ */ new Map();
@@ -38941,7 +39256,7 @@ var ToolEvaluation = class {
38941
39256
  return result;
38942
39257
  }
38943
39258
  async search(query, maxResults, signal, association) {
38944
- const started = performance.now(), startedAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = randomUUID16();
39259
+ const started = performance.now(), startedAt = (/* @__PURE__ */ new Date()).toISOString(), eventId = randomUUID17();
38945
39260
  const meta = { event_id: eventId, query, max_results: maxResults, k: association?.k ?? 3, tool_name: this.options.toolName, tool_version: this.options.toolVersion, ...association ? { run_id: association.run_id, case_key: association.case_key } : {} };
38946
39261
  let report;
38947
39262
  try {
@@ -38962,7 +39277,7 @@ var ToolEvaluation = class {
38962
39277
  if (Object.keys(payload).some((key) => !["dataset_id", "max_results", "k"].includes(key)) || typeof payload.dataset_id !== "string" || !/^[a-zA-Z0-9_-]{1,160}$/.test(payload.dataset_id) || typeof maxResults !== "number" || !Number.isInteger(maxResults) || maxResults < 1 || maxResults > this.options.maxResults || typeof k2 !== "number" || !Number.isInteger(k2) || k2 < 1 || k2 > 8) throw new KnowledgeError("bad-request");
38963
39278
  this.starting++;
38964
39279
  try {
38965
- const run = parseRun(await this.options.evaluate({ operation: "create_tool_run", payload: { ...payload, client_run_id: randomUUID16(), tool_name: this.options.toolName, tool_version: this.options.toolVersion } }, signal));
39280
+ const run = parseRun(await this.options.evaluate({ operation: "create_tool_run", payload: { ...payload, client_run_id: randomUUID17(), tool_name: this.options.toolName, tool_version: this.options.toolVersion } }, signal));
38966
39281
  if (run.config.run_mode !== "harness-tool" || run.dataset_id !== payload.dataset_id || run.config.max_results !== maxResults || run.config.k !== k2 || run.items.length < 1 || run.items.length > 200 || new Set(run.items.map((i) => i.case_key)).size !== run.items.length) throw new KnowledgeError("invalid-response");
38967
39282
  const controller = new AbortController();
38968
39283
  this.runs.set(run.id, controller);
@@ -39014,25 +39329,26 @@ var ToolEvaluation = class {
39014
39329
 
39015
39330
  // src/weknora-http.ts
39016
39331
  import { readFileSync as readFileSync3, statSync } from "node:fs";
39017
- import { isAbsolute as isAbsolute4 } from "node:path";
39332
+ import { isAbsolute as isAbsolute5 } from "node:path";
39018
39333
  var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
39019
- function resolveWeKnoraConnection(raw, label) {
39334
+ function resolveWeKnoraConnection(raw, label, defaultBaseUrl) {
39020
39335
  if (raw === void 0) return void 0;
39021
39336
  try {
39022
39337
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error();
39023
39338
  const c = raw;
39024
39339
  if (Object.keys(c).some((k2) => !["baseUrl", "apiKey", "apiKeyFile", "tenantId"].includes(k2))) throw new Error();
39025
- if (typeof c.baseUrl !== "string") throw new Error();
39340
+ const baseUrl = c.baseUrl === void 0 ? defaultBaseUrl : c.baseUrl;
39341
+ if (typeof baseUrl !== "string") throw new Error();
39026
39342
  let credential = c.apiKey;
39027
39343
  if (c.apiKeyFile !== void 0) {
39028
39344
  const file = c.apiKeyFile;
39029
- if (credential !== void 0 || typeof file !== "string" || !isAbsolute4(file)) throw new Error();
39345
+ if (credential !== void 0 || typeof file !== "string" || !isAbsolute5(file)) throw new Error();
39030
39346
  const stat4 = statSync(file);
39031
39347
  if (!stat4.isFile() || stat4.size > 65536 || process.platform !== "win32" && stat4.mode & 63) throw new Error();
39032
39348
  credential = JSON.parse(readFileSync3(file, "utf8"))?.api_key;
39033
39349
  }
39034
39350
  if (typeof credential !== "string" || !credential.trim()) throw new Error();
39035
- const url = new URL(c.baseUrl.trim());
39351
+ const url = new URL(baseUrl.trim());
39036
39352
  if (!["https:", "http:"].includes(url.protocol) || url.username || url.password || url.search || url.hash) throw new Error();
39037
39353
  const path3 = url.pathname.replace(/\/+$/, "");
39038
39354
  url.pathname = path3.endsWith("/api/v1") ? path3 : path3 + "/api/v1";
@@ -39228,7 +39544,11 @@ function createEvaluationClient(connection, options) {
39228
39544
  try {
39229
39545
  const headers = { "X-API-Key": connection.apiKey, Accept: "application/json", "Content-Type": "application/json", "X-Evaluation-Source": "sales-assistant" };
39230
39546
  if (connection.tenantId) headers["X-Tenant-ID"] = connection.tenantId;
39231
- const response = await fetch(connection.baseUrl + req.path, { method: req.method, body: req.body, headers, signal: fused, redirect: "error" });
39547
+ const response = await diagnosticHttp(
39548
+ "weknora.http.evaluation",
39549
+ () => fetch(connection.baseUrl + req.path, { method: req.method, body: req.body, headers, signal: fused, redirect: "error" }),
39550
+ fused
39551
+ );
39232
39552
  const value = await readWeKnoraData(response);
39233
39553
  fused.throwIfAborted();
39234
39554
  assertEvaluationScope(value, options.knowledgeBaseId);
@@ -39256,7 +39576,7 @@ var knowledgeCases = [
39256
39576
  ];
39257
39577
 
39258
39578
  // src/material-catalog.ts
39259
- import { randomUUID as randomUUID17 } from "node:crypto";
39579
+ import { randomUUID as randomUUID18 } from "node:crypto";
39260
39580
 
39261
39581
  // src/customer-materials.ts
39262
39582
  var MATERIAL_KB_ID = "1f93aee2-6d66-42d7-8b7a-b5fe5d094550";
@@ -39324,7 +39644,7 @@ function qualifiedMaterialHits(response, query, calibrated) {
39324
39644
  const passages = array2(response.results).map(record);
39325
39645
  const documents = array2(response.documents).map(record);
39326
39646
  if (!calibrated) return [...passages, ...documents];
39327
- const normalize = (text7) => text7.normalize("NFKC").replace(/\s/g, "").toLowerCase();
39647
+ const normalize = (text6) => text6.normalize("NFKC").replace(/\s/g, "").toLowerCase();
39328
39648
  const request2 = normalize(query);
39329
39649
  const hasTitle = (title) => typeof title === "string" && normalize(title).length >= 4 && request2.includes(normalize(title));
39330
39650
  return [
@@ -39347,21 +39667,21 @@ function createMaterialCatalog(config, maxResults, invoke, readMetadata, head =
39347
39667
  const format = profile3.file_format;
39348
39668
  const type = fileTypes[format];
39349
39669
  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;
39350
- const scope = record(profile3.product_scope);
39670
+ const scope2 = record(profile3.product_scope);
39351
39671
  let scopeLabel;
39352
- if (scope.status === "explicit_edition") {
39353
- if (constraints.enterpriseEditionUnknown || !materialEditions.some((edition) => edition === scope.edition && (!constraints.comparedEditions || constraints.comparedEditions.includes(edition))) || scope.edition !== meta.product_edition || constraints.edition && constraints.edition !== scope.edition) return void 0;
39354
- scopeLabel = String(scope.edition);
39672
+ if (scope2.status === "explicit_edition") {
39673
+ if (constraints.enterpriseEditionUnknown || !materialEditions.some((edition) => edition === scope2.edition && (!constraints.comparedEditions || constraints.comparedEditions.includes(edition))) || scope2.edition !== meta.product_edition || constraints.edition && constraints.edition !== scope2.edition) return void 0;
39674
+ scopeLabel = String(scope2.edition);
39355
39675
  } else {
39356
- if (constraints.edition || !["edition_unverified", "edition_independent", "demonstrated_scope_only"].includes(String(scope.status)) || typeof scope.display !== "string") return void 0;
39357
- scopeLabel = scope.status === "edition_unverified" ? scope.display + "\uFF08\u5177\u4F53\u7248\u672C\u5F85\u786E\u8BA4\uFF09" : scope.display;
39676
+ if (constraints.edition || !["edition_unverified", "edition_independent", "demonstrated_scope_only"].includes(String(scope2.status)) || typeof scope2.display !== "string") return void 0;
39677
+ scopeLabel = scope2.status === "edition_unverified" ? scope2.display + "\uFF08\u5177\u4F53\u7248\u672C\u5F85\u786E\u8BA4\uFF09" : scope2.display;
39358
39678
  }
39359
39679
  const url = new URL(meta.file_url);
39360
39680
  if (!url.href.startsWith(config.assetBaseUrl) || url.username || url.password || url.search || url.hash || !type.extension.test(url.pathname)) return void 0;
39361
39681
  const deliveryNote = typeof profile3.delivery_note === "string" ? modelText(profile3.delivery_note, 200) : "";
39362
39682
  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 } : {} };
39363
39683
  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);
39364
- const operation = scope.status === "explicit_edition" && ["operation_reference", "operation_learning"].includes(String(profile3.purpose));
39684
+ const operation = scope2.status === "explicit_edition" && ["operation_reference", "operation_learning"].includes(String(profile3.purpose));
39365
39685
  return { candidate, url: url.href, location, operation };
39366
39686
  }
39367
39687
  async function readEvidence(id2, signal) {
@@ -39434,7 +39754,7 @@ function createMaterialCatalog(config, maxResults, invoke, readMetadata, head =
39434
39754
  }
39435
39755
  signal.throwIfAborted();
39436
39756
  if (!checked.length) return { status: "empty" };
39437
- const requestId = randomUUID17();
39757
+ const requestId = randomUUID18();
39438
39758
  if (grants.size >= 128) grants.delete(grants.keys().next().value);
39439
39759
  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 });
39440
39760
  return { status: "candidates", requestId, candidates: checked.map((item) => item.candidate) };
@@ -39476,7 +39796,7 @@ function createMaterialMetadataReader(connection, requestTimeoutMs, record3) {
39476
39796
  const startedAt = (/* @__PURE__ */ new Date()).toISOString(), started = performance.now();
39477
39797
  let status = "error";
39478
39798
  try {
39479
- const response = await fetch(connection.baseUrl + "/knowledge/" + id2, { method: "GET", headers, signal: fused, redirect: "error" });
39799
+ const response = await diagnosticHttp("weknora.http.material-metadata", () => fetch(connection.baseUrl + "/knowledge/" + id2, { method: "GET", headers, signal: fused, redirect: "error" }), fused);
39480
39800
  const value = await readWeKnoraData(response);
39481
39801
  fused.throwIfAborted();
39482
39802
  status = "success";
@@ -39586,12 +39906,13 @@ function createWeKnoraRetrieval(connection, libraryIds, timeoutMs, evaluation) {
39586
39906
  const fused = AbortSignal.any([signal, timeout]);
39587
39907
  try {
39588
39908
  fused.throwIfAborted();
39589
- const response = await fetch(connection.baseUrl + path3, {
39909
+ const operation = path3 === "/knowledge-bases" ? "list" : path3 === "/knowledge-search" ? "search" : path3.startsWith("/knowledge/search?") ? "named-search" : "read";
39910
+ const response = await diagnosticHttp("weknora.http." + operation, () => fetch(connection.baseUrl + path3, {
39590
39911
  headers,
39591
39912
  signal: fused,
39592
39913
  redirect: "error",
39593
39914
  ...body ? { method: "POST", body: JSON.stringify(body) } : { method: "GET" }
39594
- });
39915
+ }), fused);
39595
39916
  const envelope = await readWeKnoraEnvelope(response);
39596
39917
  fused.throwIfAborted();
39597
39918
  return envelope;
@@ -39615,7 +39936,7 @@ function createWeKnoraRetrieval(connection, libraryIds, timeoutMs, evaluation) {
39615
39936
  const maxResults = Number(args.max_results);
39616
39937
  if (!ids.length || ids.some((id2) => !allowed2.has(id2))) throw new KnowledgeError("scope-mismatch");
39617
39938
  if (!query.trim() || query.length > 4e3 || !Number.isSafeInteger(maxResults) || maxResults < 1 || maxResults > 8) throw new KnowledgeError("bad-request");
39618
- const scope = new Set(ids), wanted = new Set(documentIds);
39939
+ const scope2 = new Set(ids), wanted = new Set(documentIds);
39619
39940
  const namedParams = new URLSearchParams({ keyword: query, limit: String(maxResults) });
39620
39941
  const [response, named] = await Promise.all([
39621
39942
  request2("/knowledge-search", signal, { query, knowledge_base_ids: ids, ...documentIds.length ? { knowledge_ids: documentIds } : {} }),
@@ -39625,13 +39946,13 @@ function createWeKnoraRetrieval(connection, libraryIds, timeoutMs, evaluation) {
39625
39946
  })
39626
39947
  ]);
39627
39948
  const hits = array2(response.data).map(record);
39628
- if (hits.some((hit) => hit.knowledge_base_id !== void 0 && !scope.has(string2(hit.knowledge_base_id)) || wanted.size && !wanted.has(string2(hit.knowledge_id)))) throw new KnowledgeError("scope-mismatch");
39949
+ if (hits.some((hit) => hit.knowledge_base_id !== void 0 && !scope2.has(string2(hit.knowledge_base_id)) || wanted.size && !wanted.has(string2(hit.knowledge_id)))) throw new KnowledgeError("scope-mismatch");
39629
39950
  const results = hits.slice(0, maxResults).map((hit, i) => projectHit(hit, i + 1));
39630
39951
  const seen = new Set(results.map((hit) => hit.knowledge_id));
39631
39952
  const documents = [];
39632
39953
  for (const doc of named) {
39633
39954
  const id2 = text5(doc.id), base = text5(doc.knowledge_base_id);
39634
- if (!id2 || seen.has(id2) || !scope.has(base) || wanted.size && !wanted.has(id2)) continue;
39955
+ if (!id2 || seen.has(id2) || !scope2.has(base) || wanted.size && !wanted.has(id2)) continue;
39635
39956
  seen.add(id2);
39636
39957
  documents.push({ knowledge_id: id2, knowledge_base_id: base, title: text5(doc.title).trim() || text5(doc.file_name) || id2, knowledge_base: text5(doc.knowledge_base_name) || base });
39637
39958
  if (documents.length === maxResults) break;
@@ -39713,8 +40034,13 @@ var MaterialRetriever = class {
39713
40034
  this.rerank = rerank;
39714
40035
  }
39715
40036
  async readable(m2, signal) {
40037
+ const fused = AbortSignal.any([signal, AbortSignal.timeout(8e3)]);
39716
40038
  try {
39717
- const response = await this.head(assetUrl(m2.fileUrl, m2.fileSha256), { method: "HEAD", redirect: "manual", signal: AbortSignal.any([signal, AbortSignal.timeout(8e3)]) }), type = response.headers.get("content-type") ?? "";
40039
+ const response = await diagnosticHttp(
40040
+ "materials.http.asset-check",
40041
+ () => this.head(assetUrl(m2.fileUrl, m2.fileSha256), { method: "HEAD", redirect: "manual", signal: fused }),
40042
+ fused
40043
+ ), type = response.headers.get("content-type") ?? "";
39718
40044
  return response.ok && Number(response.headers.get("content-length") ?? 1) > 0 && (/application\/octet-stream/i.test(type) || (m2.kind === "video" ? /^video\//i : m2.kind === "document" ? /application\/pdf/i : /^image\//i).test(type));
39719
40045
  } catch {
39720
40046
  signal.throwIfAborted();
@@ -39726,19 +40052,27 @@ var MaterialRetriever = class {
39726
40052
  if (input.edition === "unknown") return result("edition_required");
39727
40053
  if (!input.query.trim() || input.query.length > 600 || /(?:\d[\s-]*){7,}|https?:\/\/|[\w.+-]+@[\w.-]+/.test(input.query)) throw Error("MATERIAL_QUERY_INVALID");
39728
40054
  const tool = this.prefix + "_search";
39729
- if (!this.tools.get(tool)) return result("unavailable");
40055
+ if (!this.tools.get(tool)) {
40056
+ diagnostic("mcp.materials.search", "unavailable", {}, new Error("missing-tools"));
40057
+ return result("unavailable");
40058
+ }
40059
+ const started = performance.now();
39730
40060
  try {
39731
40061
  const format = { video: "\u89C6\u9891\u6559\u7A0B \u64CD\u4F5C\u6F14\u793A", document: "PDF\u6587\u5B57\u64CD\u4F5C\u6307\u5357", image: "\u754C\u9762 \u56FE\u7247 \u622A\u56FE", any: "" }[input.kind];
39732
40062
  const queries = [input.edition + "\n" + input.query, ...format ? [input.edition + " " + format + "\n" + input.query] : []];
39733
40063
  const reports = await Promise.all(queries.map(async (query) => {
39734
40064
  const id2 = crypto.randomUUID(), batch = await this.tools.execute({ calls: [{ type: "tool-call", id: id2, name: tool, arguments: JSON.stringify({ query, knowledge_base_ids: [MATERIAL_KB_ID], ...this.knowledgeIds ? { knowledge_ids: this.knowledgeIds } : {}, max_results: 8 }) }], signal }), value = batch.results.find((r) => r.callId === id2)?.result;
39735
- if (!value || value.isError) return null;
40065
+ if (!value || value.isError) {
40066
+ diagnostic("mcp.materials.search", "failed", {}, value?.error?.info);
40067
+ return null;
40068
+ }
39736
40069
  const report = parseSearch({ ...record(value.value), elapsedMs: 0, searchedAt: (/* @__PURE__ */ new Date()).toISOString(), maxResults: 8 });
39737
40070
  if (report.knowledge_base_ids.length !== 1 || report.knowledge_base_ids[0] !== MATERIAL_KB_ID || report.documents.some((d) => d.knowledge_base_id !== MATERIAL_KB_ID)) throw Error("MATERIAL_SCOPE_INVALID");
39738
40071
  if (this.knowledgeIds && (report.results.some((h) => !this.knowledgeIds.includes(h.knowledge_id)) || report.documents.some((d) => !this.knowledgeIds.includes(d.knowledge_id)))) throw Error("MATERIAL_SCOPE_INVALID");
39739
40072
  return report;
39740
40073
  }));
39741
40074
  if (reports.some((r) => !r)) return result("unavailable");
40075
+ diagnostic("mcp.materials.search", "ok", { elapsedMs: Math.round(performance.now() - started) });
39742
40076
  const catalog = JSON.parse(await readFile11(new URL("../runtime/customer-materials.json", import.meta.url), "utf8")), seen = /* @__PURE__ */ new Set();
39743
40077
  const hits = /* @__PURE__ */ new Map();
39744
40078
  for (const report of reports) for (const [i, h] of report.results.entries()) {
@@ -39764,7 +40098,8 @@ var MaterialRetriever = class {
39764
40098
  }).slice(0, 6);
39765
40099
  const checks = await Promise.all(candidates.map(async (m2) => await this.readable(m2, signal) ? m2 : null)), items = checks.filter((m2) => m2 !== null);
39766
40100
  return parseCustomerMaterials(result(items.length ? "available" : candidates.length ? "unavailable" : "not_found", items));
39767
- } catch {
40101
+ } catch (error) {
40102
+ diagnostic("materials.search", signal.aborted ? "cancelled" : "failed", {}, error);
39768
40103
  signal.throwIfAborted();
39769
40104
  return result("unavailable");
39770
40105
  }
@@ -39797,9 +40132,20 @@ function resolveKnowledgeConfig(input = {}) {
39797
40132
  const c = record(input);
39798
40133
  const ids = c.knowledgeBaseIds === void 0 ? [] : array2(c.knowledgeBaseIds).map(string2);
39799
40134
  if (ids.some((id2) => !id2.trim()) || new Set(ids).size !== ids.length) throw new Error("Invalid knowledgeBaseIds");
39800
- const current = ids.length === 1 && ids[0] === TEST_KNOWLEDGE_BASE_ID;
39801
- const environment = c.environment ?? (current ? "test" : "production");
40135
+ const salesScope = ids.length === 1 && ids[0] === TEST_KNOWLEDGE_BASE_ID;
40136
+ const usesProductionWeKnora = [c.knowledgeConnection, c.materialConnection, c.materialMetadata].some((connection) => weknoraEnvironment(connection) === "production");
40137
+ const environment = c.environment ?? (salesScope && !usesProductionWeKnora ? "test" : "production");
39802
40138
  if (environment !== "test" && environment !== "production") throw new Error("Invalid environment");
40139
+ const testingEnabled = salesScope && environment === "test" && c.knowledgeTestEnabled !== false;
40140
+ const production = environment === "production" && (c.environment === "production" || usesProductionWeKnora);
40141
+ function scoped(connection, operation) {
40142
+ const target = weknoraEnvironment(connection);
40143
+ if (target && target !== environment) {
40144
+ diagnostic(operation, "failed", {}, new Error("knowledge-environment-mismatch"));
40145
+ return;
40146
+ }
40147
+ return connection;
40148
+ }
39803
40149
  if (c.knowledgeTestEnabled !== void 0 && typeof c.knowledgeTestEnabled !== "boolean") throw new Error("Invalid knowledgeTestEnabled");
39804
40150
  if (c.draftKnowledgeEnabled !== void 0 && typeof c.draftKnowledgeEnabled !== "boolean") throw Error("Invalid draftKnowledgeEnabled");
39805
40151
  if (c.draftKnowledgeEnabled === true && !ids.length) throw Error("Draft knowledge scope required");
@@ -39825,33 +40171,39 @@ function resolveKnowledgeConfig(input = {}) {
39825
40171
  const evaluationDatasetId = c.evaluationDatasetId === void 0 ? void 0 : string2(c.evaluationDatasetId);
39826
40172
  if (evaluationDatasetId !== void 0 && !/^[a-zA-Z0-9_-]{1,160}$/.test(evaluationDatasetId)) throw new Error("Invalid evaluationDatasetId");
39827
40173
  const expected = c.expectedDocuments === void 0 ? {} : record(c.expectedDocuments);
39828
- const evaluation = resolveEvaluationConnection(c.evaluation);
40174
+ const evaluation = testingEnabled ? scoped(resolveEvaluationConnection(c.evaluation), "knowledge.evaluation-config") : void 0;
39829
40175
  const material = resolveMaterialConfig(c.materialKnowledgeBaseId, c.materialAssetBaseUrl);
39830
- const materialMetadata = resolveWeKnoraConnection(c.materialMetadata, "material metadata");
39831
- const knowledgeConnection = resolveWeKnoraConnection(c.knowledgeConnection, "sales knowledge");
39832
- const materialConnection = resolveWeKnoraConnection(c.materialConnection, "customer material");
40176
+ const defaultBaseUrl = production ? PRODUCTION_WEKNORA_BASE_URL : void 0;
40177
+ const materialMetadata = scoped(resolveWeKnoraConnection(c.materialMetadata, "material metadata", defaultBaseUrl), "materials.metadata-config");
40178
+ const knowledgeConnection = scoped(resolveWeKnoraConnection(c.knowledgeConnection, "sales knowledge", defaultBaseUrl), "knowledge.config");
40179
+ const materialConnection = scoped(resolveWeKnoraConnection(c.materialConnection, "customer material", defaultBaseUrl), "materials.config");
39833
40180
  if (materialMetadata && !material) throw new Error("Material knowledge base and download directory are required");
39834
- if (material && ids.includes(material.knowledgeBaseId)) throw new Error("Material knowledge base must be separate from reply knowledge");
40181
+ if (material && ids.includes(material.knowledgeBaseId) || production && materialIds.some((id2) => ids.includes(id2))) throw new Error("Material knowledge base must be separate from reply knowledge");
39835
40182
  const toolVersion = c.toolVersion === void 0 ? "unavailable" : string2(c.toolVersion);
39836
40183
  if (!/^[a-zA-Z0-9_.+-]{1,80}$/.test(toolVersion)) throw new Error("Invalid toolVersion");
39837
- if (c.langfuseConfigFile !== void 0 && (typeof c.langfuseConfigFile !== "string" || !c.langfuseConfigFile.startsWith("/"))) throw new Error("Invalid langfuseConfigFile");
40184
+ if (c.langfuseConfigFile !== void 0 && (typeof c.langfuseConfigFile !== "string" || !isAbsolute6(c.langfuseConfigFile))) throw new Error("Invalid langfuseConfigFile");
39838
40185
  return {
39839
- ...current && environment === "test" && c.knowledgeTestEnabled !== false ? { ...evaluationKnowledgeIds ? { evaluationKnowledgeIds } : {}, ...evaluationMaterialIds ? { evaluationMaterialIds } : {} } : {},
39840
- ...current && environment === "test" && c.knowledgeTestEnabled !== false && c.materialRetrievalEnabled === true ? { materialRetrievalEnabled: true, materialKnowledgeBaseIds: materialIds, materialToolPrefix: materialPrefix } : {},
40186
+ ...testingEnabled && evaluationKnowledgeIds ? { evaluationKnowledgeIds } : {},
40187
+ ...testingEnabled && evaluationMaterialIds ? { evaluationMaterialIds } : {},
40188
+ ...(testingEnabled || production) && c.materialRetrievalEnabled === true ? { materialRetrievalEnabled: true, materialKnowledgeBaseIds: materialIds, materialToolPrefix: materialPrefix } : {},
39841
40189
  ...c.semanticRerank === true ? { semanticRerank: true } : {},
39842
40190
  ...c.langfuseConfigFile ? { langfuseConfigFile: c.langfuseConfigFile } : {},
39843
40191
  toolVersion,
39844
40192
  ...evaluation ? { evaluation } : {},
39845
40193
  ...evaluationDatasetId ? { evaluationDatasetId } : {},
39846
- ...material ? { materialKnowledgeBaseId: material.knowledgeBaseId, materialAssetBaseUrl: material.assetBaseUrl, ...c.materialToolPrefix !== void 0 ? { materialToolPrefix: materialPrefix } : {} } : {},
40194
+ ...material ? {
40195
+ materialKnowledgeBaseId: material.knowledgeBaseId,
40196
+ materialAssetBaseUrl: material.assetBaseUrl,
40197
+ ...c.materialToolPrefix !== void 0 ? { materialToolPrefix: materialPrefix } : {}
40198
+ } : {},
39847
40199
  ...materialMetadata ? { materialMetadata } : {},
39848
- environment,
39849
- knowledgeTestEnabled: current && environment === "test" && c.knowledgeTestEnabled !== false,
39850
40200
  ...knowledgeConnection ? { knowledgeConnection } : {},
39851
40201
  ...materialConnection ? { materialConnection } : {},
39852
40202
  ...c.draftKnowledgeEnabled === true ? { draftKnowledgeEnabled: true } : {},
39853
- agentKnowledgeTracing: current && environment === "test" && c.agentKnowledgeTracing === true,
39854
- salesQuestionTracing: current && environment === "test" && c.knowledgeTestEnabled !== false && c.salesQuestionTracing !== false,
40203
+ environment,
40204
+ knowledgeTestEnabled: testingEnabled,
40205
+ agentKnowledgeTracing: salesScope && c.agentKnowledgeTracing === true && (environment === "test" || production && !!c.langfuseConfigFile),
40206
+ salesQuestionTracing: testingEnabled && c.salesQuestionTracing !== false || production && salesScope && c.salesQuestionTracing === true && !!c.langfuseConfigFile,
39855
40207
  knowledgeBaseIds: ids,
39856
40208
  knowledgeBaseName: c.knowledgeBaseName === void 0 ? "" : string2(c.knowledgeBaseName),
39857
40209
  toolPrefix: prefix,
@@ -39865,7 +40217,7 @@ function inputFields(payload, allowed2) {
39865
40217
  if (Object.keys(p2).some((key) => !allowed2.includes(key))) throw new KnowledgeError("bad-request");
39866
40218
  return p2;
39867
40219
  }
39868
- function createKnowledgeHost(tools, config, lifetime = new AbortController().signal, outbox, evaluationOrWorkspaces, injectedObserver, rerank, materialOverride, expandQuery, recordMaterialMetadata) {
40220
+ function createKnowledgeHost(tools, config, lifetime = new AbortController().signal, outbox, evaluationOrWorkspaces, injectedObserver, rerank, materialOverride, expandQuery, recordMaterialMetadata, directObserver) {
39869
40221
  const workspaceList = typeof evaluationOrWorkspaces === "function" ? evaluationOrWorkspaces : void 0;
39870
40222
  const evaluationService = typeof evaluationOrWorkspaces === "function" ? void 0 : evaluationOrWorkspaces;
39871
40223
  const contexts = /* @__PURE__ */ new WeakMap();
@@ -39889,7 +40241,7 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
39889
40241
  assertEvaluationScope(value, config.knowledgeBaseIds[0]);
39890
40242
  return value;
39891
40243
  }
39892
- const observer = config.knowledgeTestEnabled && evaluation ? injectedObserver ?? (config.langfuseConfigFile ? new LangfuseCollector({ configFile: config.langfuseConfigFile, directory: join11(homedir5(), ".local", "state", "wanji-sales", "langfuse"), knowledgeBaseId: config.knowledgeBaseIds[0], signal: lifetime, evaluate }) : void 0) : void 0;
40244
+ const observer = config.knowledgeTestEnabled && evaluation ? injectedObserver ?? (config.langfuseConfigFile ? new LangfuseCollector({ configFile: config.langfuseConfigFile, directory: join12(homedir6(), ".local", "state", "wanji-sales", "langfuse"), knowledgeBaseId: config.knowledgeBaseIds[0], signal: lifetime, evaluate }) : void 0) : void 0;
39893
40245
  const toolEvaluation = evaluation ? new ToolEvaluation({ toolName: `${config.toolPrefix}_search`, toolVersion: config.toolVersion, lifetime, maxResults: config.maxResults, outbox, observer, evaluate, retrieve }) : void 0;
39894
40246
  async function retrieve(query, maxResults, signal) {
39895
40247
  if (!query.trim() || query.length > 4e3) throw new KnowledgeError("bad-request");
@@ -39909,7 +40261,8 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
39909
40261
  if (config.semanticRerank && expandQuery) {
39910
40262
  try {
39911
40263
  for (const q2 of await expandQuery(query, AbortSignal.any([signal, AbortSignal.timeout(12e3)]))) if (q2 !== query) extra2.add(q2);
39912
- } catch {
40264
+ } catch (error) {
40265
+ diagnostic("knowledge.query-expansion", "failed", {}, error);
39913
40266
  signal.throwIfAborted();
39914
40267
  }
39915
40268
  }
@@ -39935,7 +40288,8 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
39935
40288
  try {
39936
40289
  report.results = await rerank(query, report.results, AbortSignal.any([signal, AbortSignal.timeout(15e3)]));
39937
40290
  report.count = report.results.length;
39938
- } catch {
40291
+ } catch (error) {
40292
+ diagnostic("knowledge.rerank", "failed", {}, error);
39939
40293
  signal.throwIfAborted();
39940
40294
  }
39941
40295
  report.elapsedMs = Math.round(performance.now() - start);
@@ -39954,6 +40308,27 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
39954
40308
  return toolEvaluation ? toolEvaluation.search(query, maxResults, signal) : retrieve(query, maxResults, signal);
39955
40309
  }
39956
40310
  async function invoke(suffix, args, signal, prefix = config.toolPrefix, transport) {
40311
+ const operation = (transport ? "knowledge.direct." : "mcp.knowledge.") + suffix;
40312
+ const started = performance.now();
40313
+ let execution;
40314
+ if (transport && config.environment === "production" && directObserver) {
40315
+ const callId = randomUUID19();
40316
+ execution = { token: /* @__PURE__ */ Symbol(), name: prefix + "_" + suffix, callId, rootCallId: callId, arguments: args, signal };
40317
+ await directObserver.start(execution);
40318
+ }
40319
+ try {
40320
+ const result = await invokeTool(suffix, args, signal, prefix, transport);
40321
+ if (execution) directObserver?.finish(execution, { isError: false, value: result, content: void 0 });
40322
+ diagnostic(operation, "ok", { elapsedMs: Math.round(performance.now() - started) });
40323
+ return result;
40324
+ } catch (error) {
40325
+ const code4 = error instanceof KnowledgeError && error.code === "timeout" ? "TOOL_TIMEOUT" : "DIRECT_KNOWLEDGE_FAILED";
40326
+ if (execution) directObserver?.finish(execution, { isError: true, content: void 0, error: { info: { code: code4 } } });
40327
+ diagnostic(operation, signal.aborted ? "cancelled" : "failed", { elapsedMs: Math.round(performance.now() - started) }, error);
40328
+ throw error;
40329
+ }
40330
+ }
40331
+ async function invokeTool(suffix, args, signal, prefix = config.toolPrefix, transport) {
39957
40332
  signal.throwIfAborted();
39958
40333
  if (transport) {
39959
40334
  if (suffix === "list_knowledge_bases") return transport.list(signal);
@@ -39964,7 +40339,7 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
39964
40339
  const timeout = AbortSignal.timeout(config.requestTimeoutMs);
39965
40340
  const fused = AbortSignal.any([signal, timeout]);
39966
40341
  try {
39967
- const id2 = randomUUID18();
40342
+ const id2 = randomUUID19();
39968
40343
  const batch = await tools.execute({ calls: [{ type: "tool-call", id: id2, name: `${prefix}_${suffix}`, arguments: JSON.stringify(args) }], signal: fused });
39969
40344
  fused.throwIfAborted();
39970
40345
  const result = batch.results[0]?.result;
@@ -39972,6 +40347,8 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
39972
40347
  const code4 = result?.error?.info?.code;
39973
40348
  const message = result?.error?.message ?? "";
39974
40349
  const httpStatus = /\bHTTP (\d{3})\b/.exec(message)?.[1];
40350
+ const status = Number(httpStatus);
40351
+ if (status >= 100 && status <= 599) diagnostic("mcp.knowledge." + suffix + ".response", "failed", { httpStatus: status }, { code: code4 });
39975
40352
  const unreachable = /failed: (?:fetch failed|network request failed)|\b(?:ECONNREFUSED|EHOSTDOWN|ENETUNREACH)\b/i.test(message);
39976
40353
  throw new KnowledgeError(code4 === "UNKNOWN_TOOL" ? "missing-tools" : code4 === "TOOL_TIMEOUT" ? "timeout" : unreachable ? "service-unreachable" : httpStatus && ["400", "413", "422"].includes(httpStatus) ? "bad-request" : httpStatus?.startsWith("5") ? "service-error" : "tool-failed");
39977
40354
  }
@@ -40026,6 +40403,12 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
40026
40403
  info.langfuse = { enabled: true, connection: "error", errorCode: "status-unavailable", pending: 0, otherPending: 0, blocked: 0 };
40027
40404
  }
40028
40405
  }
40406
+ diagnostic(
40407
+ "knowledge.connection",
40408
+ info.connected ? "ok" : "unavailable",
40409
+ { configured: info.toolsReady, count: config.knowledgeBaseIds.length },
40410
+ { code: info.errorCode }
40411
+ );
40029
40412
  return { ok: true, value: info };
40030
40413
  }
40031
40414
  if (endpoint === "workspaces") {
@@ -40048,7 +40431,7 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
40048
40431
  if (endpoint === "context") {
40049
40432
  const context2 = await buildSalesContext(await searchRequest(payload, signal), signal);
40050
40433
  signal.throwIfAborted();
40051
- const contextId = randomUUID18();
40434
+ const contextId = randomUUID19();
40052
40435
  const owned = contexts.get(peer) ?? /* @__PURE__ */ new Map();
40053
40436
  while (owned.size >= 128) owned.delete(owned.keys().next().value);
40054
40437
  owned.set(contextId, { ...context2, contextId });
@@ -40067,7 +40450,7 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
40067
40450
  if (!materials) throw new KnowledgeError("disabled");
40068
40451
  const p2 = inputFields(payload, ["query", "kind", "edition", "sentUrls", "allowResend"]);
40069
40452
  if (typeof p2.query !== "string" || !materialKinds.includes(p2.kind) || !materialEditions2.includes(p2.edition) || !Array.isArray(p2.sentUrls) || p2.sentUrls.length > 100 || p2.sentUrls.some((u2) => typeof u2 !== "string" || u2.length > 2048) || typeof p2.allowResend !== "boolean") throw new KnowledgeError("bad-request");
40070
- const found = await materials.search(p2, signal), contextId = randomUUID18(), owned = materialContexts.get(peer) ?? /* @__PURE__ */ new Map();
40453
+ const found = await materials.search(p2, signal), contextId = randomUUID19(), owned = materialContexts.get(peer) ?? /* @__PURE__ */ new Map();
40071
40454
  while (owned.size >= 128) owned.delete(owned.keys().next().value);
40072
40455
  const context2 = { ...found, contextId };
40073
40456
  owned.set(contextId, context2);
@@ -40151,16 +40534,17 @@ function createKnowledgeHost(tools, config, lifetime = new AbortController().sig
40151
40534
  throw new KnowledgeError("not-found");
40152
40535
  } catch (error) {
40153
40536
  const code4 = signal.aborted ? "cancelled" : errorCode(error);
40537
+ diagnostic("knowledge." + endpoint, signal.aborted ? "cancelled" : "failed", {}, error);
40154
40538
  return { ok: false, error: { code: code4, message: code4, details: error instanceof KnowledgeError ? error.details : {} } };
40155
40539
  }
40156
40540
  };
40157
40541
  return handle;
40158
40542
  }
40159
- function apply2(ctx, config, agentStatus, rerank, expandQuery, recordQuestion, recordMaterialMetadata) {
40543
+ function apply2(ctx, config, agentStatus, rerank, expandQuery, recordQuestion, recordMaterialMetadata, directObserver) {
40160
40544
  const lifetime = new AbortController();
40161
40545
  const resolved = resolveKnowledgeConfig(config);
40162
- const outbox = resolved.knowledgeTestEnabled ? new EvaluationOutbox(join11(homedir5(), ".local", "state", "wanji-sales", `${resolved.toolPrefix}-${resolved.knowledgeBaseIds[0]}`)) : void 0;
40163
- const handler = createKnowledgeHost(ctx.tools, resolved, lifetime.signal, outbox, ctx.workspaceRegistry ? () => ctx.workspaceRegistry.list() : void 0, void 0, rerank, void 0, expandQuery, recordMaterialMetadata);
40546
+ const outbox = resolved.knowledgeTestEnabled ? new EvaluationOutbox(join12(homedir6(), ".local", "state", "wanji-sales", `${resolved.toolPrefix}-${resolved.knowledgeBaseIds[0]}`)) : void 0;
40547
+ const handler = createKnowledgeHost(ctx.tools, resolved, lifetime.signal, outbox, ctx.workspaceRegistry ? () => ctx.workspaceRegistry.list() : void 0, void 0, rerank, void 0, expandQuery, recordMaterialMetadata, directObserver);
40164
40548
  const owner = { principal: { kind: "owner" } };
40165
40549
  for (const endpoint of ["info", "cases", "search", "read", "evaluation", "context", "validate-context", "workspaces", "render-reply", "materials", "validate-materials"]) {
40166
40550
  const method = KNOWLEDGE_ENDPOINT_PREFIX + endpoint;
@@ -40174,13 +40558,16 @@ function apply2(ctx, config, agentStatus, rerank, expandQuery, recordQuestion, r
40174
40558
  if (envelope.type !== "client-request" || envelope.method !== method || typeof envelope.rpcId !== "string" || envelope.rpcId.length > 128 || Object.keys(envelope).some((key) => !["type", "method", "rpcId", "payload"].includes(key))) return Response.json({ error: "bad-request" }, { status: 400 });
40175
40559
  const startedAt = Date.now();
40176
40560
  const result = await handler(endpoint, envelope.payload, request2.signal, owner);
40561
+ if (result.ok && ["search", "read", "materials", "context", "evaluation"].includes(endpoint)) {
40562
+ diagnostic("knowledge." + endpoint, "ok", { elapsedMs: Date.now() - startedAt });
40563
+ }
40177
40564
  if (recordQuestion && endpoint === "search") {
40178
40565
  const query = envelope.payload?.query;
40179
40566
  if (typeof query === "string" && query.trim() && query.length <= 4e3) {
40180
40567
  const report = result.ok ? result.value : void 0;
40181
40568
  const answer = report?.results.map((hit) => hit.document + "\n" + hit.content.slice(0, 1200)).join("\n\n");
40182
40569
  const outcome = result.ok ? answer ? { status: "answered", answer } : { status: "no-reply" } : { status: result.error.code === "cancelled" ? "cancelled" : "error", errorCode: result.error.code };
40183
- void recordQuestion({ source: "knowledge-search", sessionId: "sales-knowledge-search", requestId: randomUUID18(), question: query, startedAt }, outcome).catch(() => {
40570
+ void recordQuestion({ source: "knowledge-search", sessionId: "sales-knowledge-search", requestId: randomUUID19(), question: query, startedAt }, outcome).catch(() => {
40184
40571
  });
40185
40572
  }
40186
40573
  }
@@ -40223,7 +40610,7 @@ function apply2(ctx, config, agentStatus, rerank, expandQuery, recordQuestion, r
40223
40610
  }
40224
40611
 
40225
40612
  // src/server/conversation-route.ts
40226
- import { randomUUID as randomUUID19 } from "node:crypto";
40613
+ import { randomUUID as randomUUID20 } from "node:crypto";
40227
40614
  var CONVERSATION_ENDPOINT = "wanji-sales-conversation/context";
40228
40615
  function registerConversationRoute(ctx) {
40229
40616
  const dispose = ctx.connection.fetch.register({ path: "/api/" + CONVERSATION_ENDPOINT, methods: ["POST"], requestBody: "buffered", async fetch(request2) {
@@ -40238,7 +40625,7 @@ function registerConversationRoute(ctx) {
40238
40625
  try {
40239
40626
  const input = parseConversationInput(envelope.payload);
40240
40627
  if (!ctx.workspaceRegistry?.list().some((w2) => w2.id === input.workspaceId)) throw new ProfileError("WORKSPACE_UNAVAILABLE", "Unknown workspace");
40241
- const id2 = randomUUID19(), batch = await ctx.tools.execute({ calls: [{ type: "tool-call", id: id2, name: "crm_get_conversation_context", arguments: JSON.stringify(input) }], signal: request2.signal });
40628
+ const id2 = randomUUID20(), batch = await ctx.tools.execute({ calls: [{ type: "tool-call", id: id2, name: "crm_get_conversation_context", arguments: JSON.stringify(input) }], signal: request2.signal });
40242
40629
  const response = batch.results.find((r) => r.callId === id2)?.result;
40243
40630
  if (!response || response.isError) throw new ProfileError("CONVERSATION_CONTEXT_FAILED", "Initial context unavailable");
40244
40631
  result = { ok: true, value: response.value };
@@ -40253,7 +40640,7 @@ function registerConversationRoute(ctx) {
40253
40640
  }
40254
40641
 
40255
40642
  // src/generation-sessions.ts
40256
- import { randomUUID as randomUUID20 } from "node:crypto";
40643
+ import { randomUUID as randomUUID21 } from "node:crypto";
40257
40644
  var GenerationSessions = class {
40258
40645
  leases = /* @__PURE__ */ new Map();
40259
40646
  closed = false;
@@ -40272,7 +40659,7 @@ var GenerationSessions = class {
40272
40659
  if (leaseId && (!lease || lease.workspaceId !== workspaceId || lease.closing)) throw Error("GENERATION_LEASE");
40273
40660
  if (!lease) {
40274
40661
  if (this.leases.size >= 32) throw Error("GENERATION_BUSY");
40275
- leaseId = randomUUID20();
40662
+ leaseId = randomUUID21();
40276
40663
  const id3 = leaseId;
40277
40664
  const timer = setTimeout(() => {
40278
40665
  void this.release(id3, workspaceId).catch(() => {
@@ -40291,7 +40678,7 @@ var GenerationSessions = class {
40291
40678
  current.pending.add(finished);
40292
40679
  let handle;
40293
40680
  try {
40294
- handle = await this.services.create(workspace.path, "session-" + randomUUID20(), signal, title);
40681
+ handle = await this.services.create(workspace.path, "session-" + randomUUID21(), signal, title);
40295
40682
  if (current.closing || signal.aborted) {
40296
40683
  await handle.dispose();
40297
40684
  handle = void 0;
@@ -40371,9 +40758,9 @@ function registerGenerationSessionRoute(ctx, services) {
40371
40758
  const off = ctx.connection.fetch.register({ path: "/api/" + GENERATION_SESSION_ENDPOINT, methods: ["POST"], requestBody: "buffered", async fetch(request2) {
40372
40759
  let e;
40373
40760
  try {
40374
- const text7 = await request2.text();
40375
- if (text7.length > 4096) throw Error();
40376
- e = JSON.parse(text7);
40761
+ const text6 = await request2.text();
40762
+ if (text6.length > 4096) throw Error();
40763
+ e = JSON.parse(text6);
40377
40764
  } catch {
40378
40765
  return Response.json({ error: "bad-request" }, { status: 400 });
40379
40766
  }
@@ -40421,13 +40808,13 @@ function createGenerationRuntime(sdk, configuredModel) {
40421
40808
  await registration;
40422
40809
  signal.throwIfAborted();
40423
40810
  if (closed) throw Error("GENERATION_CLOSED");
40424
- const handle = await sdk.agents.create({ sessionId, meta: { cwd, agentPreset: SALES_GENERATION_PRESET }, agentOptions, signal, setup: async (scope, agent) => {
40425
- await sdk.presets.mount(scope, SALES_GENERATION_PRESET);
40426
- if (typeof scope.systemPrompt?.section !== "function" || typeof scope.systemPrompt?.getSectionOrder !== "function") throw Error("GENERATION_PROMPT_BOUNDARY_UNAVAILABLE");
40427
- scope.systemPrompt.section({ name: "deployment:persona-prefix", order: scope.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"), text: systemText, complete: true, interpolate: false });
40428
- if (typeof scope.tools?.restrict !== "function" || typeof scope.tools?.definitions !== "function") throw Error("GENERATION_TOOL_BOUNDARY_UNAVAILABLE");
40429
- scope.tools.restrict({ allow: [] });
40430
- if (scope.tools.definitions(agent).length) throw Error("GENERATION_TOOL_BOUNDARY_UNAVAILABLE");
40811
+ const handle = await sdk.agents.create({ sessionId, meta: { cwd, agentPreset: SALES_GENERATION_PRESET }, agentOptions, signal, setup: async (scope2, agent) => {
40812
+ await sdk.presets.mount(scope2, SALES_GENERATION_PRESET);
40813
+ if (typeof scope2.systemPrompt?.section !== "function" || typeof scope2.systemPrompt?.getSectionOrder !== "function") throw Error("GENERATION_PROMPT_BOUNDARY_UNAVAILABLE");
40814
+ scope2.systemPrompt.section({ name: "deployment:persona-prefix", order: scope2.systemPrompt.getSectionOrder("DEPLOYMENT_PERSONA_PREFIX"), text: systemText, complete: true, interpolate: false });
40815
+ if (typeof scope2.tools?.restrict !== "function" || typeof scope2.tools?.definitions !== "function") throw Error("GENERATION_TOOL_BOUNDARY_UNAVAILABLE");
40816
+ scope2.tools.restrict({ allow: [] });
40817
+ if (scope2.tools.definitions(agent).length) throw Error("GENERATION_TOOL_BOUNDARY_UNAVAILABLE");
40431
40818
  if (title && sdk.titles) sdk.titles.rename(agent.session, title);
40432
40819
  } });
40433
40820
  return { agent: handle.agent, dispose: () => handle.dispose(), titleApplied: !!title && !!sdk.titles };
@@ -40441,7 +40828,7 @@ function createGenerationRuntime(sdk, configuredModel) {
40441
40828
  }
40442
40829
 
40443
40830
  // src/question-tracing.ts
40444
- import { join as join12 } from "node:path";
40831
+ import { join as join13 } from "node:path";
40445
40832
  import { readFile as readFile12 } from "node:fs/promises";
40446
40833
 
40447
40834
  // src/question-relay.ts
@@ -40452,6 +40839,16 @@ var MANAGED_QUESTION_TARGET = resolveTarget("managed-sales-test", {
40452
40839
  credentialsRef: "wanji-langfuse-api-managed-sales-test"
40453
40840
  });
40454
40841
  async function sendManagedQuestion(relay, toolPrefix, event, signal) {
40842
+ const started = performance.now();
40843
+ try {
40844
+ await submitQuestion(relay, toolPrefix, event, signal);
40845
+ diagnostic("langfuse.managed-relay", "ok", { elapsedMs: Math.round(performance.now() - started) });
40846
+ } catch (error) {
40847
+ diagnostic("langfuse.managed-relay", signal.aborted ? "cancelled" : "failed", { elapsedMs: Math.round(performance.now() - started) }, error);
40848
+ throw error;
40849
+ }
40850
+ }
40851
+ async function submitQuestion(relay, toolPrefix, event, signal) {
40455
40852
  if (!relay || relay.toolPrefix !== toolPrefix || relay.knowledgeBaseId !== event.knowledgeBaseId) throw Error("question-relay-unavailable");
40456
40853
  if (!event.question || typeof event.input.question !== "string" || typeof event.output.status !== "string") throw Error("invalid-question-event");
40457
40854
  const receipt = await relay.submit({
@@ -40470,8 +40867,7 @@ async function sendManagedQuestion(relay, toolPrefix, event, signal) {
40470
40867
  }
40471
40868
 
40472
40869
  // src/question-tracing.ts
40473
- var safeCode = (value) => typeof value === "string" && /^[A-Za-z0-9_/-]{1,64}$/.test(value) ? value : void 0;
40474
- var text6 = (value, limit) => value.replace(/https?:\/\/[^\s<>",。!?;)]+/giu, "[\u94FE\u63A5]").replace(/\b(?:sk|pk|ghp|glpat)-[A-Za-z0-9_.-]{10,}/gu, "[\u51ED\u636E]").replace(/\bBearer\s+[A-Za-z0-9_.-]+/giu, "[\u51ED\u636E]").replace(/(?:\b(?:api[-_ ]?key|secret|password|authorization|token)\b|密码|密钥)["']?\s*[:=:]\s*["']?[^\s,"',。;]+/giu, "[\u51ED\u636E]").replace(/\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b/giu, "[\u90AE\u7BB1]").replace(/\+?\d[\d -]{8,}\d/gu, "[\u53F7\u7801]").trim().slice(0, limit);
40870
+ var safeCode2 = (value) => typeof value === "string" && /^[A-Za-z0-9_/-]{1,64}$/.test(value) ? value : void 0;
40475
40871
  var object4 = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
40476
40872
  function messageText(message, limit) {
40477
40873
  if (!Array.isArray(message.content)) return "";
@@ -40504,8 +40900,8 @@ var SalesQuestionTurns = class {
40504
40900
  }
40505
40901
  } else if (event.type === "tool/call") {
40506
40902
  if (typeof data.name === "string" && this.tools.has(data.name)) {
40507
- const scope = object4(data.arguments).knowledge_base_ids;
40508
- if (scope === void 0 || Array.isArray(scope) && scope.length === 1 && scope[0] === this.knowledgeBaseId) turn.evidence = true;
40903
+ const scope2 = object4(data.arguments).knowledge_base_ids;
40904
+ if (scope2 === void 0 || Array.isArray(scope2) && scope2.length === 1 && scope2[0] === this.knowledgeBaseId) turn.evidence = true;
40509
40905
  }
40510
40906
  } else if (event.type === "assistant/message" && data.interrupted !== true) {
40511
40907
  const answer = messageText(object4(data.message), 24e3);
@@ -40515,7 +40911,7 @@ var SalesQuestionTurns = class {
40515
40911
  if (!turn.evidence) return [];
40516
40912
  this.salesSessions.add(session);
40517
40913
  const reason = object4(data.reason);
40518
- const outcome = reason.kind === "error" ? { status: "error", errorCode: safeCode(object4(reason.error).code) } : reason.kind === "completed" ? turn.answer ? { status: "answered", answer: turn.answer } : { status: "no-reply" } : { status: reason.kind === "aborted" ? "cancelled" : "interrupted" };
40914
+ const outcome = reason.kind === "error" ? { status: "error", errorCode: safeCode2(object4(reason.error).code) } : reason.kind === "completed" ? turn.answer ? { status: "answered", answer: turn.answer } : { status: "no-reply" } : { status: reason.kind === "aborted" ? "cancelled" : "interrupted" };
40519
40915
  return turn.questions.map((q2) => ({
40520
40916
  input: { source: "sales-agent", sessionId: session.id, requestId: q2.id, question: q2.text, startedAt: turn.startedAt },
40521
40917
  outcome
@@ -40539,11 +40935,12 @@ var SalesQuestionObserver = class {
40539
40935
  options;
40540
40936
  constructor(options) {
40541
40937
  this.options = options;
40542
- this.started = new LangfuseOutbox(join12(options.directory, "started"));
40543
- this.completed = new LangfuseOutbox(join12(options.directory, "completed"));
40938
+ this.started = new LangfuseOutbox(join13(options.directory, "started"));
40939
+ this.completed = new LangfuseOutbox(join13(options.directory, "completed"));
40544
40940
  this.turns = new SalesQuestionTurns(options.toolPrefix, options.knowledgeBaseId);
40545
- this.ready = this.configure().catch(() => {
40941
+ this.ready = this.configure().catch((error) => {
40546
40942
  this.errorCode = "configuration-unavailable";
40943
+ diagnostic("langfuse.questions.config", "failed", {}, error);
40547
40944
  });
40548
40945
  this.timer = setInterval(() => {
40549
40946
  void this.flush();
@@ -40556,18 +40953,18 @@ var SalesQuestionObserver = class {
40556
40953
  this.target = MANAGED_QUESTION_TARGET;
40557
40954
  return;
40558
40955
  }
40559
- const target = await readTarget(this.options.configFile);
40956
+ const target = await readTarget(this.options.configFile, this.options.environment);
40560
40957
  if (!target) return;
40561
40958
  const config = JSON.parse(await readFile12(this.options.configFile, "utf8"));
40562
- this.sanitize = await readEvaluationPrivacy(config.redactionKeyFile);
40959
+ this.sanitize = await readEvaluationPrivacy(config.redactionKeyFile, this.options.environment);
40563
40960
  this.target = target;
40564
40961
  }
40565
40962
  event(input, outcome) {
40566
40963
  if (this.lifetime.signal.aborted || !this.target || !this.sanitize || !Number.isFinite(input.startedAt)) return;
40567
- const question = text6(this.sanitize(input.question), 8e3);
40964
+ const question = maskObservationText(this.sanitize(input.question), 8e3);
40568
40965
  if (!question) return;
40569
- const errorCode2 = safeCode(outcome.errorCode);
40570
- const answer = outcome.answer ? text6(this.sanitize(outcome.answer), 24e3) : void 0;
40966
+ const errorCode2 = safeCode2(outcome.errorCode);
40967
+ const answer = outcome.answer ? maskObservationText(this.sanitize(outcome.answer), 24e3) : void 0;
40571
40968
  return {
40572
40969
  kind: "question",
40573
40970
  id: stableId(JSON.stringify([input.source, input.sessionId, input.requestId])),
@@ -40620,7 +41017,13 @@ var SalesQuestionObserver = class {
40620
41017
  const credentials = /* @__PURE__ */ new Map();
40621
41018
  const relay = this.options.relay;
40622
41019
  const managedTarget = destinationId(MANAGED_QUESTION_TARGET);
40623
- const eligible = (event) => destinationId(event.target) === managedTarget === Boolean(relay);
41020
+ const activeTarget = destinationId(this.target);
41021
+ const production = this.options.environment === "production";
41022
+ const eligible = (event) => {
41023
+ const destination = destinationId(event.target);
41024
+ if (production) return destination === activeTarget;
41025
+ return !isProductionLangfuse(event.target) && destination === managedTarget === Boolean(relay);
41026
+ };
40624
41027
  await this.completed.flush(this.options.deliver ?? (relay ? (event) => relay(event, this.lifetime.signal) : async (event) => {
40625
41028
  const destination = destinationId(event.target);
40626
41029
  const keys = credentials.get(destination) ?? await preflight(event.target);
@@ -40694,7 +41097,7 @@ function registerQuestionRoute(ctx, observer) {
40694
41097
  }
40695
41098
 
40696
41099
  // src/server/intent-host.ts
40697
- import { randomUUID as randomUUID21 } from "node:crypto";
41100
+ import { randomUUID as randomUUID22 } from "node:crypto";
40698
41101
 
40699
41102
  // src/customer-intent.ts
40700
41103
  var intentSemanticPolicyVersion = 2;
@@ -40709,7 +41112,7 @@ function record2(value) {
40709
41112
  if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("INVALID_INTENT_RESULT");
40710
41113
  return value;
40711
41114
  }
40712
- var clean = (text7) => text7.replace(/https?:\/\/\S+/giu, "[\u94FE\u63A5]").replace(/\+?\d[\d -]{8,}\d/gu, "[\u53F7\u7801]").slice(0, 750);
41115
+ var clean = (text6) => text6.replace(/https?:\/\/\S+/giu, "[\u94FE\u63A5]").replace(/\+?\d[\d -]{8,}\d/gu, "[\u53F7\u7801]").slice(0, 750);
40713
41116
  function sources(input, profile3) {
40714
41117
  const out = input.messages.map((m2) => ({ ...m2, text: clean(m2.text), source: "wechat" }));
40715
41118
  const evidence3 = new Map(profile3?.evidence.map((value) => [value.id, value]));
@@ -40814,7 +41217,12 @@ async function lookupCrmIntent(base, phone2, ids, signal, fetcher2 = fetch) {
40814
41217
  async function request2(path3) {
40815
41218
  const url = new URL(base + path3);
40816
41219
  url.searchParams.set("phone", phone2);
40817
- const response = await fetcher2(url, { redirect: "error", signal, headers: { accept: "application/json" } });
41220
+ const operation = path3.endsWith("/customers") ? "customers" : "leads";
41221
+ const response = await diagnosticHttp(
41222
+ "crm.http.intent-" + operation,
41223
+ () => fetcher2(url, { redirect: "error", signal, headers: { accept: "application/json" } }),
41224
+ signal
41225
+ );
40818
41226
  if (!response.ok) {
40819
41227
  await response.body?.cancel();
40820
41228
  throw Error("CRM_INTENT_UNAVAILABLE");
@@ -40846,7 +41254,7 @@ function createIntentEvaluator(options) {
40846
41254
  let unavailable = false;
40847
41255
  if (binding && readyModel) {
40848
41256
  try {
40849
- const id2 = randomUUID21();
41257
+ const id2 = randomUUID22();
40850
41258
  const batch = await options.tools.execute({
40851
41259
  calls: [{ type: "tool-call", id: id2, name: "crm_get_conversation_context", arguments: JSON.stringify({ workspaceId: workspace, ...binding }) }],
40852
41260
  signal
@@ -40879,9 +41287,9 @@ function createIntentEvaluator(options) {
40879
41287
  grade = stored.grade;
40880
41288
  unavailable ||= !!stored.unavailable;
40881
41289
  }
40882
- const result = await evaluateCustomerIntent(input, { grade, profile: snapshot2?.initial, unavailable: unavailable || input.previous?.crmLookupFailed }, (system, text7) => {
41290
+ const result = await evaluateCustomerIntent(input, { grade, profile: snapshot2?.initial, unavailable: unavailable || input.previous?.crmLookupFailed }, (system, text6) => {
40883
41291
  if (!readyModel) throw Error("INTENT_FLASH_UNAVAILABLE");
40884
- return runModel(options.llm, { ...readyModel, maxTokens: 1200 }, { system, text: text7 }, AbortSignal.any([signal, AbortSignal.timeout(24e3)]));
41292
+ return runModel(options.llm, { ...readyModel, maxTokens: 1200 }, { system, text: text6 }, AbortSignal.any([signal, AbortSignal.timeout(24e3)]));
40885
41293
  });
40886
41294
  signal.throwIfAborted();
40887
41295
  result.crmChecked = input.previous?.crmChecked || !!snapshot2;
@@ -40916,10 +41324,10 @@ function applySemanticRanking(value, hits, options) {
40916
41324
  import { existsSync as existsSync3 } from "node:fs";
40917
41325
 
40918
41326
  // src/wechat/runtime.ts
40919
- import { createHash as createHash10, randomUUID as randomUUID22 } from "node:crypto";
41327
+ import { createHash as createHash10, randomUUID as randomUUID23 } from "node:crypto";
40920
41328
  import { createReadStream } from "node:fs";
40921
- import { mkdir as mkdir6, readFile as readFile13, lstat as lstat4, open as open3, rm as rm3, rename as rename6, mkdtemp, realpath as realpath3, writeFile as writeFile7 } from "node:fs/promises";
40922
- import { join as join13, basename as basename2 } from "node:path";
41329
+ import { mkdir as mkdir7, readFile as readFile13, lstat as lstat5, open as open3, rm as rm3, rename as rename6, mkdtemp, realpath as realpath3, writeFile as writeFile7 } from "node:fs/promises";
41330
+ import { join as join14, basename as basename2 } from "node:path";
40923
41331
  import { setTimeout as delay } from "node:timers/promises";
40924
41332
  import { execFile as execFile2 } from "node:child_process";
40925
41333
  import { promisify as promisify2 } from "node:util";
@@ -43913,7 +44321,7 @@ async function hashFile(file) {
43913
44321
  }
43914
44322
  async function exists(file) {
43915
44323
  try {
43916
- return await lstat4(file);
44324
+ return await lstat5(file);
43917
44325
  } catch (e) {
43918
44326
  if (e.code === "ENOENT") return void 0;
43919
44327
  throw e;
@@ -43931,6 +44339,7 @@ function checkManifest(value) {
43931
44339
  var WechatRuntime = class {
43932
44340
  options;
43933
44341
  target;
44342
+ runDiagnostic = diagnosticCallback((run) => diagnosticOperation(run));
43934
44343
  lifetime = new AbortController();
43935
44344
  pending;
43936
44345
  root;
@@ -43951,10 +44360,22 @@ var WechatRuntime = class {
43951
44360
  }
43952
44361
  ensureRoot() {
43953
44362
  if (this.closed) return Promise.reject(code3("ABORTED"));
43954
- return this.pending ??= this.install().catch((error) => {
43955
- const reason = this.closed ? "ABORTED" : error instanceof Error && /^WECHAT_RUNTIME_/.test(error.message) ? error.message.slice("WECHAT_RUNTIME_".length) : ["EPERM", "EACCES", "ENOSPC", "EIO", "EBUSY", "ENOTEMPTY", "EROFS"].includes(error?.code ?? "") ? "CACHE" : "NETWORK";
43956
- this.state = { ...this.state, phase: reason === "UNSUPPORTED" ? "unsupported" : "error", errorCode: "WECHAT_RUNTIME_" + reason };
43957
- throw code3(reason);
44363
+ return this.pending ??= this.runDiagnostic(async () => {
44364
+ const started = performance.now();
44365
+ diagnostic("wechat.runtime.install", "started");
44366
+ try {
44367
+ const root = await this.install();
44368
+ diagnostic("wechat.runtime.install", "ok", { elapsedMs: Math.round(performance.now() - started) });
44369
+ return root;
44370
+ } catch (error) {
44371
+ const reason = this.closed ? "ABORTED" : error instanceof Error && /^WECHAT_RUNTIME_/.test(error.message) ? error.message.slice("WECHAT_RUNTIME_".length) : ["EPERM", "EACCES", "ENOSPC", "EIO", "EBUSY", "ENOTEMPTY", "EROFS"].includes(error?.code ?? "") ? "CACHE" : "NETWORK";
44372
+ const failure = code3(reason);
44373
+ const stage = this.state.phase;
44374
+ diagnostic("wechat.runtime.install." + stage, this.closed ? "cancelled" : "failed", { elapsedMs: Math.round(performance.now() - started) }, failure);
44375
+ if (reason === "CACHE") diagnostic("wechat.runtime.filesystem", "failed", {}, error);
44376
+ this.state = { ...this.state, phase: reason === "UNSUPPORTED" ? "unsupported" : "error", errorCode: failure.message };
44377
+ throw failure;
44378
+ }
43958
44379
  }).finally(() => {
43959
44380
  this.pending = void 0;
43960
44381
  });
@@ -43972,8 +44393,8 @@ var WechatRuntime = class {
43972
44393
  }
43973
44394
  async cached(root, asset) {
43974
44395
  try {
43975
- if ((await lstat4(root)).isSymbolicLink() || await readFile13(join13(root, "ready.json"), "utf8") !== asset.sha256) return false;
43976
- if (await hashFile(join13(root, this.target, "component.json")) !== asset.componentSha256) return false;
44396
+ if ((await lstat5(root)).isSymbolicLink() || await readFile13(join14(root, "ready.json"), "utf8") !== asset.sha256) return false;
44397
+ if (await hashFile(join14(root, this.target, "component.json")) !== asset.componentSha256) return false;
43977
44398
  await verifyComponent(root, ...this.target.split("-"));
43978
44399
  return true;
43979
44400
  } catch {
@@ -43981,6 +44402,7 @@ var WechatRuntime = class {
43981
44402
  }
43982
44403
  }
43983
44404
  phase(phase, patch = {}) {
44405
+ if (phase !== this.state.phase) diagnostic("wechat.runtime." + phase, phase === "ready" ? "ok" : "started", { bytes: patch.received });
43984
44406
  this.state = { ...this.state, ...patch, phase, errorCode: void 0 };
43985
44407
  }
43986
44408
  async install() {
@@ -43995,9 +44417,9 @@ var WechatRuntime = class {
43995
44417
  const asset = manifest.targets[this.target];
43996
44418
  if (!asset) throw code3("UNSUPPORTED");
43997
44419
  this.phase("checking", { received: 0, total: asset.bytes });
43998
- await mkdir6(this.options.cacheDir, { recursive: true, mode: 448 });
44420
+ await mkdir7(this.options.cacheDir, { recursive: true, mode: 448 });
43999
44421
  const base = await realpath3(this.options.cacheDir);
44000
- const root = join13(base, this.target + "-" + asset.sha256.slice(0, 16)), lock = join13(base, asset.sha256 + ".lock"), part = join13(base, asset.sha256 + ".part");
44422
+ const root = join14(base, this.target + "-" + asset.sha256.slice(0, 16)), lock = join14(base, asset.sha256 + ".lock"), part = join14(base, asset.sha256 + ".part");
44001
44423
  const mac = this.target.startsWith("darwin-");
44002
44424
  const signal = AbortSignal.any([this.lifetime.signal, AbortSignal.timeout(this.options.timeoutMs ?? (mac ? 18e4 : 12e4))]);
44003
44425
  const ready = () => {
@@ -44012,7 +44434,7 @@ var WechatRuntime = class {
44012
44434
  if (await this.cached(root, asset)) return ready();
44013
44435
  try {
44014
44436
  handle = await open3(lock, "wx", 384);
44015
- owner = JSON.stringify({ pid: process.pid, token: randomUUID22() });
44437
+ owner = JSON.stringify({ pid: process.pid, token: randomUUID23() });
44016
44438
  await handle.writeFile(owner);
44017
44439
  } catch (e) {
44018
44440
  if (e.code !== "EEXIST") throw e;
@@ -44047,8 +44469,8 @@ var WechatRuntime = class {
44047
44469
  }
44048
44470
  if (await this.cached(root, asset)) return ready();
44049
44471
  if (await exists(root)) {
44050
- if ((await lstat4(root)).isSymbolicLink()) throw code3("CACHE");
44051
- await rename6(root, root + "-invalid-" + randomUUID22());
44472
+ if ((await lstat5(root)).isSymbolicLink()) throw code3("CACHE");
44473
+ await rename6(root, root + "-invalid-" + randomUUID23());
44052
44474
  }
44053
44475
  await this.download(part, asset, signal);
44054
44476
  signal.throwIfAborted();
@@ -44057,12 +44479,12 @@ var WechatRuntime = class {
44057
44479
  await rm3(part, { force: true });
44058
44480
  throw code3("CHECKSUM");
44059
44481
  }
44060
- const stage = await mkdtemp(join13(base, "stage-"));
44482
+ const stage = await mkdtemp(join14(base, "stage-"));
44061
44483
  try {
44062
44484
  this.phase("extracting");
44063
44485
  await this.unpack(part, stage, asset);
44064
44486
  signal.throwIfAborted();
44065
- if (await hashFile(join13(stage, this.target, "component.json")) !== asset.componentSha256) throw code3("COMPONENT");
44487
+ if (await hashFile(join14(stage, this.target, "component.json")) !== asset.componentSha256) throw code3("COMPONENT");
44066
44488
  let verified;
44067
44489
  try {
44068
44490
  verified = await verifyComponent(stage, ...this.target.split("-"));
@@ -44070,15 +44492,16 @@ var WechatRuntime = class {
44070
44492
  throw code3("COMPONENT");
44071
44493
  }
44072
44494
  await rename6(stage, root);
44073
- const nativeDir = join13(root, this.target);
44495
+ const nativeDir = join14(root, this.target);
44074
44496
  this.phase("self-test");
44075
44497
  const deadline = AbortSignal.timeout(mac ? 6e4 : 1e4);
44076
44498
  const selfTestSignal = AbortSignal.any([signal, deadline]);
44077
44499
  try {
44078
44500
  if (this.options.selfTest) await this.options.selfTest(nativeDir, selfTestSignal);
44079
- else await promisify2(execFile2)(join13(nativeDir, this.target.startsWith("win32-") ? "DSHWechatWorker.exe" : "DSHWechatWorker"), ["--self-test"], { cwd: nativeDir, signal: selfTestSignal, windowsHide: true, maxBuffer: 65536 });
44501
+ else await promisify2(execFile2)(join14(nativeDir, this.target.startsWith("win32-") ? "DSHWechatWorker.exe" : "DSHWechatWorker"), ["--self-test"], { cwd: nativeDir, signal: selfTestSignal, windowsHide: true, maxBuffer: 65536 });
44080
44502
  selfTestSignal.throwIfAborted();
44081
- } catch {
44503
+ } catch (error) {
44504
+ diagnostic("wechat.runtime.worker-exit", "failed", {}, error);
44082
44505
  signal.throwIfAborted();
44083
44506
  throw code3(deadline.aborted ? "SELF_TEST_TIMEOUT" : "SELF_TEST");
44084
44507
  }
@@ -44088,8 +44511,8 @@ var WechatRuntime = class {
44088
44511
  } catch {
44089
44512
  throw code3("COMPONENT");
44090
44513
  }
44091
- await writeFile7(join13(root, "ready.tmp"), asset.sha256, { mode: 384 });
44092
- await rename6(join13(root, "ready.tmp"), join13(root, "ready.json"));
44514
+ await writeFile7(join14(root, "ready.tmp"), asset.sha256, { mode: 384 });
44515
+ await rename6(join14(root, "ready.tmp"), join14(root, "ready.json"));
44093
44516
  } finally {
44094
44517
  await rm3(stage, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 });
44095
44518
  }
@@ -44119,7 +44542,8 @@ var WechatRuntime = class {
44119
44542
  let response;
44120
44543
  for (let hop = 0; hop < 6; hop++) {
44121
44544
  runtimeBaseUrl(url);
44122
- response = await fetch(url, { headers: { "Accept-Encoding": "identity", ...offset ? { Range: `bytes=${offset}-` } : {} }, redirect: "manual", signal });
44545
+ const locationUrl = url;
44546
+ response = await diagnosticHttp("wechat.runtime.http", () => fetch(locationUrl, { headers: { "Accept-Encoding": "identity", ...offset ? { Range: `bytes=${offset}-` } : {} }, redirect: "manual", signal }), signal);
44123
44547
  if ([301, 302, 303, 307, 308].includes(response.status)) {
44124
44548
  const location = response.headers.get("location");
44125
44549
  await response.body?.cancel();
@@ -44201,6 +44625,13 @@ var WechatRuntime = class {
44201
44625
 
44202
44626
  // src/company/identity.ts
44203
44627
  var COMPANY_IDENTITY_ENDPOINT = "wanji-sales-company/identity";
44628
+ var COMPANY_LOGIN_PATH = "/api/v1/sales-company/device/login";
44629
+ function isDingTalkLaunchUrl(url) {
44630
+ if (url.protocol !== "https:" || url.username || url.password || url.search || url.pathname !== COMPANY_LOGIN_PATH) return false;
44631
+ const fields5 = new URLSearchParams(url.hash.slice(1));
44632
+ const valid = /^[A-Za-z0-9_-]{43}$/u;
44633
+ return fields5.size === 2 && valid.test(fields5.get("device") ?? "") && valid.test(fields5.get("ticket") ?? "");
44634
+ }
44204
44635
  var COMPANY_FLASH = { provider: "wanji-sales-company-flash", model: "deepseek-v4.1-flash" };
44205
44636
 
44206
44637
  // src/company/remote.ts
@@ -44260,14 +44691,14 @@ function createCompanyConnection({ credentials, settings, fetch: request2 = fetc
44260
44691
  return credential.value;
44261
44692
  }
44262
44693
  function send(path3, signal, secret, hint) {
44263
- return request2(COMPANY_ORIGIN + ROOT + "/device/" + path3, {
44694
+ return diagnosticHttp("dingtalk.http." + path3, () => request2(COMPANY_ORIGIN + ROOT + "/device/" + path3, {
44264
44695
  method: "POST",
44265
44696
  signal,
44266
44697
  redirect: "error",
44267
44698
  credentials: "omit",
44268
44699
  headers: { ...secret ? { Authorization: "Bearer " + secret } : {}, ...hint ? { "Content-Type": "application/json" } : {} },
44269
44700
  ...hint ? { body: JSON.stringify(hint) } : {}
44270
- });
44701
+ }), signal);
44271
44702
  }
44272
44703
  async function revoke(secret, signal) {
44273
44704
  const response = await send("unbind", signal, secret);
@@ -44282,6 +44713,7 @@ function createCompanyConnection({ credentials, settings, fetch: request2 = fetc
44282
44713
  refresh: (signal) => ordered(signal, async () => {
44283
44714
  const secret = await token();
44284
44715
  if (!secret) {
44716
+ diagnostic("dingtalk.device-credential", "unavailable");
44285
44717
  verified = false;
44286
44718
  pending = void 0;
44287
44719
  return { status: "unbound" };
@@ -44308,7 +44740,7 @@ function createCompanyConnection({ credentials, settings, fetch: request2 = fetc
44308
44740
  }
44309
44741
  if (value?.status !== "bound" || typeof value.alias !== "string") throw Error("invalid company profile");
44310
44742
  verified = true;
44311
- if (!ready()) await ensureRoute().catch(() => void 0);
44743
+ if (!ready()) await ensureRoute().then(() => diagnostic("dingtalk.model-route", "ok"), (error) => diagnostic("dingtalk.model-route", "failed", {}, error));
44312
44744
  return {
44313
44745
  status: "bound",
44314
44746
  alias: value.alias,
@@ -44319,20 +44751,24 @@ function createCompanyConnection({ credentials, settings, fetch: request2 = fetc
44319
44751
  begin: (hint, signal) => ordered(signal, async () => {
44320
44752
  const previous = await token();
44321
44753
  if (previous) await revoke(previous, signal);
44322
- const response = await send("start", signal, void 0, hint);
44754
+ const response = await send("start", signal, void 0, { ...hint, flow: "oauth" });
44323
44755
  if (!response.ok) throw Error("company binding unavailable");
44324
44756
  const value = object5(await response.json());
44325
- if (value?.status !== "awaiting" || typeof value.token !== "string" || !tokenPattern.test(value.token) || typeof value.authorizeUrl !== "string" || typeof value.verificationCode !== "string" || !/^\d{8}$/u.test(value.verificationCode)) {
44757
+ if (value?.status !== "awaiting" || typeof value.token !== "string" || !tokenPattern.test(value.token) || typeof value.authorizeUrl !== "string") {
44326
44758
  throw Error("invalid company challenge");
44327
44759
  }
44328
44760
  const url = new URL(value.authorizeUrl);
44329
- if (url.origin !== COMPANY_ORIGIN || url.username || url.password || url.hash || url.pathname !== ROOT + "/device/verify" || !tokenPattern.test(url.searchParams.get("device") ?? "")) {
44761
+ const code4 = value.verificationCode;
44762
+ const oneClick = isDingTalkLaunchUrl(url) && code4 === void 0;
44763
+ const legacy = !url.hash && url.pathname === ROOT + "/device/verify" && url.searchParams.size === 1 && tokenPattern.test(url.searchParams.get("device") ?? "") && typeof code4 === "string" && /^\d{8}$/u.test(code4);
44764
+ if (url.origin !== COMPANY_ORIGIN || url.username || url.password || !(oneClick || legacy)) {
44330
44765
  throw Error("invalid company verification URL");
44331
44766
  }
44332
44767
  signal.throwIfAborted();
44333
44768
  await credentials.set(CREDENTIAL, value.token);
44334
44769
  verified = false;
44335
- pending = { status: "awaiting", authorizeUrl: url.href, verificationCode: value.verificationCode };
44770
+ diagnostic(oneClick ? "dingtalk.oauth-challenge" : "dingtalk.legacy-challenge", "ok");
44771
+ pending = { status: "awaiting", authorizeUrl: url.href, ...legacy ? { verificationCode: code4 } : {} };
44336
44772
  return pending;
44337
44773
  }),
44338
44774
  unbind: (signal) => ordered(signal, async () => {
@@ -44373,7 +44809,7 @@ function safeView(identity, service, ready) {
44373
44809
  }
44374
44810
  case "awaiting": {
44375
44811
  const url = new URL(identity.authorizeUrl);
44376
- if (url.protocol !== "https:" || url.username || url.password || url.hash || url.origin !== service.authorizeOrigin || url.href.length > 2048) {
44812
+ if (url.protocol !== "https:" || url.username || url.password || url.hash && !isDingTalkLaunchUrl(url) || url.origin !== service.authorizeOrigin || url.href.length > 2048) {
44377
44813
  throw Error("unsafe authorization URL");
44378
44814
  }
44379
44815
  const verificationCode = identity.verificationCode;
@@ -44391,7 +44827,7 @@ function safeView(identity, service, ready) {
44391
44827
  async function readAccountPhone(account) {
44392
44828
  if (typeof account?.getProfile !== "function") return;
44393
44829
  const result = await account.getProfile({
44394
- version: true ? "0.11.1" : "0.0.0",
44830
+ version: true ? "0.11.3" : "0.0.0",
44395
44831
  locale: Intl.DateTimeFormat().resolvedOptions().locale,
44396
44832
  timezoneOffsetSeconds: -(/* @__PURE__ */ new Date()).getTimezoneOffset() * 60
44397
44833
  });
@@ -44421,34 +44857,51 @@ function registerCompanyIdentityRoute(ctx, findService, modelReady, account) {
44421
44857
  async fetch(request2) {
44422
44858
  let rpcId, action;
44423
44859
  try {
44424
- const text7 = await request2.text();
44425
- if (text7.length > 4096) throw Error("request too large");
44426
- const body = JSON.parse(text7);
44860
+ const text6 = await request2.text();
44861
+ if (text6.length > 4096) throw Error("request too large");
44862
+ const body = JSON.parse(text6);
44427
44863
  if (!object6(body) || !fields4(body, ["type", "method", "rpcId", "payload"]) || body.type !== "client-request" || body.method !== COMPANY_IDENTITY_ENDPOINT || typeof body.rpcId !== "string" || body.rpcId.length > 128) throw Error("invalid envelope");
44428
44864
  rpcId = body.rpcId;
44429
44865
  action = parseOperation(body.payload);
44430
44866
  } catch {
44431
44867
  return Response.json({ error: "bad-request" }, { status: 400 });
44432
44868
  }
44869
+ const operation = "dingtalk." + action.operation;
44870
+ const started = performance.now();
44433
44871
  const reply = (result) => Response.json({ type: "server-response", rpcId, result }, { headers: { "Cache-Control": "no-store" } });
44434
44872
  try {
44435
44873
  const service = findService();
44436
- if (!service) return reply({ ok: true, value: { status: "unavailable" } });
44874
+ if (!service) {
44875
+ diagnostic(operation, "unavailable");
44876
+ return reply({ ok: true, value: { status: "unavailable" } });
44877
+ }
44437
44878
  const signal = AbortSignal.any([request2.signal, AbortSignal.timeout(1e4)]);
44438
44879
  signal.throwIfAborted();
44439
44880
  if (action.operation === "account-phone") {
44440
- const phone2 = await readAccountPhone(account?.()).catch(() => void 0);
44881
+ const phone2 = await readAccountPhone(account?.()).catch((error) => {
44882
+ diagnostic(operation, "failed", {}, error);
44883
+ return void 0;
44884
+ });
44441
44885
  signal.throwIfAborted();
44886
+ diagnostic(operation, phone2 ? "ok" : "unavailable");
44442
44887
  return reply({ ok: true, value: { status: "account-phone", ...phone2 ? { phone: phone2 } : {} } });
44443
44888
  }
44444
44889
  if (action.operation === "unbind") {
44445
44890
  await service.unbind(signal);
44446
44891
  if (service.canUseSharedModel()) throw Error("company grant is still active");
44892
+ diagnostic(operation, "ok", { elapsedMs: Math.round(performance.now() - started) });
44447
44893
  return reply({ ok: true, value: { status: "unbound" } });
44448
44894
  }
44449
44895
  const view = action.operation === "bind" ? await service.begin(action.hint, signal) : await service.refresh(signal);
44450
- return reply({ ok: true, value: safeView(view, service, modelReady()) });
44451
- } catch {
44896
+ const value = safeView(view, service, modelReady());
44897
+ diagnostic(
44898
+ operation + "." + value.status,
44899
+ value.status === "awaiting" ? "pending" : value.status === "unavailable" ? "unavailable" : "ok",
44900
+ { elapsedMs: Math.round(performance.now() - started), enabled: value.status === "bound" && value.modelReady }
44901
+ );
44902
+ return reply({ ok: true, value });
44903
+ } catch (error) {
44904
+ diagnostic(operation, request2.signal.aborted ? "cancelled" : "failed", { elapsedMs: Math.round(performance.now() - started) }, error);
44452
44905
  return reply({ ok: false, error: { code: "company-identity-unavailable" } });
44453
44906
  }
44454
44907
  }
@@ -44465,14 +44918,14 @@ var retrievalConnection = Schema.union([Schema.const(void 0), Schema.object({
44465
44918
  tenantId: Schema.string()
44466
44919
  })]);
44467
44920
  var knowledgeSettings = Schema.object({
44468
- materialRetrievalEnabled: Schema.boolean().description("Enable independent customer material retrieval in the configured test workspace."),
44921
+ materialRetrievalEnabled: Schema.boolean().description("Enable retrieval from the configured customer material knowledge base."),
44469
44922
  materialKnowledgeBaseIds: Schema.array(Schema.string()).description("Separate customer material knowledge base scope."),
44470
44923
  materialToolPrefix: Schema.string().description("Separate WeKnora tool instance for customer videos and documents."),
44471
44924
  evaluationKnowledgeIds: Schema.union([Schema.array(Schema.string()), Schema.const(void 0)]).default(void 0).description("Optional frozen document IDs for test-only evaluation; excludes newly added knowledge before retrieval."),
44472
44925
  evaluationMaterialIds: Schema.union([Schema.array(Schema.string()), Schema.const(void 0)]).default(void 0).description("Optional frozen material IDs for test-only evaluation; ordinary retrieval remains dynamic when omitted."),
44473
44926
  semanticRerank: Schema.boolean().description("Optional Flash semantic reranking of up to eight scoped retrieval candidates; keeps original evidence on ranking failure."),
44474
- salesQuestionTracing: Schema.boolean().description("Sync sales questions and answers in the supported test profile unless disabled."),
44475
- agentKnowledgeTracing: Schema.boolean().description("Opt-in passive Agent knowledge tracing; currently limited to the test knowledge base."),
44927
+ salesQuestionTracing: Schema.boolean().description("Sync redacted sales questions and answers. Production requires explicit opt-in and a private Langfuse configuration."),
44928
+ agentKnowledgeTracing: Schema.boolean().description("Opt-in tracking for scoped sales and material knowledge calls. Production requires a private Langfuse configuration."),
44476
44929
  environment: Schema.union(["test", "production"]).description("Knowledge evaluation environment; production disables test operations."),
44477
44930
  knowledgeTestEnabled: Schema.boolean().description("Knowledge test switch; the existing allowlist still applies."),
44478
44931
  draftKnowledgeEnabled: Schema.boolean().description("Permit scoped reply retrieval independently of knowledge evaluation."),
@@ -44508,10 +44961,12 @@ function resolveConfig2(raw) {
44508
44961
  if (Object.keys(input).some((key) => !allowed2.has(key))) throw new ProfileError("INVALID_CONFIG", "Unknown sales plugin setting");
44509
44962
  const profile3 = resolveConfig({ ...pick2(input, profileKeys), requestTimeoutMs: input.crmRequestTimeoutMs });
44510
44963
  const knowledgeInput = pick2(input, knowledgeKeys);
44964
+ const defaultBaseUrl = input.environment === "production" && Array.isArray(input.knowledgeBaseIds) && input.knowledgeBaseIds.length ? PRODUCTION_WEKNORA_BASE_URL : void 0;
44511
44965
  for (const key of ["knowledgeConnection", "materialConnection"]) {
44512
44966
  try {
44513
- knowledgeInput[key] = resolveWeKnoraConnection(knowledgeInput[key], key);
44967
+ knowledgeInput[key] = resolveWeKnoraConnection(knowledgeInput[key], key, defaultBaseUrl);
44514
44968
  } catch {
44969
+ withDiagnostics(() => diagnostic(key === "knowledgeConnection" ? "knowledge.config" : "materials.config", "failed", {}, new Error("INVALID_CONFIG")));
44515
44970
  delete knowledgeInput[key];
44516
44971
  }
44517
44972
  }
@@ -44519,7 +44974,7 @@ function resolveConfig2(raw) {
44519
44974
  delete knowledgeInput.draftKnowledgeEnabled;
44520
44975
  }
44521
44976
  const knowledge = resolveKnowledgeConfig(knowledgeInput);
44522
- if (input.wechatComponentRoot !== void 0 && (typeof input.wechatComponentRoot !== "string" || !isAbsolute5(input.wechatComponentRoot))) throw new ProfileError("INVALID_CONFIG", "wechatComponentRoot must be absolute");
44977
+ if (input.wechatComponentRoot !== void 0 && (typeof input.wechatComponentRoot !== "string" || !isAbsolute7(input.wechatComponentRoot))) throw new ProfileError("INVALID_CONFIG", "wechatComponentRoot must be absolute");
44523
44978
  let baseUrl;
44524
44979
  if (input.wechatRuntimeBaseUrl !== void 0) {
44525
44980
  try {
@@ -44543,13 +44998,32 @@ var Config2 = Schema.transform(Schema.intersect([
44543
44998
  try {
44544
44999
  return resolveConfig2(value);
44545
45000
  } catch (error) {
45001
+ withDiagnostics(() => diagnostic("host.config", "failed", {}, error));
44546
45002
  throw new Schema.ValidationError(error instanceof Error ? error.message : "Invalid sales configuration", options);
44547
45003
  }
44548
45004
  }, true);
44549
45005
  var name = "wanji-sales";
44550
45006
  var inject = ["tools", "llm"];
44551
45007
  function apply3(ctx, rawConfig = {}) {
45008
+ withDiagnostics(() => {
45009
+ diagnostic("host.activation", "started");
45010
+ try {
45011
+ activate(ctx, rawConfig);
45012
+ diagnostic("host.activation", "ok");
45013
+ } catch (error) {
45014
+ diagnostic("host.activation", "failed", {}, error);
45015
+ throw error;
45016
+ }
45017
+ });
45018
+ }
45019
+ function activate(ctx, rawConfig) {
44552
45020
  const config = Config2(rawConfig);
45021
+ diagnostic(
45022
+ "knowledge.config",
45023
+ config.knowledgeBaseIds.length ? "ok" : "unavailable",
45024
+ { count: config.knowledgeBaseIds.length, configured: Boolean(config.knowledgeConnection), enabled: config.draftKnowledgeEnabled }
45025
+ );
45026
+ diagnostic("langfuse.config", "ok", { configured: Boolean(config.langfuseConfigFile), enabled: config.salesQuestionTracing || config.agentKnowledgeTracing });
44553
45027
  const profile3 = { ...pick2(config, profileKeys), requestTimeoutMs: config.crmRequestTimeoutMs };
44554
45028
  const activity = new UpdateActivity();
44555
45029
  apply(guardSalesActivity(ctx, activity), profile3);
@@ -44557,6 +45031,37 @@ function apply3(ctx, rawConfig = {}) {
44557
45031
  const skills = child.skills;
44558
45032
  if (skills) child.effect(() => registerBundledSalesSkill(skills));
44559
45033
  });
45034
+ if (ctx.on) {
45035
+ const operations = /* @__PURE__ */ new Map();
45036
+ for (const [prefix, service] of [[config.toolPrefix, "knowledge"], [config.materialToolPrefix ?? config.toolPrefix, "materials"]]) {
45037
+ for (const suffix of ["list_knowledge_bases", "search", "read_document", "ask"]) {
45038
+ const name2 = prefix + "_" + suffix;
45039
+ if (!operations.has(name2)) operations.set(name2, "mcp." + service + "." + suffix);
45040
+ }
45041
+ }
45042
+ const observe = diagnosticCallback((operation, exec, next) => diagnosticOperation(async () => {
45043
+ const started = performance.now();
45044
+ diagnostic(operation, "started");
45045
+ try {
45046
+ const result = await next();
45047
+ diagnostic(
45048
+ operation,
45049
+ result.isError ? exec.signal.aborted ? "cancelled" : "failed" : "ok",
45050
+ { elapsedMs: Math.round(performance.now() - started) },
45051
+ result.isError ? { code: result.error?.info?.code } : void 0
45052
+ );
45053
+ return result;
45054
+ } catch (error) {
45055
+ diagnostic(operation, exec.signal.aborted ? "cancelled" : "failed", { elapsedMs: Math.round(performance.now() - started) }, error);
45056
+ throw error;
45057
+ }
45058
+ }));
45059
+ const off = ctx.on("tools/execute", (exec, next) => {
45060
+ const operation = operations.get(exec.name);
45061
+ return exec.agent && operation ? observe(operation, exec, next) : next();
45062
+ });
45063
+ ctx.effect(() => off);
45064
+ }
44560
45065
  const materialAssetBaseUrl = config.materialAssetBaseUrl;
44561
45066
  if (materialAssetBaseUrl && ctx.on) {
44562
45067
  const rawTools = new Set(["search", "read_document", "ask"].map((suffix) => config.toolPrefix + "_" + suffix));
@@ -44575,17 +45080,19 @@ function apply3(ctx, rawConfig = {}) {
44575
45080
  if (config.agentKnowledgeTracing && config.langfuseConfigFile && ctx.on) {
44576
45081
  const active = new AgentKnowledgeObserver({
44577
45082
  configFile: config.langfuseConfigFile,
44578
- directory: join14(homedir6(), ".local", "state", "wanji-sales", "langfuse-agent"),
45083
+ environment: config.environment,
45084
+ directory: join15(homedir7(), ".local", "state", "wanji-sales", config.environment === "production" ? "langfuse-agent-production" : "langfuse-agent"),
44579
45085
  knowledgeBaseId: config.knowledgeBaseIds[0],
44580
45086
  toolPrefix: config.toolPrefix,
44581
45087
  ...tracedMaterialId ? { material: { knowledgeBaseId: tracedMaterialId, toolPrefix: config.materialToolPrefix ?? config.toolPrefix } } : {}
44582
45088
  });
44583
45089
  observer = active;
45090
+ const start = diagnosticCallback(active.start.bind(active));
44584
45091
  const offExecute = ctx.on("tools/execute", async (exec, next) => {
44585
- await active.start(exec);
45092
+ await start(exec);
44586
45093
  return next();
44587
45094
  });
44588
- const offResult = ctx.on("tools/result", (exec, result) => active.finish(exec, result));
45095
+ const offResult = ctx.on("tools/result", diagnosticCallback((exec, result) => active.finish(exec, result)));
44589
45096
  ctx.effect(() => async () => {
44590
45097
  offExecute();
44591
45098
  offResult();
@@ -44593,24 +45100,25 @@ function apply3(ctx, rawConfig = {}) {
44593
45100
  });
44594
45101
  }
44595
45102
  const questions = config.salesQuestionTracing ? new SalesQuestionObserver({
44596
- ...config.langfuseConfigFile ? { configFile: config.langfuseConfigFile } : {
45103
+ ...config.langfuseConfigFile ? { configFile: config.langfuseConfigFile, environment: config.environment } : {
44597
45104
  relay: (event, signal) => sendManagedQuestion(ctx.get?.("wanjiSalesQuestionRelay"), config.toolPrefix, event, signal)
44598
45105
  },
44599
- directory: join14(config.storageDir, config.langfuseConfigFile ? "langfuse-questions" : "langfuse-managed-questions"),
45106
+ directory: join15(config.storageDir, config.environment === "production" ? "langfuse-production-questions" : config.langfuseConfigFile ? "langfuse-questions" : "langfuse-managed-questions"),
44600
45107
  knowledgeBaseId: config.knowledgeBaseIds[0],
44601
45108
  toolPrefix: config.toolPrefix
44602
45109
  }) : void 0;
44603
45110
  if (questions || observer) {
44604
- const off = ctx.on?.("session/event", (session, event) => {
45111
+ const off = ctx.on?.("session/event", diagnosticCallback((session, event) => {
44605
45112
  const recorded = observer?.sessionEvent(session.id, event) === true;
44606
45113
  questions?.observe(session, event, recorded);
44607
- });
45114
+ }));
44608
45115
  ctx.effect(() => async () => {
44609
45116
  off?.();
44610
45117
  await questions?.close();
44611
45118
  });
44612
45119
  }
44613
- ctx.inject(["connection", "workspaceRegistry"], (rawChild) => {
45120
+ ctx.inject(["connection", "workspaceRegistry"], diagnosticCallback((rawChild) => {
45121
+ diagnostic("host.web-services", "started");
44614
45122
  const child = guardSalesActivity(rawChild, activity);
44615
45123
  const optional = child;
44616
45124
  const configuredModel = config.modelProvider && config.model ? { provider: config.modelProvider, model: config.model } : void 0;
@@ -44633,7 +45141,11 @@ function apply3(ctx, rawConfig = {}) {
44633
45141
  );
44634
45142
  const companyStartup = new AbortController();
44635
45143
  child.effect(() => () => companyStartup.abort());
44636
- if (!suppliedIdentity()) void managed()?.identity.refresh(AbortSignal.any([companyStartup.signal, AbortSignal.timeout(1e4)])).catch(() => void 0);
45144
+ if (!suppliedIdentity()) {
45145
+ const connection = managed();
45146
+ if (!connection) diagnostic("dingtalk.device-service", "unavailable");
45147
+ else void diagnosticOperation(() => connection.identity.refresh(AbortSignal.any([companyStartup.signal, AbortSignal.timeout(1e4)]))).catch((error) => diagnostic("dingtalk.startup-status", companyStartup.signal.aborted ? "cancelled" : "failed", {}, error));
45148
+ }
44637
45149
  apply2(child, pick2(config, knowledgeKeys), async () => observer ? observer.status() : { enabled: false, pending: 0, otherPending: 0, blocked: 0, unfinished: 0, inFlight: 0, dropped: 0, ...config.agentKnowledgeTracing ? { errorCode: "observer-not-configured" } : {} }, async (query, hits, signal, options) => {
44638
45150
  const selected = salesModel();
44639
45151
  if (!selected?.provider || selected.model !== "deepseek-v4.1-flash") throw Error("RERANK_FLASH_UNAVAILABLE");
@@ -44644,7 +45156,7 @@ function apply3(ctx, rawConfig = {}) {
44644
45156
  if (!selected?.provider || selected.model !== "deepseek-v4.1-flash") throw Error("QUERY_FLASH_UNAVAILABLE");
44645
45157
  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);
44646
45158
  return parseQueryExpansion(value);
44647
- }, questions?.finish.bind(questions), observer && tracedMaterialId ? (startedAt, elapsedMs, status) => observer?.recordMaterialMetadata(tracedMaterialId, startedAt, elapsedMs, status) : void 0);
45159
+ }, questions?.finish.bind(questions), observer && tracedMaterialId ? (startedAt, elapsedMs, status) => observer?.recordMaterialMetadata(tracedMaterialId, startedAt, elapsedMs, status) : void 0, observer);
44648
45160
  registerQuestionRoute(child, questions);
44649
45161
  let generationRuntime;
44650
45162
  child.effect(() => async () => {
@@ -44662,18 +45174,18 @@ function apply3(ctx, rawConfig = {}) {
44662
45174
  });
44663
45175
  registerConversationRoute(child);
44664
45176
  registerJournalRoute(child, config.storageDir);
44665
- const services = () => optional.get?.("computerUse")?.providerName && optional.get?.("agents") && optional.get?.("agentPresets") ? { agents: optional.get("agents"), mountPreset: async (scope) => {
44666
- await optional.get?.("agentPresets").mount(scope, "ptc");
44667
- }, registerApproval: (scope, answer) => {
44668
- scope.on("user-questions/request", answer, { prepend: true });
45177
+ const services = () => optional.get?.("computerUse")?.providerName && optional.get?.("agents") && optional.get?.("agentPresets") ? { agents: optional.get("agents"), mountPreset: async (scope2) => {
45178
+ await optional.get?.("agentPresets").mount(scope2, "ptc");
45179
+ }, registerApproval: (scope2, answer) => {
45180
+ scope2.on("user-questions/request", answer, { prepend: true });
44669
45181
  }, tools: child.tools } : void 0;
44670
45182
  const visualServices = () => {
44671
45183
  const base = services();
44672
45184
  if (!base) return;
44673
45185
  return { ...base, readScreen: async (screenshot, signal) => {
44674
- if (typeof screenshot?.path !== "string" || !isAbsolute5(screenshot.path) || typeof screenshot.attachmentId !== "string" || !Number.isInteger(screenshot.width) || !Number.isInteger(screenshot.height) || (await stat3(screenshot.path)).size > 16 * 1024 * 1024) throw Error("WECHAT_OCR_IMAGE_INVALID");
45186
+ if (typeof screenshot?.path !== "string" || !isAbsolute7(screenshot.path) || typeof screenshot.attachmentId !== "string" || !Number.isInteger(screenshot.width) || !Number.isInteger(screenshot.height) || (await stat3(screenshot.path)).size > 16 * 1024 * 1024) throw Error("WECHAT_OCR_IMAGE_INVALID");
44675
45187
  const data = await readFile14(screenshot.path, { signal });
44676
- const screen = await recognizeWechatScreen(join14(dirname4(fileURLToPath4(import.meta.url)), "..", "runtime", `wechat-ocr-${process.arch}`), data, signal);
45188
+ const screen = await recognizeWechatScreen(join15(dirname4(fileURLToPath4(import.meta.url)), "..", "runtime", `wechat-ocr-${process.arch}`), data, signal);
44677
45189
  if (screen.width !== screenshot.width || screen.height !== screenshot.height) throw Error("WECHAT_OCR_COORDINATE_MISMATCH");
44678
45190
  return screen;
44679
45191
  } };
@@ -44690,9 +45202,9 @@ function apply3(ctx, rawConfig = {}) {
44690
45202
  } };
44691
45203
  };
44692
45204
  const sender = new DshWechatSender(diagnosticServices);
44693
- const componentRoot = config.wechatComponentRoot ?? join14(dirname4(fileURLToPath4(import.meta.url)), "..", "runtime", "wechat");
44694
- const bundled = existsSync3(join14(componentRoot, `${process.platform}-${process.arch}`, "component.json"));
44695
- const runtime2 = config.wechatComponentRoot || bundled ? void 0 : new WechatRuntime({ manifest: join14(componentRoot, "..", "wechat-manifest.json"), cacheDir: join14(config.storageDir, "wechat-runtime"), baseUrl: config.wechatRuntimeBaseUrl, autoStart: false });
45205
+ const componentRoot = config.wechatComponentRoot ?? join15(dirname4(fileURLToPath4(import.meta.url)), "..", "runtime", "wechat");
45206
+ const bundled = existsSync3(join15(componentRoot, `${process.platform}-${process.arch}`, "component.json"));
45207
+ const runtime2 = config.wechatComponentRoot || bundled ? void 0 : new WechatRuntime({ manifest: join15(componentRoot, "..", "wechat-manifest.json"), cacheDir: join15(config.storageDir, "wechat-runtime"), baseUrl: config.wechatRuntimeBaseUrl, autoStart: false });
44696
45208
  const intentEvaluator = createIntentEvaluator({
44697
45209
  tools: child.tools,
44698
45210
  llm: ctx.llm,
@@ -44707,8 +45219,10 @@ function apply3(ctx, rawConfig = {}) {
44707
45219
  return (await speech.transcribe(spec, signal)).text;
44708
45220
  } }, void 0, { available: () => !!services(), sender });
44709
45221
  mountUpdates(rawChild, config.storageDir, activity, sync);
45222
+ diagnostic("wechat.component-source", "ok", { configured: Boolean(config.wechatComponentRoot), enabled: !runtime2 });
44710
45223
  runtime2?.retry();
44711
- });
45224
+ diagnostic("host.web-services", "ok");
45225
+ }));
44712
45226
  }
44713
45227
  export {
44714
45228
  Config2 as Config,