engine7 7.1.148 → 7.1.150

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.
@@ -6077,16 +6077,15 @@ function stripInjectedContext(text2) {
6077
6077
  function escapeRegExp(s) {
6078
6078
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6079
6079
  }
6080
- var SKILL_GATE_HINT_PREFIX, SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
6080
+ var SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
6081
6081
  var init_strip_injected = __esm({
6082
6082
  "src/messages/strip-injected.ts"() {
6083
6083
  "use strict";
6084
- SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
6085
6084
  SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
6086
6085
  INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
6087
6086
  KNOWN_INJECTED_TEXT = [
6088
- SKILL_GATE_HINT_PREFIX,
6089
- // skill-gate hint 默认/自定义前缀(1007 现行)
6087
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
6088
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
6090
6089
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
6091
6090
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
6092
6091
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"
@@ -8129,6 +8128,8 @@ function attachmentToMessage(attachment) {
8129
8128
  ${attachment.notifications.join("\n\n")}`
8130
8129
  )
8131
8130
  };
8131
+ case "coldstart_hint":
8132
+ return { role: "user", content: wrapInSystemReminder(attachment.text) };
8132
8133
  case "teammate_messages": {
8133
8134
  const lines = attachment.messages.map(
8134
8135
  (m) => m.summary ? `[From: ${m.from}] ${m.summary}
@@ -10711,32 +10712,32 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10711
10712
  return { built: !hasStats, ms: Date.now() - started };
10712
10713
  }
10713
10714
  async close() {
10714
- const errors2 = [];
10715
+ const errors3 = [];
10715
10716
  try {
10716
10717
  this.capture?.close();
10717
10718
  } catch (error) {
10718
- errors2.push(error);
10719
+ errors3.push(error);
10719
10720
  }
10720
10721
  try {
10721
10722
  this.db.close();
10722
10723
  } catch (error) {
10723
- errors2.push(error);
10724
+ errors3.push(error);
10724
10725
  }
10725
10726
  try {
10726
10727
  await this.vectors?.close();
10727
10728
  } catch (error) {
10728
- errors2.push(error);
10729
+ errors3.push(error);
10729
10730
  } finally {
10730
10731
  this.vectors = null;
10731
10732
  }
10732
10733
  try {
10733
10734
  this.releaseRuntimeWriter?.();
10734
10735
  } catch (error) {
10735
- errors2.push(error);
10736
+ errors3.push(error);
10736
10737
  } finally {
10737
10738
  this.releaseRuntimeWriter = void 0;
10738
10739
  }
10739
- if (errors2.length) throw new AggregateError(errors2, "MEM7_CLOSE_FAILED");
10740
+ if (errors3.length) throw new AggregateError(errors3, "MEM7_CLOSE_FAILED");
10740
10741
  }
10741
10742
  // ── memcell 账本 ──────────────────────────────────────────
10742
10743
  insertMemcell(cell) {
@@ -13250,13 +13251,17 @@ var init_session_map = __esm({
13250
13251
 
13251
13252
  // src/cc-driver/long-http.ts
13252
13253
  import { request as request3 } from "node:http";
13253
- function longPostJson(url, body, headers = {}, signal) {
13254
+ function longPostJson(url, body, headers = {}, signal, acknowledgment) {
13254
13255
  const data = Buffer.from(JSON.stringify(body));
13255
13256
  return new Promise((resolve12, reject) => {
13256
13257
  const req = request3(url, { method: "POST", headers: { ...headers, "Content-Length": String(data.byteLength) } }, (res) => {
13258
+ if (acknowledgment && res.statusCode === 200 && res.headers[CC_JOB_HEADER] === acknowledgment.jobId) acknowledgment.onAccepted();
13257
13259
  const chunks = [];
13258
13260
  res.on("data", (chunk) => chunks.push(chunk));
13259
- res.on("error", reject);
13261
+ res.on("error", (err) => {
13262
+ cleanup();
13263
+ reject(err);
13264
+ });
13260
13265
  res.on("end", () => {
13261
13266
  cleanup();
13262
13267
  const text2 = Buffer.concat(chunks).toString("utf8");
@@ -13288,9 +13293,11 @@ function longPostJson(url, body, headers = {}, signal) {
13288
13293
  req.end(data);
13289
13294
  });
13290
13295
  }
13296
+ var CC_JOB_HEADER;
13291
13297
  var init_long_http = __esm({
13292
13298
  "src/cc-driver/long-http.ts"() {
13293
13299
  "use strict";
13300
+ CC_JOB_HEADER = "x-engine7-cc-job-id";
13294
13301
  }
13295
13302
  });
13296
13303
 
@@ -13344,19 +13351,31 @@ async function findDesktopTargets(workDir, sessionId) {
13344
13351
  }
13345
13352
  return targets;
13346
13353
  }
13347
- async function askDesktop(target, prompt, source, signal) {
13354
+ async function askDesktop(target, prompt, source, signal, acknowledgment) {
13355
+ const endpoint = acknowledgment ? "submit" : "ask";
13348
13356
  const { status, json: result } = await longPostJson(
13349
- `http://127.0.0.1:${target.port}/ask`,
13350
- { prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13357
+ `http://127.0.0.1:${target.port}/${endpoint}`,
13358
+ { prompt, source, jobId: acknowledgment?.jobId, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13351
13359
  { authorization: `Bearer ${target.token}` },
13352
- signal
13360
+ signal,
13361
+ acknowledgment
13353
13362
  );
13354
- if (status !== 200) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
13363
+ if (status !== 200 || result?.error) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
13355
13364
  if (result.sessionId !== target.sessionId || typeof result.text !== "string" || typeof result.isError !== "boolean") {
13356
13365
  throw failure("Desktop CC returned an invalid result");
13357
13366
  }
13358
13367
  return result;
13359
13368
  }
13369
+ async function stopDesktopJob(target, jobId) {
13370
+ const { status, json } = await longPostJson(
13371
+ `http://127.0.0.1:${target.port}/stop`,
13372
+ { jobId, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13373
+ { authorization: `Bearer ${target.token}` },
13374
+ AbortSignal.timeout(5e3)
13375
+ );
13376
+ if (status !== 200) throw failure(json?.error || `Desktop CC HTTP ${status}`, status);
13377
+ return json?.stopped === true;
13378
+ }
13360
13379
  var registryDir, canonical2, failure, alive;
13361
13380
  var init_desktop = __esm({
13362
13381
  "src/cc-driver/desktop.ts"() {
@@ -13804,6 +13823,7 @@ var init_driver = __esm({
13804
13823
  revision = 0;
13805
13824
  idleWaiters = [];
13806
13825
  abort = null;
13826
+ activeJob;
13807
13827
  /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
13808
13828
  feeder = null;
13809
13829
  sessionId = null;
@@ -13848,13 +13868,17 @@ var init_driver = __esm({
13848
13868
  void this.drain();
13849
13869
  }
13850
13870
  /** External callers use the same FIFO; they never answer a pending permission card. */
13851
- ask(prompt, source, expectedSessionId, signal) {
13852
- if (this.closed) return Promise.reject(requestError("CC binding is stopping", 503));
13853
- if (!prompt.trim()) return Promise.reject(requestError("prompt is required", 400));
13854
- if (signal?.aborted) return Promise.reject(requestError("CC request cancelled", 499));
13855
- if (this.sessionId !== expectedSessionId) return Promise.reject(requestError("CC session changed; select the current binding again"));
13856
- if (this.queue.length >= MAX_QUEUE) return Promise.reject(requestError("CC queue is full", 429));
13857
- const job = { prompt: prompt.trim(), source, expectedSessionId, signal };
13871
+ async ask(prompt, source, expectedSessionId, signal) {
13872
+ return this.submit(prompt, source, expectedSessionId, signal);
13873
+ }
13874
+ submit(prompt, source, expectedSessionId, signal, id3, onSession) {
13875
+ if (this.closed) throw requestError("CC binding is stopping", 503);
13876
+ if (!prompt.trim()) throw requestError("prompt is required", 400);
13877
+ if (signal?.aborted) throw requestError("CC request cancelled", 499);
13878
+ if (this.sessionId !== expectedSessionId) throw requestError("CC session changed; select the current binding again");
13879
+ if (id3 && (this.activeJob?.id === id3 || this.queue.some((job2) => job2.id === id3))) throw requestError("CC job already exists");
13880
+ if (this.queue.length >= MAX_QUEUE) throw requestError("CC queue is full", 429);
13881
+ const job = { id: id3, prompt: prompt.trim(), source, expectedSessionId, expectedRevision: id3 ? this.revision : void 0, signal, onSession };
13858
13882
  const cancel = () => {
13859
13883
  const index = this.queue.indexOf(job);
13860
13884
  if (index >= 0) {
@@ -13869,7 +13893,16 @@ var init_driver = __esm({
13869
13893
  signal?.addEventListener("abort", cancel, { once: true });
13870
13894
  void this.drain();
13871
13895
  });
13872
- return pending.finally(() => signal?.removeEventListener("abort", cancel));
13896
+ return signal ? pending.finally(() => signal.removeEventListener("abort", cancel)) : pending;
13897
+ }
13898
+ stopJob(id3) {
13899
+ const index = this.queue.findIndex((job) => job.id === id3);
13900
+ if (index >= 0) {
13901
+ this.queue.splice(index, 1)[0].reject?.(requestError("CC request cancelled (stop)", 499));
13902
+ return true;
13903
+ }
13904
+ if (this.activeJob?.id === id3) return this.activeJob.stop?.() ?? false;
13905
+ return false;
13873
13906
  }
13874
13907
  /** Reload/stop must not leave the old hub executing queued work. */
13875
13908
  shutdown() {
@@ -13895,6 +13928,9 @@ var init_driver = __esm({
13895
13928
  stop() {
13896
13929
  this.abort?.abort();
13897
13930
  }
13931
+ get queued() {
13932
+ return this.queue.length;
13933
+ }
13898
13934
  get busy() {
13899
13935
  return this.draining;
13900
13936
  }
@@ -13908,15 +13944,17 @@ var init_driver = __esm({
13908
13944
  await this.predecessor;
13909
13945
  while (!this.closed && this.queue.length > 0) {
13910
13946
  const job = this.queue.shift();
13947
+ this.activeJob = job;
13911
13948
  try {
13912
13949
  if (job.signal?.aborted) throw requestError("CC request cancelled", 499);
13913
- if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
13950
+ const changed = job.expectedRevision !== void 0 ? job.expectedRevision !== this.revision : job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId;
13951
+ if (changed) {
13914
13952
  throw requestError("CC session changed while this request was queued");
13915
13953
  }
13916
13954
  if (job.source) {
13917
13955
  const prompt = `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
13918
13956
  ${job.prompt}`;
13919
- const result = await this.runTurn(prompt, job.signal, true);
13957
+ const result = await this.runTurn(prompt, job.signal, true, job);
13920
13958
  job.resolve?.(result);
13921
13959
  } else {
13922
13960
  await this.runStreaming(job);
@@ -13925,6 +13963,8 @@ ${job.prompt}`;
13925
13963
  job.reject?.(err);
13926
13964
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
13927
13965
  await this.sendText(`[cc-driver] \u8FD9\u6B21\u4EFB\u52A1\u5931\u8D25\uFF1A${err?.message || String(err)}`);
13966
+ } finally {
13967
+ this.activeJob = void 0;
13928
13968
  }
13929
13969
  }
13930
13970
  } finally {
@@ -13932,12 +13972,24 @@ ${job.prompt}`;
13932
13972
  for (const resolve12 of this.idleWaiters.splice(0)) resolve12();
13933
13973
  }
13934
13974
  }
13935
- async runTurn(prompt, signal, external = false) {
13975
+ async runTurn(prompt, signal, external = false, job) {
13936
13976
  const ac = new AbortController();
13937
13977
  this.abort = ac;
13978
+ if (job?.id) job.stop = () => {
13979
+ ac.abort();
13980
+ return true;
13981
+ };
13938
13982
  const resumedFrom = this.sessionId;
13939
13983
  const revision = this.revision;
13940
13984
  let turnSessionId = resumedFrom;
13985
+ const observeSession = (id3) => {
13986
+ try {
13987
+ job?.onSession?.(id3);
13988
+ } catch (error) {
13989
+ console.error("[cc-driver] task session update failed:", error.message);
13990
+ }
13991
+ };
13992
+ observeSession(turnSessionId);
13941
13993
  const cancel = () => ac.abort();
13942
13994
  signal?.addEventListener("abort", cancel, { once: true });
13943
13995
  if (signal?.aborted) ac.abort();
@@ -13961,13 +14013,31 @@ ${job.prompt}`;
13961
14013
  const acc = this.makeStreamAccumulator();
13962
14014
  try {
13963
14015
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
14016
+ ac.signal.throwIfAborted();
13964
14017
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
13965
14018
  if (desktops[0]) {
13966
- const result2 = await askDesktop(desktops[0], prompt, this.key, ac.signal);
14019
+ const desktop = desktops[0];
14020
+ let result2;
14021
+ if (job?.id) {
14022
+ const jobId = job.id;
14023
+ let acknowledge;
14024
+ const accepted = new Promise((resolve12) => {
14025
+ acknowledge = resolve12;
14026
+ });
14027
+ job.stop = async () => await accepted && stopDesktopJob(desktop, jobId);
14028
+ try {
14029
+ result2 = await askDesktop(desktop, prompt, this.key, ac.signal, { jobId, onAccepted: () => acknowledge(true) });
14030
+ } finally {
14031
+ acknowledge(false);
14032
+ }
14033
+ } else {
14034
+ result2 = await askDesktop(desktop, prompt, this.key, ac.signal);
14035
+ }
13967
14036
  finalText = result2.text;
13968
14037
  isError = result2.isError;
13969
14038
  gotResult = true;
13970
14039
  turnSessionId = result2.sessionId;
14040
+ observeSession(turnSessionId);
13971
14041
  if (this.revision === revision) this.sessionId = result2.sessionId;
13972
14042
  } else {
13973
14043
  if (resumedFrom && nativeSessionOwners(resumedFrom).length) {
@@ -13980,6 +14050,7 @@ ${job.prompt}`;
13980
14050
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
13981
14051
  void this.sendText(`[cc-driver] \u9996\u6B21\u4F7F\u7528\uFF1A\u6B63\u5728\u4E0B\u8F7D ${label}\uFF08${mb}\uFF0C\u53EA\u6B64\u4E00\u6B21\uFF09\uFF0C\u5B8C\u6210\u540E\u81EA\u52A8\u7EE7\u7EED\u2026`);
13982
14052
  });
14053
+ ac.signal.throwIfAborted();
13983
14054
  const stream = query({
13984
14055
  prompt,
13985
14056
  options: {
@@ -14022,6 +14093,7 @@ ${job.prompt}`;
14022
14093
  const r = msg2;
14023
14094
  if (r.session_id) {
14024
14095
  turnSessionId = r.session_id;
14096
+ observeSession(turnSessionId);
14025
14097
  if (this.revision === revision) this.sessionId = r.session_id;
14026
14098
  }
14027
14099
  isError = r.is_error === true;
@@ -14032,6 +14104,7 @@ ${job.prompt}`;
14032
14104
  const sid = msg2.session_id;
14033
14105
  if (sid) {
14034
14106
  turnSessionId = sid;
14107
+ observeSession(turnSessionId);
14035
14108
  if (this.revision === revision) this.sessionId = sid;
14036
14109
  }
14037
14110
  } else {
@@ -14041,6 +14114,7 @@ ${job.prompt}`;
14041
14114
  }
14042
14115
  if (turnSessionId && gotResult && this.revision === revision) this.map.switchTo(this.key, turnSessionId, this.workDir);
14043
14116
  } finally {
14117
+ if (job) job.stop = void 0;
14044
14118
  this.abort = null;
14045
14119
  signal?.removeEventListener("abort", cancel);
14046
14120
  }
@@ -14641,6 +14715,164 @@ var init_router = __esm({
14641
14715
  }
14642
14716
  });
14643
14717
 
14718
+ // src/services/adaptive-proxy.ts
14719
+ var adaptive_proxy_exports = {};
14720
+ __export(adaptive_proxy_exports, {
14721
+ createProxySocketAgent: () => createProxySocketAgent,
14722
+ getProxyDispatcher: () => getProxyDispatcher,
14723
+ isAdaptiveProxy: () => isAdaptiveProxy
14724
+ });
14725
+ import net from "node:net";
14726
+ import tls from "node:tls";
14727
+ import { HttpsProxyAgent } from "https-proxy-agent";
14728
+ import { Agent as Agent2, Client, ProxyAgent, errors as errors2 } from "undici";
14729
+ function proxyAddress(value) {
14730
+ const bareLoopback = /^(?:localhost\.?|127(?:\.\d{1,3}){3}|\[::1\]):\d+$/i;
14731
+ return new URL(bareLoopback.test(value) ? `http://${value}` : value);
14732
+ }
14733
+ function localProxyKey(url) {
14734
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
14735
+ const host = url.hostname.replace(/\.$/, "");
14736
+ if (host !== "localhost" && host !== "[::1]" && !/^127\./.test(host)) return;
14737
+ return `${host}:${url.port || (url.protocol === "https:" ? 443 : 80)}`;
14738
+ }
14739
+ function isAdaptiveProxy(proxy) {
14740
+ return localProxyKey(proxyAddress(proxy.trim())) !== void 0;
14741
+ }
14742
+ function proxyUnavailable(key4) {
14743
+ return (unreachableUntil.get(key4) ?? -Infinity) > Date.now();
14744
+ }
14745
+ function markUnavailable(key4) {
14746
+ unreachableUntil.set(key4, Date.now() + RETRY_PROXY_AFTER_MS);
14747
+ }
14748
+ function isTcpDialFailure(error) {
14749
+ if (error instanceof AggregateError) {
14750
+ return error.errors.length > 0 && error.errors.every(isTcpDialFailure);
14751
+ }
14752
+ const err = error;
14753
+ return err?.syscall === "connect" && dialFailureCodes.has(err.code ?? "");
14754
+ }
14755
+ function getProxyDispatcher(value) {
14756
+ const raw = value?.trim();
14757
+ if (!raw) return;
14758
+ const cached2 = dispatchers.get(raw);
14759
+ if (cached2) return cached2;
14760
+ const url = proxyAddress(raw);
14761
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
14762
+ throw new Error(
14763
+ `\u4E0D\u652F\u6301\u7684\u4EE3\u7406\u534F\u8BAE ${url.protocol}\uFF08\u4EC5 http/https \u53EF\u76F4\u63A5\u4F7F\u7528\uFF1Bsocks5 \u7B49\u8BF7\u5148\u8F6C\u6210 http \u4EE3\u7406\uFF0C\u5982 gost/privoxy\uFF09\uFF1A${raw}`
14764
+ );
14765
+ }
14766
+ const key4 = localProxyKey(url);
14767
+ const dispatcher = key4 ? new AdaptiveProxyDispatcher(url.href, key4) : new ProxyAgent({ uri: url.href });
14768
+ dispatchers.set(raw, dispatcher);
14769
+ return dispatcher;
14770
+ }
14771
+ function createProxySocketAgent(value) {
14772
+ const url = proxyAddress(value.trim());
14773
+ const key4 = localProxyKey(url);
14774
+ return key4 ? new AdaptiveProxySocketAgent(url, key4) : new HttpsProxyAgent(url);
14775
+ }
14776
+ var RETRY_PROXY_AFTER_MS, LOCAL_CONNECT_TIMEOUT_MS, unreachableUntil, failedProxyDials, dispatchers, direct, dialFailureCodes, AdaptiveProxyDispatcher, AdaptiveProxySocketAgent;
14777
+ var init_adaptive_proxy = __esm({
14778
+ "src/services/adaptive-proxy.ts"() {
14779
+ "use strict";
14780
+ RETRY_PROXY_AFTER_MS = 5e3;
14781
+ LOCAL_CONNECT_TIMEOUT_MS = 1e3;
14782
+ unreachableUntil = /* @__PURE__ */ new Map();
14783
+ failedProxyDials = /* @__PURE__ */ new WeakSet();
14784
+ dispatchers = /* @__PURE__ */ new Map();
14785
+ direct = new Agent2();
14786
+ dialFailureCodes = /* @__PURE__ */ new Set(["ECONNREFUSED", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH", "EADDRNOTAVAIL"]);
14787
+ AdaptiveProxyDispatcher = class extends ProxyAgent {
14788
+ constructor(uri, key4) {
14789
+ super({
14790
+ uri,
14791
+ proxyTls: { timeout: LOCAL_CONNECT_TIMEOUT_MS },
14792
+ clientFactory(origin, opts) {
14793
+ const { connect } = opts;
14794
+ return new Client(origin, {
14795
+ connect(options, callback) {
14796
+ let tcpConnected = false;
14797
+ const socket = connect(options, (...result) => {
14798
+ const [error] = result;
14799
+ if (error && !tcpConnected && (isTcpDialFailure(error) || error.code === "UND_ERR_CONNECT_TIMEOUT")) {
14800
+ markUnavailable(key4);
14801
+ failedProxyDials.add(error);
14802
+ }
14803
+ callback(...result);
14804
+ });
14805
+ socket.once("connect", () => {
14806
+ tcpConnected = true;
14807
+ });
14808
+ return socket;
14809
+ }
14810
+ });
14811
+ }
14812
+ });
14813
+ this.key = key4;
14814
+ }
14815
+ dispatch(options, handler) {
14816
+ if (!this.closed && !this.destroyed && proxyUnavailable(this.key)) {
14817
+ const headers = options.headers;
14818
+ const keys = !headers ? [] : Array.isArray(headers) ? headers.filter((_, index) => index % 2 === 0) : Symbol.iterator in headers ? Array.from(headers, ([name]) => name) : Object.keys(headers);
14819
+ if (keys.some((name) => name.toLowerCase() === "proxy-authorization")) {
14820
+ throw new errors2.InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
14821
+ }
14822
+ return direct.dispatch(options, handler);
14823
+ }
14824
+ let connected = false;
14825
+ const extended = handler;
14826
+ const guarded = {
14827
+ onConnect: (abort) => {
14828
+ connected = true;
14829
+ handler.onConnect?.(abort);
14830
+ },
14831
+ onError: (error) => {
14832
+ if (!connected && failedProxyDials.has(error)) {
14833
+ direct.dispatch(options, handler);
14834
+ } else {
14835
+ handler.onError?.(error);
14836
+ }
14837
+ },
14838
+ onHeaders: handler.onHeaders?.bind(handler),
14839
+ onData: handler.onData?.bind(handler),
14840
+ onComplete: handler.onComplete?.bind(handler),
14841
+ onUpgrade: handler.onUpgrade?.bind(handler),
14842
+ onResponseStarted: handler.onResponseStarted?.bind(handler),
14843
+ onBodySent: handler.onBodySent?.bind(handler),
14844
+ onRequestSent: extended.onRequestSent?.bind(handler)
14845
+ };
14846
+ return super.dispatch(options, guarded);
14847
+ }
14848
+ };
14849
+ AdaptiveProxySocketAgent = class extends HttpsProxyAgent {
14850
+ constructor(url, key4) {
14851
+ super(url);
14852
+ this.key = key4;
14853
+ }
14854
+ async connect(req, opts) {
14855
+ if (!proxyUnavailable(this.key)) {
14856
+ try {
14857
+ return await super.connect(req, opts);
14858
+ } catch (error) {
14859
+ if (!isTcpDialFailure(error)) throw error;
14860
+ markUnavailable(this.key);
14861
+ if (req.destroyed) throw error;
14862
+ }
14863
+ }
14864
+ if (!opts.secureEndpoint) return net.connect({ ...opts, path: void 0 });
14865
+ const { host, servername } = opts;
14866
+ return tls.connect({
14867
+ ...opts,
14868
+ path: void 0,
14869
+ servername: servername ?? (host && !net.isIP(host) ? host : void 0)
14870
+ });
14871
+ }
14872
+ };
14873
+ }
14874
+ });
14875
+
14644
14876
  // src/calendar/dispatches.ts
14645
14877
  var dispatches_exports = {};
14646
14878
  __export(dispatches_exports, {
@@ -14701,10 +14933,10 @@ function installSQLiteWriteCapture(db2, source) {
14701
14933
  if (db2.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
14702
14934
  const exec = db2.exec, prepare = db2.prepare;
14703
14935
  let active, failed = false, closed = false, reading = false;
14704
- let direct;
14936
+ let direct2;
14705
14937
  const check = () => {
14706
14938
  if (closed) throw new Error("REPLICATION_TRANSACTION_CLOSED");
14707
- direct?.assertOpen();
14939
+ direct2?.assertOpen();
14708
14940
  };
14709
14941
  const wrappedExec = function(sql) {
14710
14942
  check();
@@ -14775,10 +15007,10 @@ function installSQLiteWriteCapture(db2, source) {
14775
15007
  db2.prepare = checkedPrepare;
14776
15008
  const transaction = (operation) => {
14777
15009
  check();
14778
- if (db2.isTransaction) return direct.scope(operation);
15010
+ if (db2.isTransaction) return direct2.scope(operation);
14779
15011
  db2.exec("BEGIN IMMEDIATE");
14780
15012
  try {
14781
- const result = direct.scope(operation);
15013
+ const result = direct2.scope(operation);
14782
15014
  if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
14783
15015
  db2.exec("COMMIT");
14784
15016
  return result;
@@ -14787,10 +15019,10 @@ function installSQLiteWriteCapture(db2, source) {
14787
15019
  throw error;
14788
15020
  }
14789
15021
  };
14790
- direct = installAutocommitCapture(db2, transaction);
15022
+ direct2 = installAutocommitCapture(db2, transaction);
14791
15023
  return {
14792
15024
  assertOpen: check,
14793
- scope: (operation) => direct.scope(operation),
15025
+ scope: (operation) => direct2.scope(operation),
14794
15026
  transaction,
14795
15027
  close() {
14796
15028
  if (closed) return;
@@ -14799,7 +15031,7 @@ function installSQLiteWriteCapture(db2, source) {
14799
15031
  source.endCapture(active);
14800
15032
  active = void 0;
14801
15033
  }
14802
- direct.close();
15034
+ direct2.close();
14803
15035
  db2.prepare = prepare;
14804
15036
  db2.exec = exec;
14805
15037
  closed = true;
@@ -16640,7 +16872,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16640
16872
  this.noteCascade(id3);
16641
16873
  this.db.prepare(`UPDATE actions SET basis_state='dirty',action_version=action_version+1,
16642
16874
  cancel_requested=CASE WHEN status='executing' THEN 1 ELSE cancel_requested END,
16643
- status=CASE WHEN status='queued' THEN 'cancelled' ELSE status END
16875
+ status=CASE WHEN status='queued' THEN 'cancelled' ELSE status END,
16876
+ cancel_reason=COALESCE(cancel_reason, CASE WHEN status='queued' THEN 'graph_basis_changed' END)
16644
16877
  WHERE intent_id=? AND status IN ('queued','executing')`).run(id3);
16645
16878
  this.db.prepare("UPDATE intent_runs SET state='stale',reason_code='graph_basis_changed',finished_at=? WHERE intent_id=? AND state='running'").run(Date.now(), id3);
16646
16879
  pending.push(...this.dependencies.children(scope, [{ kind: "node", id: id3 }]));
@@ -16725,11 +16958,12 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16725
16958
  a.note ?? null
16726
16959
  );
16727
16960
  }
16728
- /** status='queued' AND scheduled_time<=now,按时间升序 */
16729
- dueActions(now2, limit2 = 20) {
16961
+ /** status='queued' AND scheduled_time<=now,按时间升序。excludeIds:sweep 翻页绕开已看过的(守卫跳过的) */
16962
+ dueActions(now2, limit2 = 20, excludeIds = []) {
16730
16963
  const rows = this.db.prepare(
16731
- `SELECT * FROM actions WHERE status='queued' AND scheduled_time <= ? ORDER BY scheduled_time ASC LIMIT ?`
16732
- ).all(now2, limit2);
16964
+ `SELECT * FROM actions WHERE status='queued' AND scheduled_time <= ?
16965
+ AND id NOT IN (SELECT value FROM json_each(?)) ORDER BY scheduled_time ASC LIMIT ?`
16966
+ ).all(now2, JSON.stringify(excludeIds), limit2);
16733
16967
  return rows.map(rowToAction);
16734
16968
  }
16735
16969
  /** queued 状态 action 的 intent_id 集合(去重) */
@@ -17329,7 +17563,7 @@ __export(voice_chat_tts_daemon_exports, {
17329
17563
  stopTtsDaemon: () => stopTtsDaemon
17330
17564
  });
17331
17565
  import { spawn } from "child_process";
17332
- import net from "net";
17566
+ import net2 from "net";
17333
17567
  import path13 from "path";
17334
17568
  import fs10 from "fs";
17335
17569
  function _log(msg2) {
@@ -17337,7 +17571,7 @@ function _log(msg2) {
17337
17571
  }
17338
17572
  function _healthOnce() {
17339
17573
  return new Promise((resolve12) => {
17340
- const sock = net.connect(SOCK_PATH);
17574
+ const sock = net2.connect(SOCK_PATH);
17341
17575
  sock.setTimeout(2e3);
17342
17576
  sock.on("connect", () => {
17343
17577
  sock.write(JSON.stringify({ action: "health" }) + "\n");
@@ -17390,9 +17624,6 @@ async function startTtsDaemon(warmupCfg) {
17390
17624
  _log(`spawning ${script}`);
17391
17625
  const env = {
17392
17626
  ...process.env,
17393
- // 显式注入代理(dashscope SDK 不自动读系统代理)
17394
- HTTP_PROXY: process.env.HTTP_PROXY || "http://127.0.0.1:7892",
17395
- HTTPS_PROXY: process.env.HTTPS_PROXY || "http://127.0.0.1:7892",
17396
17627
  TTS_DAEMON_SOCK: SOCK_PATH,
17397
17628
  ...warmupCfg?.apiKey ? { ALIYUN_API_KEY: warmupCfg.apiKey } : {},
17398
17629
  ...warmupCfg?.model ? { TTS_MODEL: warmupCfg.model } : {},
@@ -17462,7 +17693,6 @@ __export(withRetry_exports, {
17462
17693
  getRetryDelay: () => getRetryDelay,
17463
17694
  readWithTimeout: () => readWithTimeout
17464
17695
  });
17465
- import { ProxyAgent } from "undici";
17466
17696
  function sleep2(ms, signal) {
17467
17697
  return new Promise((resolve12, reject) => {
17468
17698
  if (signal?.aborted) {
@@ -17530,15 +17760,6 @@ function shouldRetry(status, errorBody) {
17530
17760
  if (errorBody?.includes('"type":"overloaded_error"')) return true;
17531
17761
  return false;
17532
17762
  }
17533
- function getProxyDispatcher(proxyUrl) {
17534
- if (!proxyUrl) return void 0;
17535
- let agent = proxyAgentCache.get(proxyUrl);
17536
- if (!agent) {
17537
- agent = new ProxyAgent({ uri: proxyUrl });
17538
- proxyAgentCache.set(proxyUrl, agent);
17539
- }
17540
- return agent;
17541
- }
17542
17763
  async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, retryPolicy) {
17543
17764
  const configuredRetries = getMaxRetries();
17544
17765
  const maxRetries = retryPolicy?.maxRetries === void 0 ? configuredRetries : Math.min(configuredRetries, Math.max(0, Math.floor(retryPolicy.maxRetries)));
@@ -17676,10 +17897,11 @@ function readWithTimeout(reader, timeoutMs, signal) {
17676
17897
  if (onAbort) signal?.removeEventListener("abort", onAbort);
17677
17898
  });
17678
17899
  }
17679
- var DEFAULT_MAX_RETRIES, BASE_DELAY_MS, MAX_DELAY_MS, DEFAULT_TIMEOUT_MS, READ_TIMEOUT_MS, FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS, proxyAgentCache;
17900
+ var DEFAULT_MAX_RETRIES, BASE_DELAY_MS, MAX_DELAY_MS, DEFAULT_TIMEOUT_MS, READ_TIMEOUT_MS, FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS;
17680
17901
  var init_withRetry = __esm({
17681
17902
  "src/services/withRetry.ts"() {
17682
17903
  "use strict";
17904
+ init_adaptive_proxy();
17683
17905
  DEFAULT_MAX_RETRIES = 10;
17684
17906
  BASE_DELAY_MS = 500;
17685
17907
  MAX_DELAY_MS = 32e3;
@@ -17687,7 +17909,6 @@ var init_withRetry = __esm({
17687
17909
  READ_TIMEOUT_MS = 6e4;
17688
17910
  FIRST_READ_TIMEOUT_MS = parseInt(process.env.API_TIMEOUT_MS || "", 10) || 6e5;
17689
17911
  NO_PROGRESS_TIMEOUT_MS = parseInt(process.env.STREAM_NO_PROGRESS_TIMEOUT_MS || "", 10) || 3e5;
17690
- proxyAgentCache = /* @__PURE__ */ new Map();
17691
17912
  }
17692
17913
  });
17693
17914
 
@@ -19140,7 +19361,7 @@ function validManagement(input) {
19140
19361
  return true;
19141
19362
  }
19142
19363
  function createTravelAuthorityServer(options) {
19143
- const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls2 } = options;
19364
+ const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls3 } = options;
19144
19365
  const proxies = /* @__PURE__ */ new Set(), peers = /* @__PURE__ */ new Map(), managers = /* @__PURE__ */ new Map();
19145
19366
  const fingerprint = (value) => {
19146
19367
  const normalized = value.replaceAll(":", "").toLowerCase();
@@ -19185,7 +19406,7 @@ function createTravelAuthorityServer(options) {
19185
19406
  retirees.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
19186
19407
  }
19187
19408
  const reports = /* @__PURE__ */ new Set(), management = /* @__PURE__ */ new Set();
19188
- const server = createServer({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19409
+ const server = createServer({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19189
19410
  res.setHeader("Content-Type", "application/json");
19190
19411
  res.setHeader("Cache-Control", "no-store");
19191
19412
  const reply = (status, value) => {
@@ -20040,7 +20261,7 @@ function decodeBody(value, maximum = 16 * 1024 * 1024) {
20040
20261
  return body;
20041
20262
  }
20042
20263
  function createTravelGatewayServer(options) {
20043
- const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls2 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
20264
+ const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls3 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
20044
20265
  for (const [fingerprint, credential] of Object.entries(allowedPeers)) {
20045
20266
  const normalized = fingerprint.replaceAll(":", "").toLowerCase();
20046
20267
  if (!/^[a-f0-9]{64}$/.test(normalized) || peers.has(normalized)) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
@@ -20053,7 +20274,7 @@ function createTravelGatewayServer(options) {
20053
20274
  }
20054
20275
  if (!peers.size || typeof platform.deliver !== "function") throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
20055
20276
  let inFlight = 0;
20056
- const server = createServer2({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
20277
+ const server = createServer2({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
20057
20278
  res.setHeader("Cache-Control", "no-store");
20058
20279
  res.setHeader("Content-Type", "application/json");
20059
20280
  const reply = (status, value) => {
@@ -20434,12 +20655,55 @@ var AgentRegistryImpl = class {
20434
20655
  var agentRegistry = new AgentRegistryImpl();
20435
20656
 
20436
20657
  // src/channels/discord.ts
20437
- import { Client, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20438
- import { ProxyAgent as UndiciProxyAgent } from "undici";
20439
- import { HttpsProxyAgent } from "https-proxy-agent";
20658
+ init_adaptive_proxy();
20659
+ import { Client as Client2, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20660
+
20661
+ // src/channels/discord-gateway-proxy.ts
20662
+ init_adaptive_proxy();
20663
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
20664
+ import https from "node:https";
20665
+ import { SimpleShardingStrategy } from "@discordjs/ws";
20666
+ var gatewayRoute = new AsyncLocalStorage4();
20667
+ function gatewayDestination(url) {
20668
+ const { hostname, port } = new URL(url);
20669
+ return `${hostname.replace(/^\[|\]$/g, "")}:${port || 443}`;
20670
+ }
20671
+ var installed = false;
20672
+ function discordGatewayProxy(proxy) {
20673
+ if (!installed) {
20674
+ installed = true;
20675
+ const request4 = https.request;
20676
+ https.request = (...args) => {
20677
+ const route = gatewayRoute.getStore();
20678
+ const [options] = args;
20679
+ if (route && options && typeof options === "object" && !(options instanceof URL) && options.agent === void 0 && options.headers?.Upgrade === "websocket" && route.destinations.has(`${options.hostname ?? options.host}:${options.port ?? 443}`)) {
20680
+ args[0] = { ...options, agent: route.agent };
20681
+ }
20682
+ return Reflect.apply(request4, https, args);
20683
+ };
20684
+ }
20685
+ const agent = createProxySocketAgent(proxy);
20686
+ return (manager) => {
20687
+ const strategy = new SimpleShardingStrategy(manager);
20688
+ const destinations = /* @__PURE__ */ new Set();
20689
+ const retrieveSession = manager.options.retrieveSessionInfo.bind(manager.options);
20690
+ manager.options.retrieveSessionInfo = async (shardId) => {
20691
+ const session = await retrieveSession(shardId);
20692
+ if (session?.resumeURL) destinations.add(gatewayDestination(session.resumeURL));
20693
+ return session;
20694
+ };
20695
+ const connect = strategy.connect.bind(strategy);
20696
+ strategy.connect = async () => {
20697
+ const { url } = await manager.fetchGatewayInformation();
20698
+ destinations.add(gatewayDestination(url));
20699
+ return gatewayRoute.run({ agent, destinations }, connect);
20700
+ };
20701
+ return strategy;
20702
+ };
20703
+ }
20440
20704
 
20441
20705
  // src/memory/external-effect.ts
20442
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20706
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
20443
20707
  import { createHash as createHash25 } from "node:crypto";
20444
20708
  import { join as join17 } from "node:path";
20445
20709
 
@@ -20559,8 +20823,8 @@ function assertMemoryExecution(stateDir, workspace, context) {
20559
20823
  // src/mem7/host-turn.ts
20560
20824
  init_store();
20561
20825
  init_host_turns();
20562
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
20563
- var turns = new AsyncLocalStorage4();
20826
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20827
+ var turns = new AsyncLocalStorage5();
20564
20828
  function hasHostTurnContext() {
20565
20829
  return Boolean(turns.getStore());
20566
20830
  }
@@ -20604,8 +20868,8 @@ function beginHostTurnEffect() {
20604
20868
 
20605
20869
  // src/memory/external-effect.ts
20606
20870
  init_runtime_authority();
20607
- var effects = new AsyncLocalStorage5();
20608
- var externalFences = new AsyncLocalStorage5();
20871
+ var effects = new AsyncLocalStorage6();
20872
+ var externalFences = new AsyncLocalStorage6();
20609
20873
  function withExternalEffectFence(check, run) {
20610
20874
  return externalFences.run(check, run);
20611
20875
  }
@@ -20894,7 +21158,7 @@ var DiscordAdapter = class _DiscordAdapter {
20894
21158
  // 🔴 P0: 消息去重 — Discord RESUME 重连会重放 messageCreate
20895
21159
  recentMessageIds = /* @__PURE__ */ new Set();
20896
21160
  constructor(clientOrConfig, config) {
20897
- if (clientOrConfig instanceof Client) {
21161
+ if (clientOrConfig instanceof Client2) {
20898
21162
  this.client = clientOrConfig;
20899
21163
  this.config = config ?? {};
20900
21164
  this.ownsClient = false;
@@ -20912,24 +21176,10 @@ var DiscordAdapter = class _DiscordAdapter {
20912
21176
  partials: [Partials.Channel, Partials.Message]
20913
21177
  };
20914
21178
  if (this.config.proxy) {
20915
- const proxyUrl = this.config.proxy;
20916
- clientOptions.rest = { agent: new UndiciProxyAgent({ uri: proxyUrl }) };
20917
- const httpsAgent = new HttpsProxyAgent(proxyUrl);
20918
- const https = __require("https");
20919
- const origRequest = https.request;
20920
- if (!origRequest.__discordProxyPatched) {
20921
- https.request = function(opts, cb) {
20922
- const host = typeof opts === "string" ? "" : opts?.hostname || opts?.host || "";
20923
- if ((host.includes("discord") || host.includes("gateway")) && typeof opts === "object" && !opts.agent) {
20924
- opts.agent = httpsAgent;
20925
- }
20926
- return origRequest.call(this, opts, cb);
20927
- };
20928
- https.request.__discordProxyPatched = true;
20929
- console.log(`[discord] https.request patched for Discord gateway \u2192 ${proxyUrl}`);
20930
- }
21179
+ clientOptions.rest = { agent: getProxyDispatcher(this.config.proxy) };
21180
+ clientOptions.ws = { buildStrategy: discordGatewayProxy(this.config.proxy) };
20931
21181
  }
20932
- this.client = new Client(clientOptions);
21182
+ this.client = new Client2(clientOptions);
20933
21183
  this.ownsClient = true;
20934
21184
  }
20935
21185
  this.progressCards = new DiscordProgressCards({
@@ -20990,7 +21240,7 @@ var DiscordAdapter = class _DiscordAdapter {
20990
21240
  }
20991
21241
  try {
20992
21242
  const init = { signal: AbortSignal.timeout(HISTORY_ATTACH_TIMEOUT_MS) };
20993
- if (this.config.proxy) init.dispatcher = new UndiciProxyAgent({ uri: this.config.proxy });
21243
+ if (this.config.proxy) init.dispatcher = getProxyDispatcher(this.config.proxy);
20994
21244
  const res = await fetch(att.url, init);
20995
21245
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
20996
21246
  const buf = Buffer.from(await res.arrayBuffer());
@@ -21836,6 +22086,10 @@ var FeishuAdapter = class _FeishuAdapter {
21836
22086
  }
21837
22087
  }
21838
22088
  }
22089
+ /** 公开上传入口(1130 gmail 连接卡片等业务卡用):委托 _uploadImage。 */
22090
+ async uploadImage(buffer, filename) {
22091
+ return this._uploadImage(buffer, filename);
22092
+ }
21839
22093
  async _uploadImage(buffer, filename) {
21840
22094
  const token = await this._getTenantToken();
21841
22095
  const resp = await fetch("https://open.feishu.cn/open-apis/im/v1/images", {
@@ -23783,7 +24037,7 @@ import { promisify as promisify3 } from "node:util";
23783
24037
  init_voice_chat_tts_daemon();
23784
24038
  import * as path14 from "node:path";
23785
24039
  import * as os6 from "node:os";
23786
- import net2 from "net";
24040
+ import net3 from "net";
23787
24041
  var execFileAsync = promisify3(execFile);
23788
24042
  var VOICE_DIR = path14.join(os6.tmpdir(), "engine-voice");
23789
24043
  async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
@@ -23795,7 +24049,7 @@ async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
23795
24049
  }
23796
24050
  }
23797
24051
  return new Promise((resolve12, reject) => {
23798
- const sock = net2.connect(getSockPath());
24052
+ const sock = net3.connect(getSockPath());
23799
24053
  let buf = "";
23800
24054
  const finish = (err) => {
23801
24055
  try {
@@ -24007,8 +24261,8 @@ var DeskBuddyAdapter = class {
24007
24261
  startAsr() {
24008
24262
  if (this.asrSock) return;
24009
24263
  const port = this.asrBackend === "sensevoice" ? 9790 : 9791;
24010
- const net3 = __require("node:net");
24011
- const sock = net3.connect(port, "127.0.0.1");
24264
+ const net4 = __require("node:net");
24265
+ const sock = net4.connect(port, "127.0.0.1");
24012
24266
  sock.setNoDelay(true);
24013
24267
  this.asrSock = sock;
24014
24268
  this.asrBuf = "";
@@ -24560,7 +24814,7 @@ var CcBridgeAdapter = class {
24560
24814
 
24561
24815
  // src/channels/telegram.ts
24562
24816
  import fs13 from "node:fs";
24563
- import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
24817
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
24564
24818
  import path17 from "node:path";
24565
24819
 
24566
24820
  // src/channels/telegram-offset.ts
@@ -24752,7 +25006,7 @@ var PreviewEditThrottle = class {
24752
25006
  /** 提交一次编辑;返回的 promise 在"该内容(或其后覆盖它的更新内容)真实落盘"后 settle,失败 reject */
24753
25007
  submit(key4, req, run) {
24754
25008
  const s = this.st.get(key4) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
24755
- const guardedRun = AsyncLocalStorage6.bind(run);
25009
+ const guardedRun = AsyncLocalStorage7.bind(run);
24756
25010
  this.st.set(key4, s);
24757
25011
  return new Promise((resolve12, reject) => {
24758
25012
  const waiter = { resolve: resolve12, reject };
@@ -25938,9 +26192,6 @@ var QrManager = class {
25938
26192
  }
25939
26193
  };
25940
26194
 
25941
- // src/channels/whatsapp/socket.ts
25942
- import { HttpsProxyAgent as HttpsProxyAgent2 } from "https-proxy-agent";
25943
-
25944
26195
  // src/version.ts
25945
26196
  import { readFileSync as readFileSync12 } from "node:fs";
25946
26197
  import { dirname as dirname10, join as join21 } from "node:path";
@@ -25967,7 +26218,7 @@ function readEngineVersion() {
25967
26218
  }
25968
26219
 
25969
26220
  // src/channels/whatsapp/socket.ts
25970
- init_withRetry();
26221
+ init_adaptive_proxy();
25971
26222
  var VERSION_SOURCE_URL = "https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts";
25972
26223
  var VERSION_FETCH_TIMEOUT_MS = 3e3;
25973
26224
  var VERSION_FALLBACK_TIMEOUT_MS = 5e3;
@@ -26061,7 +26312,7 @@ async function makeWaSocket(opts) {
26061
26312
  connectTimeoutMs: 6e4,
26062
26313
  defaultQueryTimeoutMs: 6e4,
26063
26314
  // ws 层代理(https-proxy-agent,baileys 原生支持)
26064
- agent: opts.proxy ? new HttpsProxyAgent2(opts.proxy) : void 0,
26315
+ agent: opts.proxy ? createProxySocketAgent(opts.proxy) : void 0,
26065
26316
  // 媒体上传/下载走 native fetch,只认 undici dispatcher(防线 4,见文件头)
26066
26317
  fetchAgent: opts.proxy ? getProxyDispatcher(opts.proxy) : void 0,
26067
26318
  auth: { creds: auth.state.creds, keys },
@@ -27091,9 +27342,9 @@ function isPlanMode() {
27091
27342
  init_runtime_authority();
27092
27343
 
27093
27344
  // src/continuity/gateway-context.ts
27094
- import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
27095
- var contexts = new AsyncLocalStorage7();
27096
- var outputKinds = new AsyncLocalStorage7();
27345
+ import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
27346
+ var contexts = new AsyncLocalStorage8();
27347
+ var outputKinds = new AsyncLocalStorage8();
27097
27348
  var travelOutputKind = () => outputKinds.getStore() ?? "REPLY";
27098
27349
  function withTravelOutputKind(kind, run) {
27099
27350
  return outputKinds.run(kind, run);
@@ -27228,7 +27479,9 @@ function emitHookResponse(data) {
27228
27479
 
27229
27480
  // src/skills/skill-gate.ts
27230
27481
  init_strip_injected();
27482
+ init_writer();
27231
27483
  var USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
27484
+ var SKILL_CHANNELS = /* @__PURE__ */ new Set([...USER_CHANNELS, "chan7", "webhook"]);
27232
27485
  var loadedBySession = /* @__PURE__ */ new Map();
27233
27486
  var MAX_TRACKED_SESSIONS = 100;
27234
27487
  function beginSkillGate(sessionId) {
@@ -29482,7 +29735,9 @@ var SEARCH_ALIASES = /* @__PURE__ */ new Map([
29482
29735
  ["gmail", ["\u90AE\u7BB1", "\u90AE\u4EF6"]],
29483
29736
  ["device_data", ["\u8BBE\u5907\u8D44\u6599", "\u65E5\u5386", "\u63D0\u9192\u4E8B\u9879", "\u901A\u8BAF\u5F55", "\u8054\u7CFB\u4EBA", "\u5907\u5FD8\u5F55", "\u7167\u7247", "\u5065\u5EB7"]],
29484
29737
  ["cc_ask", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]],
29485
- ["cc_progress", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]]
29738
+ ["cc_progress", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]],
29739
+ ["cc_new", ["\u5C0FC", "\u684C\u9762CC", "Claude Code", "\u65B0\u5EFA CC \u4F1A\u8BDD"]],
29740
+ ["cc_stop", ["\u5C0FC", "\u684C\u9762CC", "Claude Code", "\u505C\u6B62 CC \u4EFB\u52A1"]]
29486
29741
  ]);
29487
29742
  function toolSearchAliases(name) {
29488
29743
  return SEARCH_ALIASES.get(name) ?? [];
@@ -30728,12 +30983,12 @@ var QueryEngine = class _QueryEngine {
30728
30983
  try {
30729
30984
  const url = "https://localhost:8116/voice-reply";
30730
30985
  if (url.startsWith("https://")) {
30731
- const https = await import("node:https");
30986
+ const https2 = await import("node:https");
30732
30987
  const postData = JSON.stringify({ text: line, isPlaceholder: true });
30733
30988
  assertExternalEffectCurrent();
30734
30989
  beginHostTurnEffect();
30735
30990
  await new Promise((resolve12, reject) => {
30736
- const req = https.request(url, {
30991
+ const req = https2.request(url, {
30737
30992
  method: "POST",
30738
30993
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) },
30739
30994
  rejectUnauthorized: false
@@ -33680,11 +33935,10 @@ var DingTalkAdapter = class _DingTalkAdapter {
33680
33935
  throw new Error("dingtalk clientId/clientSecret \u672A\u914D\u7F6E\uFF08\u5F00\u53D1\u8005\u540E\u53F0 \u2192 \u5E94\u7528 \u2192 \u51ED\u8BC1\uFF09");
33681
33936
  }
33682
33937
  if (this.cfg.proxy) {
33683
- const { getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_withRetry(), withRetry_exports));
33938
+ const { createProxySocketAgent: createProxySocketAgent2, getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_adaptive_proxy(), adaptive_proxy_exports));
33684
33939
  const dispatcher = getProxyDispatcher2(this.cfg.proxy);
33685
33940
  this.baseFetch = (url, init) => this.fetchImpl(url, { ...init, dispatcher });
33686
- const { HttpsProxyAgent: HttpsProxyAgent3 } = await import("https-proxy-agent");
33687
- this.wsAgent = new HttpsProxyAgent3(this.cfg.proxy);
33941
+ this.wsAgent = createProxySocketAgent2(this.cfg.proxy);
33688
33942
  this.token = new DingTalkTokenManager(this.cfg.clientId, this.cfg.clientSecret, (u, i) => this.baseFetch(u, i), this.now);
33689
33943
  console.log(`[dingtalk] outbound via proxy ${this.cfg.proxy}`);
33690
33944
  }
@@ -34245,7 +34499,7 @@ var DING_EDIT_INTERVAL_MS = 300;
34245
34499
 
34246
34500
  // src/channels/wecom-stream.ts
34247
34501
  import { EventEmitter as EventEmitter2 } from "node:events";
34248
- import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
34502
+ import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
34249
34503
  import { createHash as createHash35 } from "node:crypto";
34250
34504
  var WECOM_WS_URL = "wss://openws.work.weixin.qq.com";
34251
34505
  var HEARTBEAT_MS2 = 3e4;
@@ -34571,7 +34825,7 @@ var WecomStreamClient = class extends EventEmitter2 {
34571
34825
  const item = {
34572
34826
  frame,
34573
34827
  // The ack event which pumps this queue has another async context. Keep the sender's guards.
34574
- send: AsyncLocalStorage8.bind((ws) => {
34828
+ send: AsyncLocalStorage9.bind((ws) => {
34575
34829
  assertExternalEffectCurrent();
34576
34830
  ws.send(JSON.stringify(frame));
34577
34831
  }),
@@ -34881,12 +35135,11 @@ var WecomAdapter = class {
34881
35135
  this.loadRoutes();
34882
35136
  let wsAgent;
34883
35137
  if (this.cfg.proxy) {
34884
- const { getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_withRetry(), withRetry_exports));
35138
+ const { createProxySocketAgent: createProxySocketAgent2, getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_adaptive_proxy(), adaptive_proxy_exports));
34885
35139
  const dispatcher = getProxyDispatcher2(this.cfg.proxy);
34886
35140
  const base = this.fetchImpl;
34887
35141
  this.fetchImpl = (url, init) => base(url, { ...init, dispatcher });
34888
- const { HttpsProxyAgent: HttpsProxyAgent3 } = await import("https-proxy-agent");
34889
- wsAgent = new HttpsProxyAgent3(this.cfg.proxy);
35142
+ wsAgent = createProxySocketAgent2(this.cfg.proxy);
34890
35143
  }
34891
35144
  let wsCtor = this.cfg.wsCtor;
34892
35145
  if (!wsCtor) {
@@ -35521,7 +35774,7 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
35521
35774
  // src/continuity/gateway-feishu.ts
35522
35775
  init_gateway_media();
35523
35776
  import * as lark2 from "@larksuiteoapi/node-sdk";
35524
- import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
35777
+ import { AsyncLocalStorage as AsyncLocalStorage10 } from "node:async_hooks";
35525
35778
  import { basename as basename6 } from "node:path";
35526
35779
 
35527
35780
  // src/continuity/gateway-feishu-render.ts
@@ -35554,7 +35807,7 @@ var quiet = { error: () => {
35554
35807
  }, debug: () => {
35555
35808
  }, trace: () => {
35556
35809
  } };
35557
- var dispatchContext = new AsyncLocalStorage9();
35810
+ var dispatchContext = new AsyncLocalStorage10();
35558
35811
  var format = "engine7-feishu-gateway-inbound-v1";
35559
35812
  function createFeishuGatewayDispatcher(options) {
35560
35813
  return new lark2.EventDispatcher({ verificationToken: options.verificationToken, encryptKey: options.encryptKey, logger: quiet }).register({
@@ -35740,9 +35993,9 @@ import { basename as basename7 } from "node:path";
35740
35993
  function createRemoteTravelChannel(block, stateDir, channel = "feishu") {
35741
35994
  if (!stateDir || !runtimeAuthorityFor(stateDir)) throw new Error("TRAVEL_GATEWAY_RUNTIME_REQUIRED");
35742
35995
  validateTravelChannels(stateDir, { [channel]: block });
35743
- const tls2 = block.gatewayTls;
35744
- if (!tls2 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls2[key4] !== "string" || !tls2[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35745
- const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls2.caFile, 1024 * 1024), cert: readPrivateFile(tls2.certFile, 1024 * 1024), key: readPrivateFile(tls2.keyFile, 16384) });
35996
+ const tls3 = block.gatewayTls;
35997
+ if (!tls3 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls3[key4] !== "string" || !tls3[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
35998
+ const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls3.caFile, 1024 * 1024), cert: readPrivateFile(tls3.certFile, 1024 * 1024), key: readPrivateFile(tls3.keyFile, 16384) });
35746
35999
  return new RemoteTravelChannel({ client, channel, permit: () => runtimeAuthorityFor(stateDir).assert("INPUT"), pollIntervalMs: block.gatewayPollIntervalMs });
35747
36000
  }
35748
36001
  var RemoteTravelChannel = class {
@@ -36339,8 +36592,8 @@ var ChannelManager = class {
36339
36592
  /** 停止所有 adapter */
36340
36593
  async stopAll() {
36341
36594
  const results = await Promise.allSettled(this.adapters.map(async (adapter) => adapter.disconnect()));
36342
- const errors2 = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
36343
- if (errors2.length) throw new AggregateError(errors2, "CHANNEL_STOP_FAILED");
36595
+ const errors3 = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
36596
+ if (errors3.length) throw new AggregateError(errors3, "CHANNEL_STOP_FAILED");
36344
36597
  }
36345
36598
  /** 通道是否有已注册 adapter(投递前置判断用;1105 inbox-poller route 白名单替代硬编码) */
36346
36599
  hasChannel(channelName) {
@@ -36453,7 +36706,7 @@ function path35(value) {
36453
36706
  if (typeof value !== "string" || !isAbsolute5(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
36454
36707
  return resolve11(value);
36455
36708
  }
36456
- function tls(config) {
36709
+ function tls2(config) {
36457
36710
  return { ca: readPrivateFile(path35(config?.caFile), 1024 * 1024), cert: readPrivateFile(path35(config?.certFile), 1024 * 1024), key: readPrivateFile(path35(config?.keyFile), 16384) };
36458
36711
  }
36459
36712
  async function startTravelGateway(config) {
@@ -36462,7 +36715,7 @@ async function startTravelGateway(config) {
36462
36715
  for (const [name, value] of Object.entries(config.channels ?? {})) if (value?.enabled && !["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
36463
36716
  const feishuIngress = config.ingressEnabled !== false && config.feishu?.ingressEnabled !== false && config.channels?.feishu?.enabled !== false;
36464
36717
  if (feishuIngress && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
36465
- const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls(config.keyService.tls), timeoutMs: 1e4 };
36718
+ const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls2(config.keyService.tls), timeoutMs: 1e4 };
36466
36719
  const material = await fetchTravelKey(keyConfig);
36467
36720
  const keyDigest = createHash37("sha256").update(material.key).digest("hex");
36468
36721
  let keyWatermark = material.deletionWatermark;
@@ -36516,7 +36769,7 @@ async function startTravelGateway(config) {
36516
36769
  await store.migrateStoredInputs();
36517
36770
  if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
36518
36771
  platform = createFeishuGatewayPlatform(config.feishu);
36519
- server = createTravelGatewayServer({ ...tls(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: async (effect, body, assertCurrent) => {
36772
+ server = createTravelGatewayServer({ ...tls2(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: async (effect, body, assertCurrent) => {
36520
36773
  const packet = effect.kind === "MEDIA" ? (await Promise.resolve().then(() => (init_gateway_media(), gateway_media_exports))).decodeGatewayMedia(body).metadata : JSON.parse(body.toString());
36521
36774
  const channel = packet.channel ?? "feishu";
36522
36775
  if (channel === "feishu") return platform.deliver(effect, body, () => {
@@ -36537,7 +36790,7 @@ async function startTravelGateway(config) {
36537
36790
  if (config.control) {
36538
36791
  if (!Number.isSafeInteger(config.control.port) || config.control.port < 0 || config.control.port > 65535 || typeof config.control.host !== "string" || !config.control.host) throw new Error("TRAVEL_CONTROL_INVALID_LISTENER");
36539
36792
  controlServer = createTravelAuthorityServer({
36540
- ...tls(config.control.tls ?? config.tls),
36793
+ ...tls2(config.control.tls ?? config.tls),
36541
36794
  authority,
36542
36795
  proxyFingerprints: config.control.proxyFingerprints,
36543
36796
  allowedPeers: config.control.allowedPeers,