@authinex/dsh-plugin 0.3.10 → 0.3.12

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.
Files changed (4) hide show
  1. package/README.md +64 -48
  2. package/lib/client.js +235 -141
  3. package/lib/index.js +768 -112
  4. package/package.json +2 -2
package/lib/index.js CHANGED
@@ -83,6 +83,12 @@ function attachOptionalHosts(ctx, bridge) {
83
83
  input: { hint: "云枢 8.7 某客户 要问的问题,或「清空」" },
84
84
  handler: (invocation) => bridge.runContextCommand(invocation.rawInput)
85
85
  }));
86
+ keep(ctx, "authinex-ds: deep-command", () => service.register({
87
+ name: "ax-deep",
88
+ description: "深度分析开关:开启后每轮先查源码核实再作答(更慢,证据更全);关闭恢复按问题复杂度自动选工具",
89
+ input: { hint: "开 / 关,留空查看当前状态" },
90
+ handler: (invocation) => bridge.runDeepCommand(invocation.rawInput)
91
+ }));
86
92
  }
87
93
  }
88
94
 
@@ -90,23 +96,23 @@ function attachOptionalHosts(ctx, bridge) {
90
96
  import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
91
97
  import { homedir } from "node:os";
92
98
  import { dirname, join } from "node:path";
93
- function deviceFileAt(path2) {
99
+ function deviceFileAt(path3) {
94
100
  return {
95
101
  async read() {
96
102
  try {
97
- const text2 = await readFile(path2, "utf8");
98
- return text2.trim() ? text2 : void 0;
103
+ const text3 = await readFile(path3, "utf8");
104
+ return text3.trim() ? text3 : void 0;
99
105
  } catch {
100
106
  return void 0;
101
107
  }
102
108
  },
103
109
  async write(value) {
104
- await mkdir(dirname(path2), { recursive: true, mode: 448 });
105
- await writeFile(path2, value, { mode: 384 });
106
- await chmod(path2, 384);
110
+ await mkdir(dirname(path3), { recursive: true, mode: 448 });
111
+ await writeFile(path3, value, { mode: 384 });
112
+ await chmod(path3, 384);
107
113
  },
108
114
  async clear() {
109
- await rm(path2, { force: true });
115
+ await rm(path3, { force: true });
110
116
  }
111
117
  };
112
118
  }
@@ -129,9 +135,16 @@ var PHRASES = {
129
135
  var MISS = "这次没查到。请告诉用户这次没有查到,不要用常识补云枢功能、单号或源码路径。";
130
136
  var TIMED_OUT = "这次超时了,没有拿到结果。不要当成没查到,也不要马上用同样的参数再调一次。";
131
137
  var SERVER_FAULT = "服务端这次出错了,不是没查到。稍后再试,不要换措辞重搜。";
138
+ var AUTH_INVALID = "这把密钥当前不能用了(未绑定或已失效)。请到插件配置页重新绑定,不要换措辞重搜。";
139
+ var BUSY_REMOTE = "服务端当前繁忙(限流),不是没查到。等一会儿再试,不要换措辞重搜。";
140
+ var EMPTY_RESULT = "服务端返回了空内容,这次没拿到结果。不是没查到,稍后再试或换个工具。";
132
141
  var SERVER_PHASES = /* @__PURE__ */ new Set(["down", "http", "unreachable"]);
142
+ var AUTH_PHASES = /* @__PURE__ */ new Set(["invalid", "revoked"]);
143
+ var LOCKED_PHASES = /* @__PURE__ */ new Set(["locked"]);
133
144
  function toolFailureText(known) {
134
145
  if (known?.timedOut) return TIMED_OUT;
146
+ if (known && AUTH_PHASES.has(known.phase)) return AUTH_INVALID;
147
+ if (known && LOCKED_PHASES.has(known.phase)) return BUSY_REMOTE;
135
148
  if (known && SERVER_PHASES.has(known.phase)) return SERVER_FAULT;
136
149
  return MISS;
137
150
  }
@@ -153,6 +166,7 @@ var MAX_PARAMS = 12;
153
166
  var MAX_DESCRIPTION = 600;
154
167
  var MAX_TIMEOUT_MS = 18e4;
155
168
  var MAX_POLL_MS = 18e4;
169
+ var REGISTER_MARGIN_MS = 1e4;
156
170
  var KINDS = /* @__PURE__ */ new Set(["read", "task", "write"]);
157
171
  function isRecord(value) {
158
172
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
@@ -212,7 +226,9 @@ function readPoll(value) {
212
226
  } catch {
213
227
  return null;
214
228
  }
215
- return { tool, idPattern, firstWaitMs, waitMs, intervalMs };
229
+ const budget = MAX_TIMEOUT_MS - firstWaitMs - REGISTER_MARGIN_MS;
230
+ const bounded = Math.max(intervalMs, Math.min(waitMs, budget));
231
+ return { tool, idPattern, firstWaitMs, waitMs: bounded, intervalMs };
216
232
  }
217
233
  function registerTimeout(tool) {
218
234
  if (tool.kind === "task" && tool.poll) {
@@ -346,9 +362,9 @@ function command(file, args) {
346
362
  stdio: ["ignore", "pipe", "ignore"]
347
363
  });
348
364
  }
349
- function readText(path2) {
365
+ function readText(path3) {
350
366
  try {
351
- return readFileSync(path2, "utf8").trim();
367
+ return readFileSync(path3, "utf8").trim();
352
368
  } catch {
353
369
  return "";
354
370
  }
@@ -377,8 +393,8 @@ function readMachineId() {
377
393
  cachedMachineId = value;
378
394
  return value;
379
395
  }
380
- function sha256(text2) {
381
- return createHash("sha256").update(text2).digest("hex");
396
+ function sha256(text3) {
397
+ return createHash("sha256").update(text3).digest("hex");
382
398
  }
383
399
  function stableFingerprint(installId, env) {
384
400
  if (!env.machineId || env.machineId.length < 16) throw new Error("machine id unavailable");
@@ -458,11 +474,11 @@ async function postJson(fetchImpl, url, headers, body) {
458
474
 
459
475
  // src/session/endpoint.ts
460
476
  function checkEndpoint(raw) {
461
- const text2 = String(raw || "").trim();
462
- if (text2 === "") return "请填写访问地址";
477
+ const text3 = String(raw || "").trim();
478
+ if (text3 === "") return "请填写访问地址";
463
479
  let url;
464
480
  try {
465
- url = new URL(text2);
481
+ url = new URL(text3);
466
482
  } catch {
467
483
  return "地址不合法,需要一个完整的 http(s) 地址";
468
484
  }
@@ -498,13 +514,13 @@ function createAccountActions(deps) {
498
514
  "x-authinex-ds-version": version
499
515
  };
500
516
  }
501
- async function postPersonal(path2, body, replayed = false) {
517
+ async function postPersonal(path3, body, replayed = false) {
502
518
  const base = normalizeEndpoint(memory.endpoint);
503
519
  if (!base || !memory.token) return { ok: false, status: 0, data: { message: PHRASES.unreachable } };
504
- const res = await postJson(fetchImpl, `${base}${path2}`, sessionHeaders(), body);
520
+ const res = await postJson(fetchImpl, `${base}${path3}`, sessionHeaders(), body);
505
521
  if (res.status === 401 && !replayed && await hasDeviceSecret()) {
506
522
  const back = await signInSaved();
507
- if (back) return postPersonal(path2, body, true);
523
+ if (back) return postPersonal(path3, body, true);
508
524
  }
509
525
  return { ok: res.ok, status: res.status, data: res.data };
510
526
  }
@@ -559,9 +575,9 @@ function createAccountActions(deps) {
559
575
  async function legacyOnesOptions(issueTypes, project) {
560
576
  const base = normalizeEndpoint(memory.endpoint);
561
577
  if (!base || !memory.token) return { ok: false, message: PHRASES.unreachable };
562
- const path2 = issueTypes ? `/api/auth/me/accounts/ones/issue-types?projectUuid=${encodeURIComponent(project.trim())}` : "/api/auth/me/accounts/ones/projects";
578
+ const path3 = issueTypes ? `/api/auth/me/accounts/ones/issue-types?projectUuid=${encodeURIComponent(project.trim())}` : "/api/auth/me/accounts/ones/projects";
563
579
  try {
564
- const response = await fetchImpl(`${base}${path2}`, {
580
+ const response = await fetchImpl(`${base}${path3}`, {
565
581
  method: issueTypes ? "GET" : "POST",
566
582
  headers: {
567
583
  authorization: `Bearer ${memory.token}`,
@@ -712,23 +728,25 @@ var TOOLS = {
712
728
  ask_assistant: {
713
729
  title: "问智能助手",
714
730
  timeoutMs: 9e4,
715
- description: `把问题交给智能助手,只要同步回答。不要传 deep。
716
- 它是兜底:先试 search_kb / search_code 这些单点工具,更便宜也更快。${DATA_NOT_INSTRUCTION}`,
731
+ description: `把问题交给线上客服 Agent。后台执行,结果自动回到对话,不必调用查任务进度。
732
+ 先试 search_kb / search_code。跨来源仍对不上再用它,并在 brief 写已知依据。不要传 deep。${DATA_NOT_INSTRUCTION}`,
717
733
  parameters: {
718
734
  question: { type: "string", required: true, description: "完整问句" },
719
- version: { type: "string", description: "产品版本,可空" }
735
+ version: { type: "string", description: "产品版本,可空" },
736
+ brief: { type: "string", description: "已知依据、试过的检索、要补的部分。不要贴整段对话" }
720
737
  }
721
738
  },
722
739
  locate_online: {
723
740
  title: "线上源码定位",
724
741
  timeoutMs: 7e4,
725
- description: `按版本读线上源码做只读定位。45 秒内给出结论,或交回进度和 taskId。
742
+ description: `按版本读线上源码做只读定位。后台执行,结果自动回到对话,不必调用查任务进度。
726
743
  结论按「根因 / 文件 / 证据 / 置信度 / 反证 / 过程」分块,引用时保留行号。
727
744
  问「怎么配」「支持不支持」不要用它,用 search_kb 或 product_features。${DATA_NOT_INSTRUCTION}`,
728
745
  parameters: {
729
746
  question: { type: "string", required: true, description: "要定位的现象" },
730
747
  version: { type: "string", description: "产品版本或分支" },
731
- side: { type: "string", description: "frontend 或 backend,可空" }
748
+ side: { type: "string", description: "frontend 或 backend,可空" },
749
+ brief: { type: "string", description: "本机已查到的路径和单号。不要贴整段对话" }
732
750
  }
733
751
  },
734
752
  task_status: {
@@ -775,6 +793,41 @@ var TOOL_OUTPUT = {
775
793
  render: (_args, value) => [{ type: "text", text: String(value?.text || "") }]
776
794
  };
777
795
 
796
+ // src/work/deep-analysis.ts
797
+ var DEEP_RULE = "深度分析已开启:除了查单、建单、提交经验这类与代码无关的,每轮都先用代码检索(search_code)核实,要根因或「这版为什么」再按版本读线上源码(locate_online);知识库、文档和工单只作背景,不能单独当结论依据。答复按「结论 / 源码依据(路径:行号)/ 旁证 / 反证或未核实点 / 置信度」分块;没拿到代码证据就标「未用源码核实」再作答,别把文档推断写成事实。";
798
+ var DEEP_RULE_NO_CODE = "深度分析已开启,但当前角色没有代码检索和线上定位工具:本轮只能凭知识库、文档和工单回答,答复里必须写「未用源码核实」并说明缺哪个权限,不要把文档推断写成源码结论。";
799
+ var DEEP_STORED = "on";
800
+ function parseStoredDeep(raw) {
801
+ return String(raw || "").trim() === DEEP_STORED;
802
+ }
803
+ var HOWTO = "用法:/ax-deep 开,或 /ax-deep 关";
804
+ var USAGE = `没看懂。${HOWTO}`;
805
+ var ON_WORDS = /* @__PURE__ */ new Set(["开", "开启", "打开", "on", "true", "1"]);
806
+ var OFF_WORDS = /* @__PURE__ */ new Set(["关", "关闭", "关掉", "off", "false", "0"]);
807
+ function interpretDeepCommand(raw, current) {
808
+ const text3 = raw.trim().toLowerCase();
809
+ if (!text3) {
810
+ const head = current ? "深度分析已开启:每轮先查源码核实再答,比平时慢,证据更全。" : "深度分析已关闭:按问题复杂度自动选工具,源码分析能力仍然保留。";
811
+ return { kind: "success", text: `${head}
812
+ ${HOWTO}`, deep: current };
813
+ }
814
+ if (ON_WORDS.has(text3)) {
815
+ return {
816
+ kind: "success",
817
+ text: "已开启深度分析:每轮先查源码核实再作答;耗时可能更久,但证据更丰富、多维。",
818
+ deep: true
819
+ };
820
+ }
821
+ if (OFF_WORDS.has(text3)) {
822
+ return {
823
+ kind: "success",
824
+ text: "已关闭深度分析:回到按问题复杂度自动选工具;源码分析能力没有关,需要看代码时照样会用。",
825
+ deep: false
826
+ };
827
+ }
828
+ return { kind: "error", text: USAGE };
829
+ }
830
+
778
831
  // src/work/work-context.ts
779
832
  var PRODUCT_KINDS = [
780
833
  { id: "yunshu", label: "云枢" },
@@ -864,10 +917,10 @@ function accessLine(tickets) {
864
917
  var CITE_RULE = "没有真正检索过就不要写来源。工具返回没有 [S1] / [C1] 编号时,不要写「已引用」或「仅检出」。";
865
918
  var SOURCE_HEAD = /^(?:#{1,6}\s*)?(?:已引用|仅检出)\s*$/;
866
919
  var SOURCE_ITEM = /^(?:[-*+]\s|\d+[.)、]\s|>|\[[A-Z]\d+\])/;
867
- function omitSourceSections(text2) {
920
+ function omitSourceSections(text3) {
868
921
  const kept = [];
869
922
  let skipping = false;
870
- for (const line of text2.split("\n")) {
923
+ for (const line of text3.split("\n")) {
871
924
  const trimmed = line.trim();
872
925
  if (trimmed.startsWith("本返回带编号")) continue;
873
926
  if (SOURCE_HEAD.test(trimmed)) {
@@ -891,7 +944,9 @@ function buildPrompt(input) {
891
944
  const work = formatWork(input.work);
892
945
  if (work) parts.push(work);
893
946
  parts.push(accessLine(input.tickets));
894
- parts.push([CITE_RULE, PLAN_RULE, FOLLOW_UP_RULE, NO_HIT_RULE].join(""));
947
+ const rules = [CITE_RULE, PLAN_RULE, FOLLOW_UP_RULE, NO_HIT_RULE];
948
+ if (input.deep) rules.unshift(input.codeTools === false ? DEEP_RULE_NO_CODE : DEEP_RULE);
949
+ parts.push(rules.join(""));
895
950
  let head = parts.join("\n");
896
951
  if (head.length > PROMPT_LIMIT) return head.slice(0, PROMPT_LIMIT);
897
952
  const extra = input.promptContext.trim().slice(0, PROMPT_CONTEXT_MAX);
@@ -910,27 +965,28 @@ function contextPatch(input) {
910
965
  }
911
966
  return patch;
912
967
  }
913
- var USAGE = "没看懂。用法:/ax-context 云枢 8.7 某客户 要问的问题,或 /ax-context 清空";
968
+ var HOWTO2 = "用法:/ax-context 云枢 8.7 某客户 要问的问题,或 /ax-context 清空";
969
+ var USAGE2 = `没看懂。${HOWTO2}`;
914
970
  var QUESTION_MARKS = ["?", "?", "怎么", "怎样", "如何", "为啥", "为什么", "为何", "哪些", "哪个", "排查", "报错"];
915
971
  function questionStartOf(tokens) {
916
972
  return tokens.findIndex((token) => QUESTION_MARKS.some((mark) => token.includes(mark)));
917
973
  }
918
974
  function interpretCommand(raw, current) {
919
- const text2 = raw.trim();
920
- if (!text2) {
975
+ const text3 = raw.trim();
976
+ if (!text3) {
921
977
  const line2 = formatWorkFields(current);
922
978
  return {
923
979
  kind: "success",
924
- text: line2 ? `当前工作上下文:${line2}` : `还没有工作上下文。${USAGE}`,
980
+ text: line2 ? `当前工作上下文:${line2}` : `还没有工作上下文。${HOWTO2}`,
925
981
  work: current,
926
982
  question: ""
927
983
  };
928
984
  }
929
- if (text2 === "清空") return { kind: "success", text: "已清空工作上下文", work: EMPTY_WORK, question: "" };
930
- const tokens = text2.split(/\s+/).filter(Boolean);
985
+ if (text3 === "清空") return { kind: "success", text: "已清空工作上下文", work: EMPTY_WORK, question: "" };
986
+ const tokens = text3.split(/\s+/).filter(Boolean);
931
987
  const kindToken = tokens[0] || "";
932
988
  if (!Object.prototype.hasOwnProperty.call(ALIASES, kindToken) || !ALIASES[kindToken]) {
933
- return { kind: "error", text: USAGE };
989
+ return { kind: "error", text: USAGE2 };
934
990
  }
935
991
  const version = tokens[1] || "";
936
992
  const rest = tokens.slice(2);
@@ -976,13 +1032,19 @@ function createRouteHandler(deps) {
976
1032
  listSkills,
977
1033
  importSkill,
978
1034
  exportSkill,
979
- installSkill
1035
+ installSkill,
1036
+ downloadUpgrade
980
1037
  } = deps;
981
- async function handle(method, path2, body, headers) {
1038
+ async function handle(method, path3, body, headers, query = {}) {
1039
+ if (method === "GET" && (path3 === "/authinex-ds/upgrade/template" || path3 === "/authinex-ds/upgrade/report")) {
1040
+ const kind = path3.endsWith("/template") ? "template" : "report";
1041
+ const file = await downloadUpgrade(kind, query);
1042
+ return { status: file.status, body: { detail: file.text }, raw: file };
1043
+ }
982
1044
  if (headers?.["x-authinex-ds"] !== "1") {
983
1045
  return { status: 403, body: { detail: "forbidden" } };
984
1046
  }
985
- if (method === "GET" && path2 === "/authinex-ds/state") {
1047
+ if (method === "GET" && path3 === "/authinex-ds/state") {
986
1048
  if (!memory.token && memory.phase !== "binding") {
987
1049
  const saved = await readSecret();
988
1050
  if (secretReady(saved)) await restore();
@@ -990,37 +1052,41 @@ function createRouteHandler(deps) {
990
1052
  await dispatch.refreshStatus();
991
1053
  return { status: 200, body: snapshot() };
992
1054
  }
993
- if (method === "GET" && path2 === "/authinex-ds/context") {
1055
+ if (method === "GET" && path3 === "/authinex-ds/context") {
994
1056
  return { status: 200, body: dispatch.contextView() };
995
1057
  }
996
- if (method === "POST" && path2 === "/authinex-ds/context") {
1058
+ if (method === "POST" && path3 === "/authinex-ds/context") {
997
1059
  const saved = await dispatch.saveContext(body || {});
998
1060
  return { status: saved.ok ? 200 : 400, body: { ...saved, state: snapshot() } };
999
1061
  }
1000
- if (method === "POST" && path2 === "/authinex-ds/bind") {
1062
+ if (method === "POST" && path3 === "/authinex-ds/deep") {
1063
+ const saved = await dispatch.saveDeep(body?.enabled === true);
1064
+ return { status: saved.ok ? 200 : 400, body: { ...saved, state: snapshot() } };
1065
+ }
1066
+ if (method === "POST" && path3 === "/authinex-ds/bind") {
1001
1067
  const result = await bind({ key: String(body?.key || ""), endpoint: body?.endpoint });
1002
1068
  return { status: result.ok ? 200 : 400, body: { ...result.state, message: result.message || "" } };
1003
1069
  }
1004
- if (method === "POST" && path2 === "/authinex-ds/unbind") {
1070
+ if (method === "POST" && path3 === "/authinex-ds/unbind") {
1005
1071
  const result = await unbind();
1006
1072
  return { status: 200, body: { ...result.state, message: "已解除绑定" } };
1007
1073
  }
1008
- if (path2 === "/authinex-ds/accounts" && method === "GET") {
1074
+ if (path3 === "/authinex-ds/accounts" && method === "GET") {
1009
1075
  return { status: 200, body: snapshot().accounts };
1010
1076
  }
1011
- if (path2 === "/authinex-ds/accounts" && method === "PATCH") {
1077
+ if (path3 === "/authinex-ds/accounts" && method === "PATCH") {
1012
1078
  const result = await saveAccount(String(body?.provider || ""), body?.form || {});
1013
1079
  return { status: 200, body: result };
1014
1080
  }
1015
- if (path2 === "/authinex-ds/accounts/test" && method === "POST") {
1081
+ if (path3 === "/authinex-ds/accounts/test" && method === "POST") {
1016
1082
  const result = await testAccount(String(body?.provider || ""), body?.form || {});
1017
1083
  return { status: 200, body: result };
1018
1084
  }
1019
- if (path2 === "/authinex-ds/accounts/enabled" && method === "POST") {
1085
+ if (path3 === "/authinex-ds/accounts/enabled" && method === "POST") {
1020
1086
  const result = await setAccountEnabled(String(body?.provider || ""), Boolean(body?.enabled));
1021
1087
  return { status: result.ok ? 200 : 400, body: result };
1022
1088
  }
1023
- if (path2 === "/authinex-ds/accounts/options" && method === "POST") {
1089
+ if (path3 === "/authinex-ds/accounts/options" && method === "POST") {
1024
1090
  const result = await accountOptions(
1025
1091
  String(body?.provider || ""),
1026
1092
  String(body?.kind || ""),
@@ -1029,19 +1095,19 @@ function createRouteHandler(deps) {
1029
1095
  );
1030
1096
  return { status: 200, body: result };
1031
1097
  }
1032
- if (method === "POST" && path2 === "/authinex-ds/update/check") {
1098
+ if (method === "POST" && path3 === "/authinex-ds/update/check") {
1033
1099
  const result = await checkUpdate();
1034
1100
  return { status: 200, body: { ...result.state, updateMessage: result.message || "" } };
1035
1101
  }
1036
- if (method === "POST" && path2 === "/authinex-ds/update/apply") {
1102
+ if (method === "POST" && path3 === "/authinex-ds/update/apply") {
1037
1103
  const result = await applyUpdate();
1038
1104
  return { status: result.ok ? 200 : 400, body: { ...result } };
1039
1105
  }
1040
- if (method === "POST" && path2 === "/authinex-ds/update/download") {
1106
+ if (method === "POST" && path3 === "/authinex-ds/update/download") {
1041
1107
  const result = await downloadUpdate();
1042
1108
  return { status: result.ok ? 200 : 400, body: { ...result } };
1043
1109
  }
1044
- if (method === "POST" && path2 === "/authinex-ds/skills") {
1110
+ if (method === "POST" && path3 === "/authinex-ds/skills") {
1045
1111
  const result = await listSkills({
1046
1112
  q: String(body?.q || ""),
1047
1113
  page: Number(body?.page || 1),
@@ -1050,7 +1116,7 @@ function createRouteHandler(deps) {
1050
1116
  });
1051
1117
  return { status: 200, body: result };
1052
1118
  }
1053
- if (method === "POST" && path2 === "/authinex-ds/skills/import") {
1119
+ if (method === "POST" && path3 === "/authinex-ds/skills/import") {
1054
1120
  const result = await importSkill({
1055
1121
  markdown: String(body?.markdown || ""),
1056
1122
  name: String(body?.name || ""),
@@ -1058,11 +1124,11 @@ function createRouteHandler(deps) {
1058
1124
  });
1059
1125
  return { status: result.ok ? 200 : 400, body: result };
1060
1126
  }
1061
- if (method === "POST" && path2 === "/authinex-ds/skills/export") {
1127
+ if (method === "POST" && path3 === "/authinex-ds/skills/export") {
1062
1128
  const result = await exportSkill(body?.id);
1063
1129
  return { status: result.ok ? 200 : 400, body: result };
1064
1130
  }
1065
- if (method === "POST" && path2 === "/authinex-ds/skills/install") {
1131
+ if (method === "POST" && path3 === "/authinex-ds/skills/install") {
1066
1132
  const result = await installSkill(body?.id);
1067
1133
  return { status: result.ok ? 200 : 400, body: { ...result, state: snapshot() } };
1068
1134
  }
@@ -1075,6 +1141,17 @@ function createRouteHandler(deps) {
1075
1141
  import { randomUUID } from "node:crypto";
1076
1142
  import { hostname as hostname2, platform as platform2 } from "node:os";
1077
1143
 
1144
+ // src/session/retry-policy.ts
1145
+ var INVALID_RETRIES = 2;
1146
+ function shouldStopRetry(phase, tries) {
1147
+ if (phase === "revoked" || phase === "locked") return true;
1148
+ if (phase === "invalid") return tries >= INVALID_RETRIES;
1149
+ return false;
1150
+ }
1151
+ function resumeDelayMs(attempt) {
1152
+ return Math.min(3e4, 2e3 * 2 ** attempt);
1153
+ }
1154
+
1078
1155
  // src/session/key.ts
1079
1156
  var CROCKFORD = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
1080
1157
  function foldChar(ch) {
@@ -1112,7 +1189,7 @@ function parseKey(raw) {
1112
1189
  // src/tools/tool-run.ts
1113
1190
  var RUNNING = /还在跑|queued|running/;
1114
1191
  var TERMINAL = /* @__PURE__ */ new Set(["done", "failed", "timeout"]);
1115
- var INDEX_WARMING = "代码索引预热中,稍后再试";
1192
+ var INDEX_WARMING = "检索超时了,多半是查询改写在排队,不是索引在预热,也不是没查到。稍后再试;手里有类名时用 find_code。";
1116
1193
  function isTimeoutError(error) {
1117
1194
  const name2 = "name" in error && typeof error.name === "string" ? error.name : "";
1118
1195
  if (name2 === "TimeoutError") return true;
@@ -1210,13 +1287,13 @@ function createSessionActions(deps) {
1210
1287
  function secretReady(secret) {
1211
1288
  return Boolean(secret?.privateJwk && secret.deviceId && secret.installId && secret.endpoint);
1212
1289
  }
1213
- function secretText(record) {
1290
+ function secretText(record2) {
1214
1291
  return JSON.stringify({
1215
- installId: record.installId,
1216
- deviceId: record.deviceId || "",
1217
- endpoint: normalizeEndpoint(record.endpoint),
1218
- privateJwk: record.privateJwk,
1219
- publicJwk: record.publicJwk
1292
+ installId: record2.installId,
1293
+ deviceId: record2.deviceId || "",
1294
+ endpoint: normalizeEndpoint(record2.endpoint),
1295
+ privateJwk: record2.privateJwk,
1296
+ publicJwk: record2.publicJwk
1220
1297
  });
1221
1298
  }
1222
1299
  async function readSecret() {
@@ -1239,12 +1316,12 @@ function createSessionActions(deps) {
1239
1316
  }
1240
1317
  return fromFile;
1241
1318
  }
1242
- async function writeSecret(record) {
1243
- const text2 = secretText(record);
1244
- await credentials.set(credentialRef2, text2);
1319
+ async function writeSecret(record2) {
1320
+ const text3 = secretText(record2);
1321
+ await credentials.set(credentialRef2, text3);
1245
1322
  if (deviceFile) {
1246
1323
  try {
1247
- await deviceFile.write(text2);
1324
+ await deviceFile.write(text3);
1248
1325
  } catch {
1249
1326
  }
1250
1327
  }
@@ -1262,14 +1339,16 @@ function createSessionActions(deps) {
1262
1339
  let resumeTimer = null;
1263
1340
  let resumeAttempt = 0;
1264
1341
  let signingIn = false;
1342
+ let invalidTries = 0;
1265
1343
  function stopResume() {
1266
1344
  if (resumeTimer) clearTimeout(resumeTimer);
1267
1345
  resumeTimer = null;
1268
1346
  resumeAttempt = 0;
1347
+ invalidTries = 0;
1269
1348
  }
1270
1349
  function scheduleResume() {
1271
1350
  if (resumeTimer) return;
1272
- const wait = Math.min(3e4, 2e3 * 2 ** resumeAttempt);
1351
+ const wait = resumeDelayMs(resumeAttempt);
1273
1352
  resumeAttempt += 1;
1274
1353
  resumeTimer = setTimeout(() => {
1275
1354
  resumeTimer = null;
@@ -1277,16 +1356,22 @@ function createSessionActions(deps) {
1277
1356
  }, wait);
1278
1357
  resumeTimer.unref?.();
1279
1358
  }
1359
+ const TRANSIENT_PHASES = /* @__PURE__ */ new Set(["unreachable", "locked"]);
1280
1360
  function fail(phase, detail = "") {
1361
+ if (TRANSIENT_PHASES.has(phase)) {
1362
+ memory.phase = phase;
1363
+ memory.detail = ALLOWED_DETAILS.has(detail) ? detail : "";
1364
+ if (phase === "unreachable" && detail === "服务不可用,联系管理员") {
1365
+ memory.detail = detail;
1366
+ }
1367
+ return snapshot();
1368
+ }
1281
1369
  clearSession();
1282
1370
  memory.phase = phase;
1283
1371
  memory.detail = ALLOWED_DETAILS.has(detail) ? detail : "";
1284
- if (phase === "unreachable" && detail === "服务不可用,联系管理员") {
1285
- memory.detail = detail;
1286
- }
1287
1372
  return snapshot();
1288
1373
  }
1289
- async function request(path2, init = {}) {
1374
+ async function request(path3, init = {}) {
1290
1375
  const method = init.method || "POST";
1291
1376
  const timeout = init.timeout ?? 3e4;
1292
1377
  const session = Boolean(init.session);
@@ -1297,7 +1382,7 @@ function createSessionActions(deps) {
1297
1382
  "x-authinex-ds-version": version
1298
1383
  };
1299
1384
  if (memory.token) headers.authorization = `Bearer ${memory.token}`;
1300
- const run = () => fetchImpl(`${base}${path2}`, {
1385
+ const run = () => fetchImpl(`${base}${path3}`, {
1301
1386
  method,
1302
1387
  headers,
1303
1388
  body: init.body === void 0 ? void 0 : JSON.stringify(init.body),
@@ -1347,7 +1432,7 @@ function createSessionActions(deps) {
1347
1432
  const known = phaseError(failure);
1348
1433
  if (known && !init.replayed && known.phase === "invalid" && await hasDeviceSecret()) {
1349
1434
  const back = await signInSaved();
1350
- if (back) return request(path2, { ...init, replayed: true });
1435
+ if (back) return request(path3, { ...init, replayed: true });
1351
1436
  throw new PhaseError("session", "unreachable");
1352
1437
  }
1353
1438
  if (known) throw failure;
@@ -1418,6 +1503,7 @@ function createSessionActions(deps) {
1418
1503
  });
1419
1504
  applySession(data);
1420
1505
  stopResume();
1506
+ invalidTries = 0;
1421
1507
  await loadAccounts();
1422
1508
  await refreshInstalled();
1423
1509
  await getDispatch().refreshStatus();
@@ -1430,6 +1516,16 @@ function createSessionActions(deps) {
1430
1516
  memory.retryAfter = known.retryAfter || 0;
1431
1517
  return false;
1432
1518
  }
1519
+ if (known?.phase === "invalid") {
1520
+ invalidTries += 1;
1521
+ if (shouldStopRetry("invalid", invalidTries)) {
1522
+ stopResume();
1523
+ fail("invalid", known.detail || "");
1524
+ return false;
1525
+ }
1526
+ } else {
1527
+ invalidTries = 0;
1528
+ }
1433
1529
  clearSession();
1434
1530
  memory.endpoint = secret.endpoint;
1435
1531
  memory.deviceId = secret.deviceId;
@@ -1523,8 +1619,8 @@ function createSessionActions(deps) {
1523
1619
  }
1524
1620
  }
1525
1621
  const shown = String(memory.phase);
1526
- const text2 = phrase(shown);
1527
- const message = shown === "unreachable" && memory.endpoint ? `${text2}(${memory.endpoint})` : text2;
1622
+ const text3 = phrase(shown);
1623
+ const message = shown === "unreachable" && memory.endpoint ? `${text3}(${memory.endpoint})` : text3;
1528
1624
  return { ok: false, message, state: snapshot() };
1529
1625
  }
1530
1626
  }
@@ -1550,6 +1646,21 @@ function createSessionActions(deps) {
1550
1646
  }
1551
1647
  return { ok: true, state: snapshot() };
1552
1648
  }
1649
+ async function openEvents(path3, signal) {
1650
+ const base = normalizeEndpoint(memory.endpoint);
1651
+ if (!base || !memory.token) return null;
1652
+ const response = await fetchImpl(`${base}${path3}`, {
1653
+ method: "GET",
1654
+ headers: {
1655
+ accept: "text/event-stream",
1656
+ authorization: `Bearer ${memory.token}`,
1657
+ "x-authinex-ds-version": version
1658
+ },
1659
+ signal
1660
+ });
1661
+ if (!response.ok || !response.body) return null;
1662
+ return response.body;
1663
+ }
1553
1664
  return {
1554
1665
  readSecret,
1555
1666
  writeSecret,
@@ -1557,6 +1668,7 @@ function createSessionActions(deps) {
1557
1668
  stopResume,
1558
1669
  fail,
1559
1670
  request,
1671
+ openEvents,
1560
1672
  applySession,
1561
1673
  loadAccounts,
1562
1674
  hasDeviceSecret,
@@ -1569,6 +1681,163 @@ function createSessionActions(deps) {
1569
1681
  };
1570
1682
  }
1571
1683
 
1684
+ // src/session/controller-upgrade.ts
1685
+ import { randomUUID as randomUUID2 } from "node:crypto";
1686
+
1687
+ // src/tools/upgrade-links.ts
1688
+ var SERVER_TEMPLATE_PATH = "/api/auth/ds-plugin/upgrade/evaluate/template";
1689
+ var SERVER_REPORT_PATH = "/api/auth/ds-plugin/upgrade/evaluate/report";
1690
+ var REPORT_LINK = /\/api\/auth\/ds-plugin\/upgrade\/evaluate\/report\?taskId=(eval:)?([0-9a-fA-F]{16})/g;
1691
+ function rewriteUpgradeLinks(text3, urls) {
1692
+ if (!text3) return text3;
1693
+ const withTemplate = text3.split(SERVER_TEMPLATE_PATH).join(`[下载模板](${urls.templateUrl()})`);
1694
+ return withTemplate.replace(REPORT_LINK, (_match, _prefix, id) => `[打开报告](${urls.reportUrl(`eval:${id}`)})`);
1695
+ }
1696
+ function record(value) {
1697
+ return value && typeof value === "object" && !Array.isArray(value) ? value : {};
1698
+ }
1699
+ function text2(value) {
1700
+ return typeof value === "string" ? value.trim() : "";
1701
+ }
1702
+ function num(value) {
1703
+ const parsed = Number(value);
1704
+ return Number.isFinite(parsed) ? parsed : 0;
1705
+ }
1706
+ function list(value) {
1707
+ return Array.isArray(value) ? value : [];
1708
+ }
1709
+ function days(value) {
1710
+ const n = num(value);
1711
+ return Number.isInteger(n) ? String(n) : n.toFixed(1);
1712
+ }
1713
+ function lines(items, render) {
1714
+ return items.map(render).map((line) => line.trim()).filter(Boolean);
1715
+ }
1716
+ function renderReportMarkdown(payload) {
1717
+ const data = record(record(payload).data);
1718
+ const result = record(data.result);
1719
+ const report = record(result.report);
1720
+ const form = record(result.form);
1721
+ const taskId = text2(data.taskId) || "eval";
1722
+ const out = [`# 云枢升级评估报告`, ""];
1723
+ const versions = [text2(form.currentVersion), text2(form.targetVersion)].filter(Boolean);
1724
+ out.push(`- 任务:${taskId}`);
1725
+ if (versions.length === 2) out.push(`- 版本:${versions[0]} → ${versions[1]}`);
1726
+ if (text2(form.dbType)) out.push(`- 数据库:${text2(form.dbType)} ${text2(form.dbVersion)}`.trim());
1727
+ out.push("");
1728
+ const summary = text2(report.executiveSummary) || text2(report.summary);
1729
+ if (summary) out.push("## 结论", "", summary, "");
1730
+ const baseline = record(report.baselineEstimate);
1731
+ const ai = record(report.aiEstimate);
1732
+ const confidence = text2(report.confidence) || text2(baseline.confidence) || "low";
1733
+ out.push("## 工作量", "");
1734
+ out.push(`- 基线:${days(baseline.totalMin)}–${days(baseline.totalMax)} 人天(置信度 ${confidence})`);
1735
+ if (num(ai.totalMax) > 0) {
1736
+ out.push(`- AI 复核:${days(ai.totalMin)}–${days(ai.totalMax)} 人天`);
1737
+ } else {
1738
+ out.push("- AI 复核:没有通过证据复核的人天,以上基线只作数量级参考");
1739
+ }
1740
+ const modules = list(ai.modules).map(record).filter((item) => text2(item.name));
1741
+ if (modules.length) {
1742
+ out.push("", "| 模块 | 人天 | 依据 |", "| --- | ---: | --- |");
1743
+ for (const item of modules) {
1744
+ const reason = text2(item.reason).replace(/\|/g, "/").slice(0, 120);
1745
+ out.push(`| ${text2(item.name)} | ${days(item.minDays)}–${days(item.maxDays)} | ${reason} |`);
1746
+ }
1747
+ }
1748
+ out.push("");
1749
+ const counts = record(report.riskCounts);
1750
+ const risks = list(report.risks).map(record);
1751
+ out.push("## 风险", "");
1752
+ out.push(`高 ${num(counts.high)} / 中 ${num(counts.medium)} / 低 ${num(counts.low)}`, "");
1753
+ for (const risk of risks) {
1754
+ const title = text2(risk.title);
1755
+ if (!title) continue;
1756
+ out.push(`### [${text2(risk.level) || "medium"}] ${title}`);
1757
+ const detail = text2(risk.detail);
1758
+ const impact = text2(risk.impact);
1759
+ const mitigation = text2(risk.mitigation);
1760
+ if (detail) out.push("", detail);
1761
+ if (impact) out.push("", `- 影响:${impact}`);
1762
+ if (mitigation) out.push(`- 措施:${mitigation}`);
1763
+ out.push("");
1764
+ }
1765
+ const drivers = lines(list(report.keyDrivers), (item) => `- ${text2(item)}`);
1766
+ if (drivers.length) out.push("## 影响工作量的关键事实", "", ...drivers, "");
1767
+ const assumptions = lines(list(report.assumptions), (item) => `- ${text2(item)}`);
1768
+ if (assumptions.length) out.push("## 仍需确认", "", ...assumptions, "");
1769
+ const actions = lines(list(report.nextActions), (item) => `- ${text2(item)}`);
1770
+ if (actions.length) out.push("## 下一步", "", ...actions, "");
1771
+ return `${out.join("\n").trimEnd()}
1772
+ `;
1773
+ }
1774
+
1775
+ // src/session/controller-upgrade.ts
1776
+ var TEMPLATE_NAME = "cloudpivot-upgrade-evaluate-material-template.md";
1777
+ var TASK_ID = /^eval:[0-9a-fA-F]{16}$/;
1778
+ function plain(status, message, filename = "upgrade-evaluate.txt") {
1779
+ return { status, contentType: "text/plain; charset=utf-8", filename, text: `${message}
1780
+ ` };
1781
+ }
1782
+ function createUpgradeDownloads(deps) {
1783
+ const token = randomUUID2().replace(/-/g, "");
1784
+ const base = () => deps.origin().replace(/\/+$/, "");
1785
+ const templateUrl = () => `${base()}/authinex-ds/upgrade/template?t=${token}`;
1786
+ const reportUrl = (taskId) => `${base()}/authinex-ds/upgrade/report?t=${token}&taskId=${encodeURIComponent(taskId)}`;
1787
+ async function pull(path3) {
1788
+ const base2 = normalizeEndpoint(deps.memory.endpoint);
1789
+ if (!base2) return { status: 503, text: "还没绑定服务地址" };
1790
+ const headers = { "x-authinex-ds-version": deps.version };
1791
+ if (deps.memory.token) headers.authorization = `Bearer ${deps.memory.token}`;
1792
+ try {
1793
+ const response = await deps.fetchImpl(`${base2}${path3}`, { method: "GET", headers, timeout: 3e4 });
1794
+ return { status: response.status, text: await response.text() };
1795
+ } catch {
1796
+ return { status: 503, text: "服务不可达" };
1797
+ }
1798
+ }
1799
+ async function download(kind, query) {
1800
+ if (query.t !== token) return plain(403, "这个下载链接已失效。回插件页重新取一次。");
1801
+ if (kind === "template") {
1802
+ const pulled = await pull(SERVER_TEMPLATE_PATH);
1803
+ if (pulled.status !== 200 || !pulled.text.trim()) {
1804
+ return plain(
1805
+ pulled.status === 200 ? 502 : pulled.status,
1806
+ pulled.status === 403 ? "当前角色不能做升级评估。" : "模板没取到,稍后再试。"
1807
+ );
1808
+ }
1809
+ return {
1810
+ status: 200,
1811
+ contentType: "text/markdown; charset=utf-8",
1812
+ filename: TEMPLATE_NAME,
1813
+ text: pulled.text
1814
+ };
1815
+ }
1816
+ if (kind === "report") {
1817
+ const taskId = query.taskId || "";
1818
+ if (!TASK_ID.test(taskId)) return plain(400, "任务号不对,形如 eval: 加 16 位任务号。");
1819
+ const pulled = await pull(`${SERVER_REPORT_PATH}?taskId=${encodeURIComponent(taskId)}`);
1820
+ if (pulled.status !== 200) {
1821
+ return plain(pulled.status === 404 ? 404 : pulled.status, "这份报告不在这台设备上,或已经过期。");
1822
+ }
1823
+ let payload = null;
1824
+ try {
1825
+ payload = JSON.parse(pulled.text);
1826
+ } catch {
1827
+ return plain(502, "报告格式不对,回对话里看摘要。");
1828
+ }
1829
+ return {
1830
+ status: 200,
1831
+ contentType: "text/markdown; charset=utf-8",
1832
+ filename: `${taskId.replace(":", "-")}.md`,
1833
+ text: renderReportMarkdown(payload)
1834
+ };
1835
+ }
1836
+ return plain(404, "没有这个下载项。");
1837
+ }
1838
+ return { templateUrl, reportUrl, download };
1839
+ }
1840
+
1572
1841
  // src/skills/skills-fs.ts
1573
1842
  import { mkdir as mkdir2, readdir, writeFile as writeFile2 } from "node:fs/promises";
1574
1843
  import { homedir as homedir2 } from "node:os";
@@ -1718,9 +1987,9 @@ function createSkillActions(deps) {
1718
1987
  if (!validSlug(slug)) {
1719
1988
  return { ok: false, message: "技能目录名不合法,已放弃这次安装", path: "", slug: "" };
1720
1989
  }
1721
- const path2 = await writeSkill2(slug, exported.markdown);
1990
+ const path3 = await writeSkill2(slug, exported.markdown);
1722
1991
  await refreshInstalled();
1723
- return { ok: true, message: "已装到本机技能目录,新会话生效", path: path2, slug };
1992
+ return { ok: true, message: "已装到本机技能目录,新会话生效", path: path3, slug };
1724
1993
  } catch {
1725
1994
  return { ok: false, message: "写到本机技能目录失败", path: "", slug: "" };
1726
1995
  } finally {
@@ -1894,11 +2163,11 @@ function piece(pathName, name2 = "", mime = "", data = "") {
1894
2163
  return { path: pathName, name: name2, mime, data };
1895
2164
  }
1896
2165
  function pieceFromText(value) {
1897
- const text2 = value.trim();
1898
- if (!text2) return null;
1899
- if (text2.startsWith("data:")) return piece("", "", "", text2);
1900
- const quoted = text2.match(/["'](\/[^"']+)["']/);
1901
- const candidate = (quoted ? quoted[1] : text2.replace(/^["']|["']$/g, "")).trim();
2166
+ const text3 = value.trim();
2167
+ if (!text3) return null;
2168
+ if (text3.startsWith("data:")) return piece("", "", "", text3);
2169
+ const quoted = text3.match(/["'](\/[^"']+)["']/);
2170
+ const candidate = (quoted ? quoted[1] : text3.replace(/^["']|["']$/g, "")).trim();
1902
2171
  if (!path.isAbsolute(candidate)) return null;
1903
2172
  return piece(candidate);
1904
2173
  }
@@ -1920,18 +2189,18 @@ function parseAttachmentInput(raw) {
1920
2189
  });
1921
2190
  }
1922
2191
  if (typeof raw !== "string") return [];
1923
- const text2 = raw.trim();
1924
- if (!text2) return [];
1925
- if (text2.startsWith("[") || text2.startsWith("{")) {
2192
+ const text3 = raw.trim();
2193
+ if (!text3) return [];
2194
+ if (text3.startsWith("[") || text3.startsWith("{")) {
1926
2195
  try {
1927
- const parsed = JSON.parse(text2);
2196
+ const parsed = JSON.parse(text3);
1928
2197
  if (Array.isArray(parsed) || parsed && typeof parsed === "object") {
1929
2198
  return parseAttachmentInput(Array.isArray(parsed) ? parsed : [parsed]);
1930
2199
  }
1931
2200
  } catch {
1932
2201
  }
1933
2202
  }
1934
- return text2.split(/\r?\n/).flatMap((line) => {
2203
+ return text3.split(/\r?\n/).flatMap((line) => {
1935
2204
  const parsed = pieceFromText(line);
1936
2205
  return parsed ? [parsed] : [];
1937
2206
  });
@@ -2099,13 +2368,94 @@ ${args.problem}`;
2099
2368
  return { proceed: true };
2100
2369
  }
2101
2370
 
2371
+ // src/tools/upgrade-files.ts
2372
+ import { readFile as readFile3, realpath as realpath2, stat as stat2 } from "node:fs/promises";
2373
+ import path2 from "node:path";
2374
+ var MAX_FILES2 = 20;
2375
+ var MAX_BYTES2 = 12 * 1024 * 1024;
2376
+ var MAX_TOTAL = MAX_BYTES2 * 3;
2377
+ var ALLOWED = [".md", ".markdown", ".txt", ".docx", ".pdf", ".xml", ".json", ".yml", ".yaml"];
2378
+ function suffix(name2) {
2379
+ const dot = name2.lastIndexOf(".");
2380
+ return dot > 0 ? name2.slice(dot).toLowerCase() : "";
2381
+ }
2382
+ function decodeLength2(data) {
2383
+ const comma = data.indexOf(",");
2384
+ const body = data.startsWith("data:") && comma >= 0 ? data.slice(comma + 1) : data;
2385
+ const compact = body.replace(/\s+/g, "");
2386
+ return Buffer.from(compact, "base64").length;
2387
+ }
2388
+ async function insideRoots(real, roots) {
2389
+ for (const root of roots) {
2390
+ let base = "";
2391
+ try {
2392
+ base = await realpath2(root);
2393
+ } catch {
2394
+ continue;
2395
+ }
2396
+ if (real === base || real.startsWith(base + path2.sep)) return true;
2397
+ }
2398
+ return false;
2399
+ }
2400
+ function fromData(name2, data) {
2401
+ const bytes = decodeLength2(data);
2402
+ if (bytes <= 0) throw new Error("empty");
2403
+ return { name: name2, data: data.replace(/^data:[^;,]+(;base64)?,/, "").replace(/\s+/g, ""), bytes };
2404
+ }
2405
+ async function fromPath(item, roots) {
2406
+ const real = await realpath2(item.path);
2407
+ const info = await stat2(real);
2408
+ if (!info.isFile() || info.size <= 0) throw new Error("skip");
2409
+ if (!await insideRoots(real, roots)) throw new Error("skip");
2410
+ const body = await readFile3(real);
2411
+ return { name: item.name || path2.basename(real), data: body.toString("base64"), bytes: body.length };
2412
+ }
2413
+ async function readUpgradeFiles(raw, roots = attachmentRoots()) {
2414
+ const pieces = parseAttachmentInput(raw).slice(0, MAX_FILES2 + 4);
2415
+ if (!pieces.length) return { payload: "", count: 0, names: [], note: "" };
2416
+ const files = [];
2417
+ const names = [];
2418
+ const skipped = [];
2419
+ let total = 0;
2420
+ for (const item of pieces) {
2421
+ const label = item.name || (item.path ? path2.basename(item.path) : "附件");
2422
+ if (files.length >= MAX_FILES2) {
2423
+ skipped.push(label);
2424
+ continue;
2425
+ }
2426
+ if (!ALLOWED.includes(suffix(label))) {
2427
+ skipped.push(label);
2428
+ continue;
2429
+ }
2430
+ try {
2431
+ const file = item.data ? fromData(label, item.data) : await fromPath(item, roots);
2432
+ if (file.bytes > MAX_BYTES2 || total + file.bytes > MAX_TOTAL) {
2433
+ skipped.push(file.name);
2434
+ continue;
2435
+ }
2436
+ total += file.bytes;
2437
+ files.push({ name: file.name, data: file.data });
2438
+ names.push(file.name);
2439
+ } catch {
2440
+ skipped.push(label);
2441
+ }
2442
+ }
2443
+ const note = skipped.length ? `有 ${skipped.length} 个附件没带上(${skipped.slice(0, 3).join("、")})。评估只收 md/txt/docx/pdf/xml/json/yml,单个 12MB、合计 36MB,且必须是对话附件目录里的文件。` : "";
2444
+ return {
2445
+ payload: files.length ? JSON.stringify(files) : "",
2446
+ count: files.length,
2447
+ names,
2448
+ note
2449
+ };
2450
+ }
2451
+
2102
2452
  // src/skills/skills-source.ts
2103
2453
  var SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
2104
2454
  var ONLINE_SKILL_RANK = 350;
2105
2455
  var SKILL_PROVIDER = "authinex";
2106
2456
  function descriptionOf(item) {
2107
- const text2 = String(item.description || item.title || "").trim().slice(0, 200);
2108
- return text2;
2457
+ const text3 = String(item.description || item.title || "").trim().slice(0, 200);
2458
+ return text3;
2109
2459
  }
2110
2460
  function listedSkills(items) {
2111
2461
  if (!items) return [];
@@ -2146,6 +2496,125 @@ function loadedSkill(item, invocation) {
2146
2496
  };
2147
2497
  }
2148
2498
 
2499
+ // src/tools/delegate-job.ts
2500
+ var BACKOFF_MS = [2e3, 5e3, 1e4, 1e4, 1e4];
2501
+ var TASK_ID2 = /\b(?:ask|dive|eval):[A-Za-z0-9_-]+/;
2502
+ function onlineTaskId(text3) {
2503
+ return TASK_ID2.exec(text3)?.[0] || "";
2504
+ }
2505
+ function delegateLabel(name2, question) {
2506
+ const who = name2 === "locate_online" ? "编码 Agent" : name2 === "upgrade_evaluate" ? "升级评估" : "客服 Agent";
2507
+ const title = question.replace(/\s+/g, " ").trim().slice(0, 40);
2508
+ return title ? `${who}:${title}` : who;
2509
+ }
2510
+ function clipBytes(text3, maxBytes) {
2511
+ if (Buffer.byteLength(text3, "utf8") <= maxBytes) return text3;
2512
+ let out = "";
2513
+ let used = 0;
2514
+ for (const char of text3) {
2515
+ const size = Buffer.byteLength(char, "utf8");
2516
+ if (used + size > maxBytes - 3) break;
2517
+ out += char;
2518
+ used += size;
2519
+ }
2520
+ return `${out}…`;
2521
+ }
2522
+ var ANSWER_BYTES = 2900;
2523
+ function renderDone(frame) {
2524
+ const lines2 = ["线上任务已完成。"];
2525
+ if (frame.answer) lines2.push(clipBytes(frame.answer, ANSWER_BYTES));
2526
+ const cites = frame.citations || [];
2527
+ if (cites.length) {
2528
+ lines2.push("出处:");
2529
+ for (const item of cites.slice(0, 12)) {
2530
+ const bits = [item.ref, item.docId ? `doc_id=${item.docId}` : "", item.path || ""].filter(Boolean);
2531
+ if (bits.length) lines2.push(`- ${bits.join(" ")}`);
2532
+ }
2533
+ }
2534
+ for (const gap of frame.gaps || []) lines2.push(`没查到:${gap}`);
2535
+ lines2.push("用 search_kb 或 search_code 复核出处。两边不一致时并列给用户,不要自行取舍。");
2536
+ return lines2.join("\n");
2537
+ }
2538
+ async function followTask(input) {
2539
+ let last = "";
2540
+ for (let attempt = 0; attempt <= BACKOFF_MS.length; attempt += 1) {
2541
+ if (input.signal.aborted) {
2542
+ await input.cancelTask(input.taskId).catch(() => void 0);
2543
+ return { status: "killed", detail: "已取消", result: `线上任务 ${input.taskId} 已取消。` };
2544
+ }
2545
+ try {
2546
+ const body = await input.openEvents(input.taskId, input.signal);
2547
+ if (!body) throw new Error("no stream");
2548
+ const done = await readFrames(body, (frame) => {
2549
+ if (frame.type === "progress") input.job.updateProgress(String(frame.progress || frame.status || "进行中"));
2550
+ if (frame.answer) {
2551
+ const answer = input.rewrite ? input.rewrite(frame.answer) : frame.answer;
2552
+ last = renderDone({ ...frame, answer });
2553
+ }
2554
+ });
2555
+ if (done) {
2556
+ if (last) input.job.append(last);
2557
+ return { status: "completed", result: last || `线上任务 ${input.taskId} 已结束。` };
2558
+ }
2559
+ } catch {
2560
+ if (input.signal.aborted) {
2561
+ await input.cancelTask(input.taskId).catch(() => void 0);
2562
+ return { status: "killed", detail: "已取消", result: `线上任务 ${input.taskId} 已取消。` };
2563
+ }
2564
+ }
2565
+ if (attempt === BACKOFF_MS.length) break;
2566
+ await input.sleep(BACKOFF_MS[attempt]);
2567
+ }
2568
+ const fallback = `线上任务还在跑(${input.taskId})。用查任务进度取结果。`;
2569
+ return { status: "failed", detail: "事件流中断", result: last || fallback };
2570
+ }
2571
+ function startDelegate(input) {
2572
+ const abort = new AbortController();
2573
+ return input.jobs.start({
2574
+ kind: "authinex",
2575
+ label: delegateLabel(input.name, input.question),
2576
+ owner: input.call.agentId || void 0,
2577
+ toolCall: input.call.callId && input.call.rootCallId ? { callId: input.call.callId, rootCallId: input.call.rootCallId } : void 0,
2578
+ outputLimitBytes: 4096,
2579
+ run: (job) => ({
2580
+ cancel: () => abort.abort(),
2581
+ done: followTask({
2582
+ taskId: input.taskId,
2583
+ job,
2584
+ openEvents: input.openEvents,
2585
+ cancelTask: input.cancelTask,
2586
+ sleep: input.sleep,
2587
+ signal: abort.signal,
2588
+ rewrite: input.rewrite
2589
+ })
2590
+ })
2591
+ });
2592
+ }
2593
+ async function readFrames(body, onFrame) {
2594
+ const decoder = new TextDecoder();
2595
+ let buffer = "";
2596
+ for await (const chunk of body) {
2597
+ buffer += decoder.decode(chunk, { stream: true });
2598
+ const parts = buffer.split("\n\n");
2599
+ buffer = parts.pop() || "";
2600
+ for (const part of parts) {
2601
+ for (const line of part.split("\n")) {
2602
+ if (!line.startsWith("data:")) continue;
2603
+ let frame;
2604
+ try {
2605
+ frame = JSON.parse(line.slice(5).trim());
2606
+ } catch {
2607
+ continue;
2608
+ }
2609
+ if (!frame || typeof frame !== "object") continue;
2610
+ onFrame(frame);
2611
+ if (frame.type === "done") return true;
2612
+ }
2613
+ }
2614
+ }
2615
+ return false;
2616
+ }
2617
+
2149
2618
  // src/tools/tool-dispatch.ts
2150
2619
  var CITABLE = /* @__PURE__ */ new Set([
2151
2620
  "search_kb",
@@ -2154,7 +2623,9 @@ var CITABLE = /* @__PURE__ */ new Set([
2154
2623
  "fix_patterns",
2155
2624
  "ask_assistant",
2156
2625
  "locate_online",
2157
- "task_status"
2626
+ "task_status",
2627
+ "upgrade_evaluate",
2628
+ "upgrade_evaluate_template"
2158
2629
  ]);
2159
2630
  function textOf2(data) {
2160
2631
  if (Array.isArray(data?.content)) {
@@ -2303,9 +2774,11 @@ ${accepted.tools.map((tool) => tool.name).join("\n")}`;
2303
2774
  });
2304
2775
  const status = data.structuredContent?.status;
2305
2776
  const failed = Boolean(data.isError);
2306
- const text2 = failed || CITABLE.has(name2) ? textOf2(data) : omitSourceSections(textOf2(data));
2777
+ const shown = failed || CITABLE.has(name2) ? textOf2(data) : omitSourceSections(textOf2(data));
2778
+ const text3 = failed ? shown : rewriteUpgradeLinks(shown, deps.upgradeUrls);
2779
+ if (!failed && !text3.trim()) return { text: EMPTY_RESULT, isError: true, taskId: "", structuredStatus: "" };
2307
2780
  return {
2308
- text: text2,
2781
+ text: text3,
2309
2782
  isError: failed,
2310
2783
  taskId: data.taskId || "",
2311
2784
  structuredStatus: typeof status === "string" ? status : ""
@@ -2335,6 +2808,32 @@ ${accepted.tools.map((tool) => tool.name).join("\n")}`;
2335
2808
  status: (taskId) => toolCall(poll.tool, { taskId }, statusTimeout)
2336
2809
  });
2337
2810
  }
2811
+ async function prepareUpgrade(args) {
2812
+ const outbound = { ...args };
2813
+ if ((textArg(args, "action") || "start") === "cancel") return { outbound };
2814
+ const prepared = await readUpgradeFiles(args.attachments);
2815
+ if (attachmentCount(args.attachments) > 0 && prepared.count === 0) {
2816
+ return { error: { text: prepared.note || "附件没读到,评估没有启动。", isError: true } };
2817
+ }
2818
+ if (prepared.count) outbound.attachments = prepared.payload;
2819
+ else delete outbound.attachments;
2820
+ const form = args.form;
2821
+ if (form && typeof form === "object") outbound.form = JSON.stringify(form);
2822
+ if (!outbound.attachments && !textArg(outbound, "form")) {
2823
+ return { error: { text: "要有填好的模板或项目特征 JSON 才能评估。先下载模板。", isError: true } };
2824
+ }
2825
+ return { outbound };
2826
+ }
2827
+ async function runUpgradeEvaluate(args, entry, timeout) {
2828
+ const action = textArg(args, "action") || "start";
2829
+ state.busy += 1;
2830
+ try {
2831
+ if (action === "cancel") return await toolCall("upgrade_evaluate", args, timeout);
2832
+ return entry?.kind === "task" && entry.poll ? await runTask(entry, args) : await toolCall("upgrade_evaluate", args, timeout);
2833
+ } finally {
2834
+ state.busy -= 1;
2835
+ }
2836
+ }
2338
2837
  async function locate(args) {
2339
2838
  const first = await toolCall("locate_online", args, 15e3);
2340
2839
  return pollTask({
@@ -2402,6 +2901,48 @@ ${prepared.note}` };
2402
2901
  state.busy -= 1;
2403
2902
  }
2404
2903
  }
2904
+ function agentIdOf(agent) {
2905
+ if (!agent || typeof agent !== "object" || !("id" in agent)) return "";
2906
+ const id = agent.id;
2907
+ return typeof id === "string" ? id : "";
2908
+ }
2909
+ function jobsOf() {
2910
+ const jobs = deps.jobs;
2911
+ return jobs && typeof jobs.start === "function" ? jobs : void 0;
2912
+ }
2913
+ async function delegate(name2, args, ctx) {
2914
+ const jobs = jobsOf();
2915
+ if (!jobs || !deps.openEvents) return null;
2916
+ if (name2 === "upgrade_evaluate" && textArg(args, "action") === "cancel") return null;
2917
+ const first = await toolCall(name2, args, 2e4);
2918
+ const taskId = first.taskId || onlineTaskId(first.text);
2919
+ if (first.isError || !taskId) return first;
2920
+ const who = name2 === "locate_online" ? "编码 Agent" : name2 === "upgrade_evaluate" ? "升级评估" : "客服 Agent";
2921
+ let jobId = "";
2922
+ try {
2923
+ jobId = startDelegate({
2924
+ jobs,
2925
+ name: name2,
2926
+ question: textArg(args, "question"),
2927
+ taskId,
2928
+ call: {
2929
+ agentId: agentIdOf(ctx.agent),
2930
+ callId: ctx.callId,
2931
+ rootCallId: ctx.rootCallId
2932
+ },
2933
+ openEvents: (id, signal) => deps.openEvents(`/api/auth/ds-plugin/tasks/${encodeURIComponent(id)}/events`, signal),
2934
+ cancelTask: async (id) => {
2935
+ await deps.request(`/api/auth/ds-plugin/tasks/${encodeURIComponent(id)}/cancel`, { session: true, body: { name: "cancel", arguments: {} } });
2936
+ },
2937
+ sleep: deps.sleep,
2938
+ // 升级评估的摘要带报告地址,服务端只认设备密钥,改成本机能点的链接。
2939
+ rewrite: (text3) => rewriteUpgradeLinks(text3, deps.upgradeUrls)
2940
+ });
2941
+ } catch {
2942
+ return first;
2943
+ }
2944
+ return { text: `已交给线上${who}(任务 ${jobId},线上 ${taskId})。完成后会自动回到对话,可以先继续问别的。`, taskId, isError: false };
2945
+ }
2405
2946
  async function callTool(name2, args = {}, ctx = {}) {
2406
2947
  const entry = activeTools()?.find((tool) => tool.name === name2);
2407
2948
  const legacy = !state.catalogJson && isToolName(name2);
@@ -2409,8 +2950,23 @@ ${prepared.note}` };
2409
2950
  return { text: "当前没有这个工具。", isError: true };
2410
2951
  }
2411
2952
  const payload = applyContextArgs(name2, args);
2953
+ if (name2 === "ask_assistant" && fieldBlank(payload, "chatId")) {
2954
+ const id = agentIdOf(ctx.agent);
2955
+ if (id) payload.chatId = `ds-${id}`.slice(0, 80);
2956
+ }
2957
+ let upgradeArgs = null;
2958
+ if (name2 === "upgrade_evaluate") {
2959
+ const prepared = await prepareUpgrade(payload);
2960
+ if ("error" in prepared) return prepared.error;
2961
+ upgradeArgs = prepared.outbound;
2962
+ }
2963
+ if (name2 === "ask_assistant" || name2 === "locate_online" || name2 === "upgrade_evaluate") {
2964
+ const handed = await delegate(name2, upgradeArgs ?? payload, ctx);
2965
+ if (handed) return handed;
2966
+ }
2412
2967
  if (name2 === "create_ticket") return runTicket(payload, ctx, entry?.timeoutMs || TOOLS.create_ticket.timeoutMs);
2413
2968
  if (name2 === "submit_experience") return runExperience(payload, ctx, entry?.timeoutMs || 3e4);
2969
+ if (name2 === "upgrade_evaluate") return runUpgradeEvaluate(upgradeArgs ?? payload, entry, entry?.timeoutMs || 15e3);
2414
2970
  state.busy += 1;
2415
2971
  try {
2416
2972
  if (!entry && name2 === "locate_online") return await locate(payload);
@@ -2450,11 +3006,19 @@ ${prepared.note}` };
2450
3006
  }
2451
3007
  }
2452
3008
  async function loadWork() {
2453
- if (!deps.workStore) return;
2454
- try {
2455
- state.work = parseStoredWork(await deps.workStore.load());
2456
- } catch {
2457
- state.work = EMPTY_WORK;
3009
+ if (deps.workStore) {
3010
+ try {
3011
+ state.work = parseStoredWork(await deps.workStore.load());
3012
+ } catch {
3013
+ state.work = EMPTY_WORK;
3014
+ }
3015
+ }
3016
+ if (deps.deepStore) {
3017
+ try {
3018
+ state.deep = parseStoredDeep(await deps.deepStore.load());
3019
+ } catch {
3020
+ state.deep = false;
3021
+ }
2458
3022
  }
2459
3023
  }
2460
3024
  async function saveWork() {
@@ -2462,12 +3026,30 @@ ${prepared.note}` };
2462
3026
  if (workIsEmpty(state.work)) await deps.workStore.clear();
2463
3027
  else await deps.workStore.save(JSON.stringify(state.work));
2464
3028
  }
3029
+ async function saveDeep(enabled) {
3030
+ try {
3031
+ if (deps.deepStore) {
3032
+ if (enabled) await deps.deepStore.save(DEEP_STORED);
3033
+ else await deps.deepStore.clear();
3034
+ }
3035
+ } catch {
3036
+ return { ok: false, message: "没有写成深度分析开关" };
3037
+ }
3038
+ state.deep = enabled;
3039
+ return {
3040
+ ok: true,
3041
+ message: enabled ? "已开启深度分析:每轮先查源码核实再答,耗时可能更久" : "已关闭深度分析:按问题复杂度自动选工具"
3042
+ };
3043
+ }
2465
3044
  function promptText() {
2466
3045
  return buildPrompt({
2467
3046
  bound: state.phase === "bound" && Boolean(state.token),
2468
3047
  work: state.work,
2469
3048
  tickets: state.capabilities?.tickets,
2470
- promptContext: state.promptContext
3049
+ promptContext: state.promptContext,
3050
+ deep: state.deep,
3051
+ // 代码工具是按角色下发的:没有就别让模型去调,免得它反复失败或编一个「已核实」。
3052
+ codeTools: allowedTools().includes("search_code")
2471
3053
  });
2472
3054
  }
2473
3055
  async function applyContextCommand(raw) {
@@ -2481,9 +3063,16 @@ ${prepared.note}` };
2481
3063
  }
2482
3064
  return { kind: "success", text: outcome.text };
2483
3065
  }
3066
+ async function applyDeepCommand(raw) {
3067
+ const outcome = interpretDeepCommand(raw, state.deep);
3068
+ if (outcome.kind === "error") return { kind: "error", text: outcome.text };
3069
+ const saved = await saveDeep(outcome.deep);
3070
+ if (!saved.ok) return { kind: "error", text: saved.message };
3071
+ return { kind: "success", text: outcome.text };
3072
+ }
2484
3073
  function contextView() {
2485
3074
  const work = deps.verified() ? state.work : EMPTY_WORK;
2486
- return { ...work, skillsOnline: state.skillsOnline };
3075
+ return { ...work, skillsOnline: state.skillsOnline, deepAnalysis: deps.verified() ? state.deep : false };
2487
3076
  }
2488
3077
  async function saveContext(input) {
2489
3078
  if (input.clear === true) {
@@ -2556,17 +3145,20 @@ ${prepared.note}` };
2556
3145
  loadWork,
2557
3146
  promptText,
2558
3147
  applyContextCommand,
3148
+ applyDeepCommand,
2559
3149
  contextView,
2560
3150
  saveContext,
3151
+ saveDeep,
2561
3152
  listSkillSource,
2562
3153
  loadSkillSource
2563
3154
  };
2564
3155
  }
2565
3156
 
2566
3157
  // src/session/controller.ts
2567
- var VERSION = true ? "0.3.10" : "0.1.0";
3158
+ var VERSION = true ? "0.3.12" : "0.1.0";
2568
3159
  var CREDENTIAL_REF = "AUTHINEX_DS_DEVICE";
2569
3160
  var CONTEXT_CREDENTIAL_REF = "AUTHINEX_DS_CONTEXT";
3161
+ var DEEP_CREDENTIAL_REF = "AUTHINEX_DS_DEEP";
2570
3162
  function defaultMachineFingerprint() {
2571
3163
  return machineFingerprint({ platform: platform3(), arch: arch2(), machineId: readMachineId() });
2572
3164
  }
@@ -2655,6 +3247,7 @@ function createController(options) {
2655
3247
  skillsVersion: "",
2656
3248
  promptContext: "",
2657
3249
  work: EMPTY_WORK,
3250
+ deep: false,
2658
3251
  skillsOnline: false,
2659
3252
  occupied: /* @__PURE__ */ new Set(),
2660
3253
  invalidateSkills: null
@@ -2679,6 +3272,7 @@ function createController(options) {
2679
3272
  update: memory.update,
2680
3273
  installedSkills: memory.installedSkills,
2681
3274
  workContext: verified() ? memory.work : EMPTY_WORK,
3275
+ deepAnalysis: verified() ? memory.deep : false,
2682
3276
  skillsOnline: memory.skillsOnline,
2683
3277
  toolTitles: dispatch.toolTitles()
2684
3278
  };
@@ -2701,14 +3295,24 @@ function createController(options) {
2701
3295
  getDispatch: () => dispatch,
2702
3296
  refreshInstalled: () => refreshInstalled()
2703
3297
  });
3298
+ const downloads = createUpgradeDownloads({
3299
+ memory,
3300
+ version,
3301
+ fetchImpl,
3302
+ origin: () => options.origin?.() || ""
3303
+ });
2704
3304
  dispatch = createToolDispatch({
2705
3305
  state: memory,
2706
3306
  version,
2707
3307
  now,
2708
3308
  sleep,
2709
3309
  workStore: options.workStore,
3310
+ deepStore: options.deepStore,
2710
3311
  cancelled,
2711
3312
  request: session.request,
3313
+ jobs: options.jobs,
3314
+ openEvents: session.openEvents,
3315
+ upgradeUrls: { templateUrl: downloads.templateUrl, reportUrl: downloads.reportUrl },
2712
3316
  verified,
2713
3317
  fail: session.fail,
2714
3318
  classify(error) {
@@ -2765,6 +3369,7 @@ function createController(options) {
2765
3369
  restore,
2766
3370
  dispatch,
2767
3371
  snapshot,
3372
+ downloadUpgrade: downloads.download,
2768
3373
  bind,
2769
3374
  unbind,
2770
3375
  saveAccount,
@@ -2806,6 +3411,7 @@ function createController(options) {
2806
3411
  loadSkillSource: dispatch.loadSkillSource,
2807
3412
  promptText: dispatch.promptText,
2808
3413
  applyContextCommand: dispatch.applyContextCommand,
3414
+ applyDeepCommand: dispatch.applyDeepCommand,
2809
3415
  saveAccount,
2810
3416
  setAccountEnabled,
2811
3417
  testAccount,
@@ -2838,7 +3444,10 @@ var PATHS = [
2838
3444
  "/authinex-ds/skills/import",
2839
3445
  "/authinex-ds/skills/export",
2840
3446
  "/authinex-ds/skills/install",
2841
- "/authinex-ds/context"
3447
+ "/authinex-ds/context",
3448
+ "/authinex-ds/deep",
3449
+ "/authinex-ds/upgrade/template",
3450
+ "/authinex-ds/upgrade/report"
2842
3451
  ];
2843
3452
  function headerMap(req) {
2844
3453
  const headers = {};
@@ -2863,6 +3472,15 @@ function readBody(req) {
2863
3472
  req.on("error", reject);
2864
3473
  });
2865
3474
  }
3475
+ function sendFile(res, status, file) {
3476
+ const name2 = file.filename.replace(/["\\\r\n]/g, "") || "download.md";
3477
+ res.writeHead(status, {
3478
+ "content-type": file.contentType,
3479
+ "content-disposition": `attachment; filename="${name2}"`,
3480
+ "cache-control": "no-store"
3481
+ });
3482
+ res.end(file.text);
3483
+ }
2866
3484
  function send(res, status, body) {
2867
3485
  res.writeHead(status, {
2868
3486
  "content-type": "application/json; charset=utf-8",
@@ -2881,6 +3499,7 @@ function occupiedNames(ctx) {
2881
3499
  function apply(ctx) {
2882
3500
  const ref = credentialRef(CREDENTIAL_REF);
2883
3501
  const contextRef = credentialRef(CONTEXT_CREDENTIAL_REF);
3502
+ const deepRef = credentialRef(DEEP_CREDENTIAL_REF);
2884
3503
  const manager = () => {
2885
3504
  const service = ctx.get?.("pluginManager", false);
2886
3505
  if (!service || typeof service.installBundle !== "function") return void 0;
@@ -2888,6 +3507,13 @@ function apply(ctx) {
2888
3507
  };
2889
3508
  const controller = createController({
2890
3509
  clientKind: detectClientKind(),
3510
+ origin: () => {
3511
+ try {
3512
+ return ctx.webServer.getOrigin?.() || "";
3513
+ } catch {
3514
+ return "";
3515
+ }
3516
+ },
2891
3517
  // 更新走 DeepSeek 自己的安装器:它会改 profile 的 package.json、重算组合并重新加载。
2892
3518
  install: async (spec) => {
2893
3519
  const service = manager();
@@ -2911,16 +3537,27 @@ function apply(ctx) {
2911
3537
  restartRequired: result?.application === "restart-required" || result?.restartRequired === true
2912
3538
  };
2913
3539
  },
2914
- fetch: (url, init) => fetch(url, {
2915
- method: init.method,
2916
- headers: init.headers,
2917
- body: init.body,
2918
- signal: AbortSignal.timeout(init.timeout || 3e4)
2919
- }),
3540
+ fetch: async (url, init) => {
3541
+ const response = await fetch(url, {
3542
+ method: init.method,
3543
+ headers: init.headers,
3544
+ body: init.body,
3545
+ signal: init.signal ?? AbortSignal.timeout(init.timeout || 3e4)
3546
+ });
3547
+ return {
3548
+ status: response.status,
3549
+ ok: response.ok,
3550
+ headers: { get: (name2) => response.headers.get(name2) },
3551
+ text: () => response.text(),
3552
+ arrayBuffer: () => response.arrayBuffer(),
3553
+ body: response.body
3554
+ };
3555
+ },
2920
3556
  // 技能只落 DSH 自己的技能目录,不进用户工作区、不碰仓库。
2921
3557
  writeSkill,
2922
3558
  listInstalled,
2923
3559
  deviceFile: defaultDeviceFile(),
3560
+ jobs: ctx.get?.("jobs"),
2924
3561
  credentials: {
2925
3562
  resolve: () => ctx.credentials.resolve(ref),
2926
3563
  set: (_ref, value) => ctx.credentials.set(ref, value),
@@ -2934,6 +3571,15 @@ function apply(ctx) {
2934
3571
  },
2935
3572
  save: (value) => ctx.credentials.set(contextRef, value),
2936
3573
  clear: () => ctx.credentials.unset(contextRef)
3574
+ },
3575
+ deepStore: {
3576
+ load: async () => {
3577
+ const resolved = await ctx.credentials.resolve(deepRef);
3578
+ if (!resolved) return void 0;
3579
+ return typeof resolved === "string" ? resolved : resolved.value;
3580
+ },
3581
+ save: (value) => ctx.credentials.set(deepRef, value),
3582
+ clear: () => ctx.credentials.unset(deepRef)
2937
3583
  }
2938
3584
  });
2939
3585
  attachOptionalHosts(ctx, {
@@ -2942,6 +3588,7 @@ function apply(ctx) {
2942
3588
  setInvalidate: (fn) => controller.setSkillInvalidator(fn),
2943
3589
  promptText: () => controller.promptText(),
2944
3590
  runContextCommand: (raw) => controller.applyContextCommand(raw),
3591
+ runDeepCommand: (raw) => controller.applyDeepCommand(raw),
2945
3592
  markSkillsOnline: (online) => controller.setSkillsOnline(online)
2946
3593
  });
2947
3594
  const disposers = [];
@@ -2963,7 +3610,9 @@ function apply(ctx) {
2963
3610
  const result = await controller.callTool(spec.name, args, {
2964
3611
  ask: (request) => ctx.userQuestions.ask(request),
2965
3612
  agent: exec?.agent,
2966
- signal: exec?.signal
3613
+ signal: exec?.signal,
3614
+ callId: exec?.callId,
3615
+ rootCallId: exec?.rootCallId
2967
3616
  });
2968
3617
  return publishToolResult(result);
2969
3618
  }
@@ -2974,10 +3623,10 @@ function apply(ctx) {
2974
3623
  disposed = true;
2975
3624
  for (const dispose of disposers.splice(0)) dispose();
2976
3625
  }, "authinex-ds: tools");
2977
- for (const path2 of PATHS) {
3626
+ for (const path3 of PATHS) {
2978
3627
  ctx.effect(() => ctx.webServer.register({
2979
3628
  kind: "exact",
2980
- path: path2,
3629
+ path: path3,
2981
3630
  handler: async (req, res) => {
2982
3631
  const rejection = ctx.connection?.requestRejection?.(req);
2983
3632
  if (rejection !== void 0) {
@@ -2994,9 +3643,12 @@ function apply(ctx) {
2994
3643
  return;
2995
3644
  }
2996
3645
  }
2997
- const result = await controller.handle(method, path2, body, headerMap(req));
3646
+ const query = {};
3647
+ const rawQuery = String(req.url || "").split("?")[1] || "";
3648
+ for (const [key, value] of new URLSearchParams(rawQuery)) query[key] = value;
3649
+ const result = await controller.handle(method, path3, body, headerMap(req), query);
2998
3650
  const payload = result.body;
2999
- if (path2 === "/authinex-ds/bind" || path2 === "/authinex-ds/unbind" || path2 === "/authinex-ds/accounts") {
3651
+ if (path3 === "/authinex-ds/bind" || path3 === "/authinex-ds/unbind" || path3 === "/authinex-ds/accounts") {
3000
3652
  try {
3001
3653
  registerTools();
3002
3654
  } catch (error) {
@@ -3009,9 +3661,13 @@ function apply(ctx) {
3009
3661
  console.error("authinex-ds: 工具注册失败", error);
3010
3662
  }
3011
3663
  }
3664
+ if (result.raw) {
3665
+ sendFile(res, result.status, result.raw);
3666
+ return;
3667
+ }
3012
3668
  send(res, result.status, payload);
3013
3669
  }
3014
- }), `authinex-ds: ${path2}`);
3670
+ }), `authinex-ds: ${path3}`);
3015
3671
  }
3016
3672
  void controller.restore().then(() => registerTools());
3017
3673
  }