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.
@@ -6282,16 +6282,15 @@ function stripInjectedContext(text2) {
6282
6282
  function escapeRegExp(s) {
6283
6283
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
6284
6284
  }
6285
- var SKILL_GATE_HINT_PREFIX, SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
6285
+ var SYSTEM_REMINDER_BLOCK, INJECT_SECTION_HEADS, KNOWN_INJECTED_TEXT, INJECTED_LINE_PREFIXES, XML_BLOCK;
6286
6286
  var init_strip_injected = __esm({
6287
6287
  "src/messages/strip-injected.ts"() {
6288
6288
  "use strict";
6289
- SKILL_GATE_HINT_PREFIX = "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1";
6290
6289
  SYSTEM_REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/g;
6291
6290
  INJECT_SECTION_HEADS = /^(本轮对话|当前情绪状态|当前模式)/;
6292
6291
  KNOWN_INJECTED_TEXT = [
6293
- SKILL_GATE_HINT_PREFIX,
6294
- // skill-gate hint 默认/自定义前缀(1007 现行)
6292
+ "\u8FD9\u6761\u6D88\u606F\u662F\u5F00\u53D1\u4EFB\u52A1",
6293
+ // 旧版 skill-gate 提示前缀,兼容未打标签的历史
6295
6294
  "\u5F00\u53D1\u4EFB\u52A1\u8DEF\u6807\uFF0C\u6309\u573A\u666F\u5BF9\u53F7\u5165\u5EA7",
6296
6295
  // skill-gate hint(0912 老文案,历史 JSONL 兼容)
6297
6296
  "\u3010\u5B9A\u65F6\u5FC3\u8DF3\u3011\u8BF7 read HEARTBEAT.md"
@@ -8334,6 +8333,8 @@ function attachmentToMessage(attachment) {
8334
8333
  ${attachment.notifications.join("\n\n")}`
8335
8334
  )
8336
8335
  };
8336
+ case "coldstart_hint":
8337
+ return { role: "user", content: wrapInSystemReminder(attachment.text) };
8337
8338
  case "teammate_messages": {
8338
8339
  const lines = attachment.messages.map(
8339
8340
  (m) => m.summary ? `[From: ${m.from}] ${m.summary}
@@ -10916,32 +10917,32 @@ CREATE TABLE IF NOT EXISTS cluster_members (
10916
10917
  return { built: !hasStats, ms: Date.now() - started };
10917
10918
  }
10918
10919
  async close() {
10919
- const errors2 = [];
10920
+ const errors3 = [];
10920
10921
  try {
10921
10922
  this.capture?.close();
10922
10923
  } catch (error) {
10923
- errors2.push(error);
10924
+ errors3.push(error);
10924
10925
  }
10925
10926
  try {
10926
10927
  this.db.close();
10927
10928
  } catch (error) {
10928
- errors2.push(error);
10929
+ errors3.push(error);
10929
10930
  }
10930
10931
  try {
10931
10932
  await this.vectors?.close();
10932
10933
  } catch (error) {
10933
- errors2.push(error);
10934
+ errors3.push(error);
10934
10935
  } finally {
10935
10936
  this.vectors = null;
10936
10937
  }
10937
10938
  try {
10938
10939
  this.releaseRuntimeWriter?.();
10939
10940
  } catch (error) {
10940
- errors2.push(error);
10941
+ errors3.push(error);
10941
10942
  } finally {
10942
10943
  this.releaseRuntimeWriter = void 0;
10943
10944
  }
10944
- if (errors2.length) throw new AggregateError(errors2, "MEM7_CLOSE_FAILED");
10945
+ if (errors3.length) throw new AggregateError(errors3, "MEM7_CLOSE_FAILED");
10945
10946
  }
10946
10947
  // ── memcell 账本 ──────────────────────────────────────────
10947
10948
  insertMemcell(cell) {
@@ -13455,13 +13456,17 @@ var init_session_map = __esm({
13455
13456
 
13456
13457
  // src/cc-driver/long-http.ts
13457
13458
  import { request as request3 } from "node:http";
13458
- function longPostJson(url, body, headers = {}, signal) {
13459
+ function longPostJson(url, body, headers = {}, signal, acknowledgment) {
13459
13460
  const data = Buffer.from(JSON.stringify(body));
13460
13461
  return new Promise((resolve13, reject) => {
13461
13462
  const req = request3(url, { method: "POST", headers: { ...headers, "Content-Length": String(data.byteLength) } }, (res) => {
13463
+ if (acknowledgment && res.statusCode === 200 && res.headers[CC_JOB_HEADER] === acknowledgment.jobId) acknowledgment.onAccepted();
13462
13464
  const chunks = [];
13463
13465
  res.on("data", (chunk) => chunks.push(chunk));
13464
- res.on("error", reject);
13466
+ res.on("error", (err) => {
13467
+ cleanup();
13468
+ reject(err);
13469
+ });
13465
13470
  res.on("end", () => {
13466
13471
  cleanup();
13467
13472
  const text2 = Buffer.concat(chunks).toString("utf8");
@@ -13493,9 +13498,11 @@ function longPostJson(url, body, headers = {}, signal) {
13493
13498
  req.end(data);
13494
13499
  });
13495
13500
  }
13501
+ var CC_JOB_HEADER;
13496
13502
  var init_long_http = __esm({
13497
13503
  "src/cc-driver/long-http.ts"() {
13498
13504
  "use strict";
13505
+ CC_JOB_HEADER = "x-engine7-cc-job-id";
13499
13506
  }
13500
13507
  });
13501
13508
 
@@ -13549,19 +13556,31 @@ async function findDesktopTargets(workDir, sessionId) {
13549
13556
  }
13550
13557
  return targets;
13551
13558
  }
13552
- async function askDesktop(target, prompt, source, signal) {
13559
+ async function askDesktop(target, prompt, source, signal, acknowledgment) {
13560
+ const endpoint = acknowledgment ? "submit" : "ask";
13553
13561
  const { status, json: result } = await longPostJson(
13554
- `http://127.0.0.1:${target.port}/ask`,
13555
- { prompt, source, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13562
+ `http://127.0.0.1:${target.port}/${endpoint}`,
13563
+ { prompt, source, jobId: acknowledgment?.jobId, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13556
13564
  { authorization: `Bearer ${target.token}` },
13557
- signal
13565
+ signal,
13566
+ acknowledgment
13558
13567
  );
13559
- if (status !== 200) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
13568
+ if (status !== 200 || result?.error) throw failure(result?.error || `Desktop CC HTTP ${status}`, status);
13560
13569
  if (result.sessionId !== target.sessionId || typeof result.text !== "string" || typeof result.isError !== "boolean") {
13561
13570
  throw failure("Desktop CC returned an invalid result");
13562
13571
  }
13563
13572
  return result;
13564
13573
  }
13574
+ async function stopDesktopJob(target, jobId) {
13575
+ const { status, json } = await longPostJson(
13576
+ `http://127.0.0.1:${target.port}/stop`,
13577
+ { jobId, sessionId: target.sessionId, instance: target.instance, workDir: target.workDir },
13578
+ { authorization: `Bearer ${target.token}` },
13579
+ AbortSignal.timeout(5e3)
13580
+ );
13581
+ if (status !== 200) throw failure(json?.error || `Desktop CC HTTP ${status}`, status);
13582
+ return json?.stopped === true;
13583
+ }
13565
13584
  var registryDir, canonical2, failure, alive;
13566
13585
  var init_desktop = __esm({
13567
13586
  "src/cc-driver/desktop.ts"() {
@@ -14009,6 +14028,7 @@ var init_driver = __esm({
14009
14028
  revision = 0;
14010
14029
  idleWaiters = [];
14011
14030
  abort = null;
14031
+ activeJob;
14012
14032
  /** 当前流式 chunk 的 steer 口(仅用户消息路径开;外部 ask/桌面路径为 null) */
14013
14033
  feeder = null;
14014
14034
  sessionId = null;
@@ -14053,13 +14073,17 @@ var init_driver = __esm({
14053
14073
  void this.drain();
14054
14074
  }
14055
14075
  /** External callers use the same FIFO; they never answer a pending permission card. */
14056
- ask(prompt, source, expectedSessionId, signal) {
14057
- if (this.closed) return Promise.reject(requestError("CC binding is stopping", 503));
14058
- if (!prompt.trim()) return Promise.reject(requestError("prompt is required", 400));
14059
- if (signal?.aborted) return Promise.reject(requestError("CC request cancelled", 499));
14060
- if (this.sessionId !== expectedSessionId) return Promise.reject(requestError("CC session changed; select the current binding again"));
14061
- if (this.queue.length >= MAX_QUEUE) return Promise.reject(requestError("CC queue is full", 429));
14062
- const job = { prompt: prompt.trim(), source, expectedSessionId, signal };
14076
+ async ask(prompt, source, expectedSessionId, signal) {
14077
+ return this.submit(prompt, source, expectedSessionId, signal);
14078
+ }
14079
+ submit(prompt, source, expectedSessionId, signal, id3, onSession) {
14080
+ if (this.closed) throw requestError("CC binding is stopping", 503);
14081
+ if (!prompt.trim()) throw requestError("prompt is required", 400);
14082
+ if (signal?.aborted) throw requestError("CC request cancelled", 499);
14083
+ if (this.sessionId !== expectedSessionId) throw requestError("CC session changed; select the current binding again");
14084
+ if (id3 && (this.activeJob?.id === id3 || this.queue.some((job2) => job2.id === id3))) throw requestError("CC job already exists");
14085
+ if (this.queue.length >= MAX_QUEUE) throw requestError("CC queue is full", 429);
14086
+ const job = { id: id3, prompt: prompt.trim(), source, expectedSessionId, expectedRevision: id3 ? this.revision : void 0, signal, onSession };
14063
14087
  const cancel = () => {
14064
14088
  const index = this.queue.indexOf(job);
14065
14089
  if (index >= 0) {
@@ -14074,7 +14098,16 @@ var init_driver = __esm({
14074
14098
  signal?.addEventListener("abort", cancel, { once: true });
14075
14099
  void this.drain();
14076
14100
  });
14077
- return pending.finally(() => signal?.removeEventListener("abort", cancel));
14101
+ return signal ? pending.finally(() => signal.removeEventListener("abort", cancel)) : pending;
14102
+ }
14103
+ stopJob(id3) {
14104
+ const index = this.queue.findIndex((job) => job.id === id3);
14105
+ if (index >= 0) {
14106
+ this.queue.splice(index, 1)[0].reject?.(requestError("CC request cancelled (stop)", 499));
14107
+ return true;
14108
+ }
14109
+ if (this.activeJob?.id === id3) return this.activeJob.stop?.() ?? false;
14110
+ return false;
14078
14111
  }
14079
14112
  /** Reload/stop must not leave the old hub executing queued work. */
14080
14113
  shutdown() {
@@ -14100,6 +14133,9 @@ var init_driver = __esm({
14100
14133
  stop() {
14101
14134
  this.abort?.abort();
14102
14135
  }
14136
+ get queued() {
14137
+ return this.queue.length;
14138
+ }
14103
14139
  get busy() {
14104
14140
  return this.draining;
14105
14141
  }
@@ -14113,15 +14149,17 @@ var init_driver = __esm({
14113
14149
  await this.predecessor;
14114
14150
  while (!this.closed && this.queue.length > 0) {
14115
14151
  const job = this.queue.shift();
14152
+ this.activeJob = job;
14116
14153
  try {
14117
14154
  if (job.signal?.aborted) throw requestError("CC request cancelled", 499);
14118
- if (job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId) {
14155
+ const changed = job.expectedRevision !== void 0 ? job.expectedRevision !== this.revision : job.expectedSessionId !== void 0 && job.expectedSessionId !== this.sessionId;
14156
+ if (changed) {
14119
14157
  throw requestError("CC session changed while this request was queued");
14120
14158
  }
14121
14159
  if (job.source) {
14122
14160
  const prompt = `[cc_ask from ${job.source.replace(/[\r\n]/g, " ").slice(0, 160)}]
14123
14161
  ${job.prompt}`;
14124
- const result = await this.runTurn(prompt, job.signal, true);
14162
+ const result = await this.runTurn(prompt, job.signal, true, job);
14125
14163
  job.resolve?.(result);
14126
14164
  } else {
14127
14165
  await this.runStreaming(job);
@@ -14130,6 +14168,8 @@ ${job.prompt}`;
14130
14168
  job.reject?.(err);
14131
14169
  console.error(`[cc-driver] turn \u5931\u8D25 key=${this.key}: ${err?.stack || err}`);
14132
14170
  await this.sendText(`[cc-driver] \u8FD9\u6B21\u4EFB\u52A1\u5931\u8D25\uFF1A${err?.message || String(err)}`);
14171
+ } finally {
14172
+ this.activeJob = void 0;
14133
14173
  }
14134
14174
  }
14135
14175
  } finally {
@@ -14137,12 +14177,24 @@ ${job.prompt}`;
14137
14177
  for (const resolve13 of this.idleWaiters.splice(0)) resolve13();
14138
14178
  }
14139
14179
  }
14140
- async runTurn(prompt, signal, external = false) {
14180
+ async runTurn(prompt, signal, external = false, job) {
14141
14181
  const ac = new AbortController();
14142
14182
  this.abort = ac;
14183
+ if (job?.id) job.stop = () => {
14184
+ ac.abort();
14185
+ return true;
14186
+ };
14143
14187
  const resumedFrom = this.sessionId;
14144
14188
  const revision = this.revision;
14145
14189
  let turnSessionId = resumedFrom;
14190
+ const observeSession = (id3) => {
14191
+ try {
14192
+ job?.onSession?.(id3);
14193
+ } catch (error) {
14194
+ console.error("[cc-driver] task session update failed:", error.message);
14195
+ }
14196
+ };
14197
+ observeSession(turnSessionId);
14146
14198
  const cancel = () => ac.abort();
14147
14199
  signal?.addEventListener("abort", cancel, { once: true });
14148
14200
  if (signal?.aborted) ac.abort();
@@ -14166,13 +14218,31 @@ ${job.prompt}`;
14166
14218
  const acc = this.makeStreamAccumulator();
14167
14219
  try {
14168
14220
  const desktops = resumedFrom ? await findDesktopTargets(this.workDir, resumedFrom) : [];
14221
+ ac.signal.throwIfAborted();
14169
14222
  if (desktops.length > 1) throw new Error("Multiple desktop writers claim this CC session; close the duplicate");
14170
14223
  if (desktops[0]) {
14171
- const result2 = await askDesktop(desktops[0], prompt, this.key, ac.signal);
14224
+ const desktop = desktops[0];
14225
+ let result2;
14226
+ if (job?.id) {
14227
+ const jobId = job.id;
14228
+ let acknowledge;
14229
+ const accepted = new Promise((resolve13) => {
14230
+ acknowledge = resolve13;
14231
+ });
14232
+ job.stop = async () => await accepted && stopDesktopJob(desktop, jobId);
14233
+ try {
14234
+ result2 = await askDesktop(desktop, prompt, this.key, ac.signal, { jobId, onAccepted: () => acknowledge(true) });
14235
+ } finally {
14236
+ acknowledge(false);
14237
+ }
14238
+ } else {
14239
+ result2 = await askDesktop(desktop, prompt, this.key, ac.signal);
14240
+ }
14172
14241
  finalText = result2.text;
14173
14242
  isError = result2.isError;
14174
14243
  gotResult = true;
14175
14244
  turnSessionId = result2.sessionId;
14245
+ observeSession(turnSessionId);
14176
14246
  if (this.revision === revision) this.sessionId = result2.sessionId;
14177
14247
  } else {
14178
14248
  if (resumedFrom && nativeSessionOwners(resumedFrom).length) {
@@ -14185,6 +14255,7 @@ ${job.prompt}`;
14185
14255
  const mb = total ? `\u7EA6 ${Math.round(total / 1024 / 1024)}M` : "\u7EA6 350M";
14186
14256
  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`);
14187
14257
  });
14258
+ ac.signal.throwIfAborted();
14188
14259
  const stream = query({
14189
14260
  prompt,
14190
14261
  options: {
@@ -14227,6 +14298,7 @@ ${job.prompt}`;
14227
14298
  const r = msg2;
14228
14299
  if (r.session_id) {
14229
14300
  turnSessionId = r.session_id;
14301
+ observeSession(turnSessionId);
14230
14302
  if (this.revision === revision) this.sessionId = r.session_id;
14231
14303
  }
14232
14304
  isError = r.is_error === true;
@@ -14237,6 +14309,7 @@ ${job.prompt}`;
14237
14309
  const sid = msg2.session_id;
14238
14310
  if (sid) {
14239
14311
  turnSessionId = sid;
14312
+ observeSession(turnSessionId);
14240
14313
  if (this.revision === revision) this.sessionId = sid;
14241
14314
  }
14242
14315
  } else {
@@ -14246,6 +14319,7 @@ ${job.prompt}`;
14246
14319
  }
14247
14320
  if (turnSessionId && gotResult && this.revision === revision) this.map.switchTo(this.key, turnSessionId, this.workDir);
14248
14321
  } finally {
14322
+ if (job) job.stop = void 0;
14249
14323
  this.abort = null;
14250
14324
  signal?.removeEventListener("abort", cancel);
14251
14325
  }
@@ -14846,6 +14920,164 @@ var init_router = __esm({
14846
14920
  }
14847
14921
  });
14848
14922
 
14923
+ // src/services/adaptive-proxy.ts
14924
+ var adaptive_proxy_exports = {};
14925
+ __export(adaptive_proxy_exports, {
14926
+ createProxySocketAgent: () => createProxySocketAgent,
14927
+ getProxyDispatcher: () => getProxyDispatcher,
14928
+ isAdaptiveProxy: () => isAdaptiveProxy
14929
+ });
14930
+ import net from "node:net";
14931
+ import tls from "node:tls";
14932
+ import { HttpsProxyAgent } from "https-proxy-agent";
14933
+ import { Agent as Agent2, Client, ProxyAgent, errors as errors2 } from "undici";
14934
+ function proxyAddress(value) {
14935
+ const bareLoopback = /^(?:localhost\.?|127(?:\.\d{1,3}){3}|\[::1\]):\d+$/i;
14936
+ return new URL(bareLoopback.test(value) ? `http://${value}` : value);
14937
+ }
14938
+ function localProxyKey(url) {
14939
+ if (url.protocol !== "http:" && url.protocol !== "https:") return;
14940
+ const host = url.hostname.replace(/\.$/, "");
14941
+ if (host !== "localhost" && host !== "[::1]" && !/^127\./.test(host)) return;
14942
+ return `${host}:${url.port || (url.protocol === "https:" ? 443 : 80)}`;
14943
+ }
14944
+ function isAdaptiveProxy(proxy) {
14945
+ return localProxyKey(proxyAddress(proxy.trim())) !== void 0;
14946
+ }
14947
+ function proxyUnavailable(key4) {
14948
+ return (unreachableUntil.get(key4) ?? -Infinity) > Date.now();
14949
+ }
14950
+ function markUnavailable(key4) {
14951
+ unreachableUntil.set(key4, Date.now() + RETRY_PROXY_AFTER_MS);
14952
+ }
14953
+ function isTcpDialFailure(error) {
14954
+ if (error instanceof AggregateError) {
14955
+ return error.errors.length > 0 && error.errors.every(isTcpDialFailure);
14956
+ }
14957
+ const err = error;
14958
+ return err?.syscall === "connect" && dialFailureCodes.has(err.code ?? "");
14959
+ }
14960
+ function getProxyDispatcher(value) {
14961
+ const raw = value?.trim();
14962
+ if (!raw) return;
14963
+ const cached2 = dispatchers.get(raw);
14964
+ if (cached2) return cached2;
14965
+ const url = proxyAddress(raw);
14966
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
14967
+ throw new Error(
14968
+ `\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}`
14969
+ );
14970
+ }
14971
+ const key4 = localProxyKey(url);
14972
+ const dispatcher = key4 ? new AdaptiveProxyDispatcher(url.href, key4) : new ProxyAgent({ uri: url.href });
14973
+ dispatchers.set(raw, dispatcher);
14974
+ return dispatcher;
14975
+ }
14976
+ function createProxySocketAgent(value) {
14977
+ const url = proxyAddress(value.trim());
14978
+ const key4 = localProxyKey(url);
14979
+ return key4 ? new AdaptiveProxySocketAgent(url, key4) : new HttpsProxyAgent(url);
14980
+ }
14981
+ var RETRY_PROXY_AFTER_MS, LOCAL_CONNECT_TIMEOUT_MS, unreachableUntil, failedProxyDials, dispatchers, direct, dialFailureCodes, AdaptiveProxyDispatcher, AdaptiveProxySocketAgent;
14982
+ var init_adaptive_proxy = __esm({
14983
+ "src/services/adaptive-proxy.ts"() {
14984
+ "use strict";
14985
+ RETRY_PROXY_AFTER_MS = 5e3;
14986
+ LOCAL_CONNECT_TIMEOUT_MS = 1e3;
14987
+ unreachableUntil = /* @__PURE__ */ new Map();
14988
+ failedProxyDials = /* @__PURE__ */ new WeakSet();
14989
+ dispatchers = /* @__PURE__ */ new Map();
14990
+ direct = new Agent2();
14991
+ dialFailureCodes = /* @__PURE__ */ new Set(["ECONNREFUSED", "ETIMEDOUT", "ENETUNREACH", "EHOSTUNREACH", "EADDRNOTAVAIL"]);
14992
+ AdaptiveProxyDispatcher = class extends ProxyAgent {
14993
+ constructor(uri, key4) {
14994
+ super({
14995
+ uri,
14996
+ proxyTls: { timeout: LOCAL_CONNECT_TIMEOUT_MS },
14997
+ clientFactory(origin, opts) {
14998
+ const { connect } = opts;
14999
+ return new Client(origin, {
15000
+ connect(options, callback) {
15001
+ let tcpConnected = false;
15002
+ const socket = connect(options, (...result) => {
15003
+ const [error] = result;
15004
+ if (error && !tcpConnected && (isTcpDialFailure(error) || error.code === "UND_ERR_CONNECT_TIMEOUT")) {
15005
+ markUnavailable(key4);
15006
+ failedProxyDials.add(error);
15007
+ }
15008
+ callback(...result);
15009
+ });
15010
+ socket.once("connect", () => {
15011
+ tcpConnected = true;
15012
+ });
15013
+ return socket;
15014
+ }
15015
+ });
15016
+ }
15017
+ });
15018
+ this.key = key4;
15019
+ }
15020
+ dispatch(options, handler) {
15021
+ if (!this.closed && !this.destroyed && proxyUnavailable(this.key)) {
15022
+ const headers = options.headers;
15023
+ const keys = !headers ? [] : Array.isArray(headers) ? headers.filter((_, index) => index % 2 === 0) : Symbol.iterator in headers ? Array.from(headers, ([name]) => name) : Object.keys(headers);
15024
+ if (keys.some((name) => name.toLowerCase() === "proxy-authorization")) {
15025
+ throw new errors2.InvalidArgumentError("Proxy-Authorization should be sent in ProxyAgent constructor");
15026
+ }
15027
+ return direct.dispatch(options, handler);
15028
+ }
15029
+ let connected = false;
15030
+ const extended = handler;
15031
+ const guarded = {
15032
+ onConnect: (abort) => {
15033
+ connected = true;
15034
+ handler.onConnect?.(abort);
15035
+ },
15036
+ onError: (error) => {
15037
+ if (!connected && failedProxyDials.has(error)) {
15038
+ direct.dispatch(options, handler);
15039
+ } else {
15040
+ handler.onError?.(error);
15041
+ }
15042
+ },
15043
+ onHeaders: handler.onHeaders?.bind(handler),
15044
+ onData: handler.onData?.bind(handler),
15045
+ onComplete: handler.onComplete?.bind(handler),
15046
+ onUpgrade: handler.onUpgrade?.bind(handler),
15047
+ onResponseStarted: handler.onResponseStarted?.bind(handler),
15048
+ onBodySent: handler.onBodySent?.bind(handler),
15049
+ onRequestSent: extended.onRequestSent?.bind(handler)
15050
+ };
15051
+ return super.dispatch(options, guarded);
15052
+ }
15053
+ };
15054
+ AdaptiveProxySocketAgent = class extends HttpsProxyAgent {
15055
+ constructor(url, key4) {
15056
+ super(url);
15057
+ this.key = key4;
15058
+ }
15059
+ async connect(req, opts) {
15060
+ if (!proxyUnavailable(this.key)) {
15061
+ try {
15062
+ return await super.connect(req, opts);
15063
+ } catch (error) {
15064
+ if (!isTcpDialFailure(error)) throw error;
15065
+ markUnavailable(this.key);
15066
+ if (req.destroyed) throw error;
15067
+ }
15068
+ }
15069
+ if (!opts.secureEndpoint) return net.connect({ ...opts, path: void 0 });
15070
+ const { host, servername } = opts;
15071
+ return tls.connect({
15072
+ ...opts,
15073
+ path: void 0,
15074
+ servername: servername ?? (host && !net.isIP(host) ? host : void 0)
15075
+ });
15076
+ }
15077
+ };
15078
+ }
15079
+ });
15080
+
14849
15081
  // src/calendar/dispatches.ts
14850
15082
  var dispatches_exports = {};
14851
15083
  __export(dispatches_exports, {
@@ -14906,10 +15138,10 @@ function installSQLiteWriteCapture(db2, source) {
14906
15138
  if (db2.isTransaction) throw new Error("REPLICATION_TRANSACTION_ALREADY_OPEN");
14907
15139
  const exec = db2.exec, prepare = db2.prepare;
14908
15140
  let active, failed = false, closed = false, reading = false;
14909
- let direct;
15141
+ let direct2;
14910
15142
  const check = () => {
14911
15143
  if (closed) throw new Error("REPLICATION_TRANSACTION_CLOSED");
14912
- direct?.assertOpen();
15144
+ direct2?.assertOpen();
14913
15145
  };
14914
15146
  const wrappedExec = function(sql) {
14915
15147
  check();
@@ -14980,10 +15212,10 @@ function installSQLiteWriteCapture(db2, source) {
14980
15212
  db2.prepare = checkedPrepare;
14981
15213
  const transaction = (operation) => {
14982
15214
  check();
14983
- if (db2.isTransaction) return direct.scope(operation);
15215
+ if (db2.isTransaction) return direct2.scope(operation);
14984
15216
  db2.exec("BEGIN IMMEDIATE");
14985
15217
  try {
14986
- const result = direct.scope(operation);
15218
+ const result = direct2.scope(operation);
14987
15219
  if (result && typeof result.then === "function") throw new Error("REPLICATION_ASYNC_TRANSACTION");
14988
15220
  db2.exec("COMMIT");
14989
15221
  return result;
@@ -14992,10 +15224,10 @@ function installSQLiteWriteCapture(db2, source) {
14992
15224
  throw error;
14993
15225
  }
14994
15226
  };
14995
- direct = installAutocommitCapture(db2, transaction);
15227
+ direct2 = installAutocommitCapture(db2, transaction);
14996
15228
  return {
14997
15229
  assertOpen: check,
14998
- scope: (operation) => direct.scope(operation),
15230
+ scope: (operation) => direct2.scope(operation),
14999
15231
  transaction,
15000
15232
  close() {
15001
15233
  if (closed) return;
@@ -15004,7 +15236,7 @@ function installSQLiteWriteCapture(db2, source) {
15004
15236
  source.endCapture(active);
15005
15237
  active = void 0;
15006
15238
  }
15007
- direct.close();
15239
+ direct2.close();
15008
15240
  db2.prepare = prepare;
15009
15241
  db2.exec = exec;
15010
15242
  closed = true;
@@ -16845,7 +17077,8 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16845
17077
  this.noteCascade(id3);
16846
17078
  this.db.prepare(`UPDATE actions SET basis_state='dirty',action_version=action_version+1,
16847
17079
  cancel_requested=CASE WHEN status='executing' THEN 1 ELSE cancel_requested END,
16848
- status=CASE WHEN status='queued' THEN 'cancelled' ELSE status END
17080
+ status=CASE WHEN status='queued' THEN 'cancelled' ELSE status END,
17081
+ cancel_reason=COALESCE(cancel_reason, CASE WHEN status='queued' THEN 'graph_basis_changed' END)
16849
17082
  WHERE intent_id=? AND status IN ('queued','executing')`).run(id3);
16850
17083
  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);
16851
17084
  pending.push(...this.dependencies.children(scope, [{ kind: "node", id: id3 }]));
@@ -16930,11 +17163,12 @@ CREATE INDEX IF NOT EXISTS idx_proactive_decisions_created ON proactive_decision
16930
17163
  a.note ?? null
16931
17164
  );
16932
17165
  }
16933
- /** status='queued' AND scheduled_time<=now,按时间升序 */
16934
- dueActions(now2, limit2 = 20) {
17166
+ /** status='queued' AND scheduled_time<=now,按时间升序。excludeIds:sweep 翻页绕开已看过的(守卫跳过的) */
17167
+ dueActions(now2, limit2 = 20, excludeIds = []) {
16935
17168
  const rows = this.db.prepare(
16936
- `SELECT * FROM actions WHERE status='queued' AND scheduled_time <= ? ORDER BY scheduled_time ASC LIMIT ?`
16937
- ).all(now2, limit2);
17169
+ `SELECT * FROM actions WHERE status='queued' AND scheduled_time <= ?
17170
+ AND id NOT IN (SELECT value FROM json_each(?)) ORDER BY scheduled_time ASC LIMIT ?`
17171
+ ).all(now2, JSON.stringify(excludeIds), limit2);
16938
17172
  return rows.map(rowToAction);
16939
17173
  }
16940
17174
  /** queued 状态 action 的 intent_id 集合(去重) */
@@ -17534,7 +17768,7 @@ __export(voice_chat_tts_daemon_exports, {
17534
17768
  stopTtsDaemon: () => stopTtsDaemon
17535
17769
  });
17536
17770
  import { spawn } from "child_process";
17537
- import net from "net";
17771
+ import net2 from "net";
17538
17772
  import path13 from "path";
17539
17773
  import fs10 from "fs";
17540
17774
  function _log(msg2) {
@@ -17542,7 +17776,7 @@ function _log(msg2) {
17542
17776
  }
17543
17777
  function _healthOnce() {
17544
17778
  return new Promise((resolve13) => {
17545
- const sock = net.connect(SOCK_PATH);
17779
+ const sock = net2.connect(SOCK_PATH);
17546
17780
  sock.setTimeout(2e3);
17547
17781
  sock.on("connect", () => {
17548
17782
  sock.write(JSON.stringify({ action: "health" }) + "\n");
@@ -17595,9 +17829,6 @@ async function startTtsDaemon(warmupCfg) {
17595
17829
  _log(`spawning ${script}`);
17596
17830
  const env = {
17597
17831
  ...process.env,
17598
- // 显式注入代理(dashscope SDK 不自动读系统代理)
17599
- HTTP_PROXY: process.env.HTTP_PROXY || "http://127.0.0.1:7892",
17600
- HTTPS_PROXY: process.env.HTTPS_PROXY || "http://127.0.0.1:7892",
17601
17832
  TTS_DAEMON_SOCK: SOCK_PATH,
17602
17833
  ...warmupCfg?.apiKey ? { ALIYUN_API_KEY: warmupCfg.apiKey } : {},
17603
17834
  ...warmupCfg?.model ? { TTS_MODEL: warmupCfg.model } : {},
@@ -17667,7 +17898,6 @@ __export(withRetry_exports, {
17667
17898
  getRetryDelay: () => getRetryDelay,
17668
17899
  readWithTimeout: () => readWithTimeout
17669
17900
  });
17670
- import { ProxyAgent } from "undici";
17671
17901
  function sleep2(ms, signal) {
17672
17902
  return new Promise((resolve13, reject) => {
17673
17903
  if (signal?.aborted) {
@@ -17735,15 +17965,6 @@ function shouldRetry(status, errorBody) {
17735
17965
  if (errorBody?.includes('"type":"overloaded_error"')) return true;
17736
17966
  return false;
17737
17967
  }
17738
- function getProxyDispatcher(proxyUrl) {
17739
- if (!proxyUrl) return void 0;
17740
- let agent = proxyAgentCache.get(proxyUrl);
17741
- if (!agent) {
17742
- agent = new ProxyAgent({ uri: proxyUrl });
17743
- proxyAgentCache.set(proxyUrl, agent);
17744
- }
17745
- return agent;
17746
- }
17747
17968
  async function* fetchWithRetry(url, init, providerLabel, proxy, beforeRequest, retryPolicy) {
17748
17969
  const configuredRetries = getMaxRetries();
17749
17970
  const maxRetries = retryPolicy?.maxRetries === void 0 ? configuredRetries : Math.min(configuredRetries, Math.max(0, Math.floor(retryPolicy.maxRetries)));
@@ -17881,10 +18102,11 @@ function readWithTimeout(reader, timeoutMs, signal) {
17881
18102
  if (onAbort) signal?.removeEventListener("abort", onAbort);
17882
18103
  });
17883
18104
  }
17884
- 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;
18105
+ var DEFAULT_MAX_RETRIES, BASE_DELAY_MS, MAX_DELAY_MS, DEFAULT_TIMEOUT_MS, READ_TIMEOUT_MS, FIRST_READ_TIMEOUT_MS, NO_PROGRESS_TIMEOUT_MS;
17885
18106
  var init_withRetry = __esm({
17886
18107
  "src/services/withRetry.ts"() {
17887
18108
  "use strict";
18109
+ init_adaptive_proxy();
17888
18110
  DEFAULT_MAX_RETRIES = 10;
17889
18111
  BASE_DELAY_MS = 500;
17890
18112
  MAX_DELAY_MS = 32e3;
@@ -17892,7 +18114,6 @@ var init_withRetry = __esm({
17892
18114
  READ_TIMEOUT_MS = 6e4;
17893
18115
  FIRST_READ_TIMEOUT_MS = parseInt(process.env.API_TIMEOUT_MS || "", 10) || 6e5;
17894
18116
  NO_PROGRESS_TIMEOUT_MS = parseInt(process.env.STREAM_NO_PROGRESS_TIMEOUT_MS || "", 10) || 3e5;
17895
- proxyAgentCache = /* @__PURE__ */ new Map();
17896
18117
  }
17897
18118
  });
17898
18119
 
@@ -19164,8 +19385,8 @@ init_key_service_store();
19164
19385
  init_key_service_store();
19165
19386
  import { createServer } from "node:https";
19166
19387
  function createKeyServiceServer(options) {
19167
- const { store, ...tls2 } = options;
19168
- const server = createServer({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19388
+ const { store, ...tls3 } = options;
19389
+ const server = createServer({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19169
19390
  res.setHeader("Cache-Control", "no-store");
19170
19391
  res.setHeader("Content-Type", "application/json");
19171
19392
  const reply = (status, error) => {
@@ -19429,7 +19650,7 @@ function validManagement(input) {
19429
19650
  return true;
19430
19651
  }
19431
19652
  function createTravelAuthorityServer(options) {
19432
- const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls2 } = options;
19653
+ const { authority, proxyFingerprints = [], allowedPeers = {}, managementPeers = {}, recoveryPeers = {}, retirementPeers = {}, bootstrapPeers = {}, maximumInFlight = 16, requestTimeoutMs = 8e3, ...tls3 } = options;
19433
19654
  const proxies = /* @__PURE__ */ new Set(), peers = /* @__PURE__ */ new Map(), managers = /* @__PURE__ */ new Map();
19434
19655
  const fingerprint2 = (value) => {
19435
19656
  const normalized = value.replaceAll(":", "").toLowerCase();
@@ -19474,7 +19695,7 @@ function createTravelAuthorityServer(options) {
19474
19695
  retirees.set(fp, new Set(credentials.map((credential) => authority.authenticateRetirement(credential).credentialHash)));
19475
19696
  }
19476
19697
  const reports = /* @__PURE__ */ new Set(), management = /* @__PURE__ */ new Set();
19477
- const server = createServer2({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19698
+ const server = createServer2({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
19478
19699
  res.setHeader("Content-Type", "application/json");
19479
19700
  res.setHeader("Cache-Control", "no-store");
19480
19701
  const reply = (status, value) => {
@@ -20329,7 +20550,7 @@ function decodeBody(value, maximum = 16 * 1024 * 1024) {
20329
20550
  return body;
20330
20551
  }
20331
20552
  function createTravelGatewayServer(options) {
20332
- const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls2 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
20553
+ const { authority, store, allowedPeers, recoveryPeers = {}, platform, assertReady, ...tls3 } = options, peers = /* @__PURE__ */ new Map(), recovery = /* @__PURE__ */ new Map();
20333
20554
  for (const [fingerprint2, credential] of Object.entries(allowedPeers)) {
20334
20555
  const normalized = fingerprint2.replaceAll(":", "").toLowerCase();
20335
20556
  if (!/^[a-f0-9]{64}$/.test(normalized) || peers.has(normalized)) throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
@@ -20342,7 +20563,7 @@ function createTravelGatewayServer(options) {
20342
20563
  }
20343
20564
  if (!peers.size || typeof platform.deliver !== "function") throw new Error("TRAVEL_GATEWAY_INVALID_LISTENER");
20344
20565
  let inFlight = 0;
20345
- const server = createServer3({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
20566
+ const server = createServer3({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
20346
20567
  res.setHeader("Cache-Control", "no-store");
20347
20568
  res.setHeader("Content-Type", "application/json");
20348
20569
  const reply = (status, value) => {
@@ -20723,12 +20944,55 @@ var AgentRegistryImpl = class {
20723
20944
  var agentRegistry = new AgentRegistryImpl();
20724
20945
 
20725
20946
  // src/channels/discord.ts
20726
- import { Client, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20727
- import { ProxyAgent as UndiciProxyAgent } from "undici";
20728
- import { HttpsProxyAgent } from "https-proxy-agent";
20947
+ init_adaptive_proxy();
20948
+ import { Client as Client2, GatewayIntentBits, MessageFlags, Partials, ApplicationCommandOptionType } from "discord.js";
20949
+
20950
+ // src/channels/discord-gateway-proxy.ts
20951
+ init_adaptive_proxy();
20952
+ import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
20953
+ import https from "node:https";
20954
+ import { SimpleShardingStrategy } from "@discordjs/ws";
20955
+ var gatewayRoute = new AsyncLocalStorage4();
20956
+ function gatewayDestination(url) {
20957
+ const { hostname, port } = new URL(url);
20958
+ return `${hostname.replace(/^\[|\]$/g, "")}:${port || 443}`;
20959
+ }
20960
+ var installed = false;
20961
+ function discordGatewayProxy(proxy) {
20962
+ if (!installed) {
20963
+ installed = true;
20964
+ const request4 = https.request;
20965
+ https.request = (...args) => {
20966
+ const route = gatewayRoute.getStore();
20967
+ const [options] = args;
20968
+ 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}`)) {
20969
+ args[0] = { ...options, agent: route.agent };
20970
+ }
20971
+ return Reflect.apply(request4, https, args);
20972
+ };
20973
+ }
20974
+ const agent = createProxySocketAgent(proxy);
20975
+ return (manager) => {
20976
+ const strategy = new SimpleShardingStrategy(manager);
20977
+ const destinations = /* @__PURE__ */ new Set();
20978
+ const retrieveSession = manager.options.retrieveSessionInfo.bind(manager.options);
20979
+ manager.options.retrieveSessionInfo = async (shardId) => {
20980
+ const session = await retrieveSession(shardId);
20981
+ if (session?.resumeURL) destinations.add(gatewayDestination(session.resumeURL));
20982
+ return session;
20983
+ };
20984
+ const connect = strategy.connect.bind(strategy);
20985
+ strategy.connect = async () => {
20986
+ const { url } = await manager.fetchGatewayInformation();
20987
+ destinations.add(gatewayDestination(url));
20988
+ return gatewayRoute.run({ agent, destinations }, connect);
20989
+ };
20990
+ return strategy;
20991
+ };
20992
+ }
20729
20993
 
20730
20994
  // src/memory/external-effect.ts
20731
- import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
20995
+ import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
20732
20996
  import { createHash as createHash25 } from "node:crypto";
20733
20997
  import { join as join18 } from "node:path";
20734
20998
 
@@ -20848,8 +21112,8 @@ function assertMemoryExecution(stateDir, workspace, context) {
20848
21112
  // src/mem7/host-turn.ts
20849
21113
  init_store();
20850
21114
  init_host_turns();
20851
- import { AsyncLocalStorage as AsyncLocalStorage4 } from "node:async_hooks";
20852
- var turns = new AsyncLocalStorage4();
21115
+ import { AsyncLocalStorage as AsyncLocalStorage5 } from "node:async_hooks";
21116
+ var turns = new AsyncLocalStorage5();
20853
21117
  function hasHostTurnContext() {
20854
21118
  return Boolean(turns.getStore());
20855
21119
  }
@@ -20893,8 +21157,8 @@ function beginHostTurnEffect() {
20893
21157
 
20894
21158
  // src/memory/external-effect.ts
20895
21159
  init_runtime_authority();
20896
- var effects = new AsyncLocalStorage5();
20897
- var externalFences = new AsyncLocalStorage5();
21160
+ var effects = new AsyncLocalStorage6();
21161
+ var externalFences = new AsyncLocalStorage6();
20898
21162
  function withExternalEffectFence(check, run) {
20899
21163
  return externalFences.run(check, run);
20900
21164
  }
@@ -21183,7 +21447,7 @@ var DiscordAdapter = class _DiscordAdapter {
21183
21447
  // 🔴 P0: 消息去重 — Discord RESUME 重连会重放 messageCreate
21184
21448
  recentMessageIds = /* @__PURE__ */ new Set();
21185
21449
  constructor(clientOrConfig, config) {
21186
- if (clientOrConfig instanceof Client) {
21450
+ if (clientOrConfig instanceof Client2) {
21187
21451
  this.client = clientOrConfig;
21188
21452
  this.config = config ?? {};
21189
21453
  this.ownsClient = false;
@@ -21201,24 +21465,10 @@ var DiscordAdapter = class _DiscordAdapter {
21201
21465
  partials: [Partials.Channel, Partials.Message]
21202
21466
  };
21203
21467
  if (this.config.proxy) {
21204
- const proxyUrl = this.config.proxy;
21205
- clientOptions.rest = { agent: new UndiciProxyAgent({ uri: proxyUrl }) };
21206
- const httpsAgent = new HttpsProxyAgent(proxyUrl);
21207
- const https = __require("https");
21208
- const origRequest = https.request;
21209
- if (!origRequest.__discordProxyPatched) {
21210
- https.request = function(opts, cb) {
21211
- const host = typeof opts === "string" ? "" : opts?.hostname || opts?.host || "";
21212
- if ((host.includes("discord") || host.includes("gateway")) && typeof opts === "object" && !opts.agent) {
21213
- opts.agent = httpsAgent;
21214
- }
21215
- return origRequest.call(this, opts, cb);
21216
- };
21217
- https.request.__discordProxyPatched = true;
21218
- console.log(`[discord] https.request patched for Discord gateway \u2192 ${proxyUrl}`);
21219
- }
21468
+ clientOptions.rest = { agent: getProxyDispatcher(this.config.proxy) };
21469
+ clientOptions.ws = { buildStrategy: discordGatewayProxy(this.config.proxy) };
21220
21470
  }
21221
- this.client = new Client(clientOptions);
21471
+ this.client = new Client2(clientOptions);
21222
21472
  this.ownsClient = true;
21223
21473
  }
21224
21474
  this.progressCards = new DiscordProgressCards({
@@ -21279,7 +21529,7 @@ var DiscordAdapter = class _DiscordAdapter {
21279
21529
  }
21280
21530
  try {
21281
21531
  const init = { signal: AbortSignal.timeout(HISTORY_ATTACH_TIMEOUT_MS) };
21282
- if (this.config.proxy) init.dispatcher = new UndiciProxyAgent({ uri: this.config.proxy });
21532
+ if (this.config.proxy) init.dispatcher = getProxyDispatcher(this.config.proxy);
21283
21533
  const res = await fetch(att.url, init);
21284
21534
  if (!res.ok) throw new Error(`HTTP ${res.status}`);
21285
21535
  const buf = Buffer.from(await res.arrayBuffer());
@@ -22125,6 +22375,10 @@ var FeishuAdapter = class _FeishuAdapter {
22125
22375
  }
22126
22376
  }
22127
22377
  }
22378
+ /** 公开上传入口(1130 gmail 连接卡片等业务卡用):委托 _uploadImage。 */
22379
+ async uploadImage(buffer, filename) {
22380
+ return this._uploadImage(buffer, filename);
22381
+ }
22128
22382
  async _uploadImage(buffer, filename) {
22129
22383
  const token = await this._getTenantToken();
22130
22384
  const resp = await fetch("https://open.feishu.cn/open-apis/im/v1/images", {
@@ -24072,7 +24326,7 @@ import { promisify as promisify3 } from "node:util";
24072
24326
  init_voice_chat_tts_daemon();
24073
24327
  import * as path14 from "node:path";
24074
24328
  import * as os6 from "node:os";
24075
- import net2 from "net";
24329
+ import net3 from "net";
24076
24330
  var execFileAsync = promisify3(execFile);
24077
24331
  var VOICE_DIR = path14.join(os6.tmpdir(), "engine-voice");
24078
24332
  async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
@@ -24084,7 +24338,7 @@ async function ttsCosyvoiceWorker(text2, cfg, onChunk) {
24084
24338
  }
24085
24339
  }
24086
24340
  return new Promise((resolve13, reject) => {
24087
- const sock = net2.connect(getSockPath());
24341
+ const sock = net3.connect(getSockPath());
24088
24342
  let buf = "";
24089
24343
  const finish = (err) => {
24090
24344
  try {
@@ -24296,8 +24550,8 @@ var DeskBuddyAdapter = class {
24296
24550
  startAsr() {
24297
24551
  if (this.asrSock) return;
24298
24552
  const port = this.asrBackend === "sensevoice" ? 9790 : 9791;
24299
- const net3 = __require("node:net");
24300
- const sock = net3.connect(port, "127.0.0.1");
24553
+ const net4 = __require("node:net");
24554
+ const sock = net4.connect(port, "127.0.0.1");
24301
24555
  sock.setNoDelay(true);
24302
24556
  this.asrSock = sock;
24303
24557
  this.asrBuf = "";
@@ -24849,7 +25103,7 @@ var CcBridgeAdapter = class {
24849
25103
 
24850
25104
  // src/channels/telegram.ts
24851
25105
  import fs13 from "node:fs";
24852
- import { AsyncLocalStorage as AsyncLocalStorage6 } from "node:async_hooks";
25106
+ import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
24853
25107
  import path17 from "node:path";
24854
25108
 
24855
25109
  // src/channels/telegram-offset.ts
@@ -25041,7 +25295,7 @@ var PreviewEditThrottle = class {
25041
25295
  /** 提交一次编辑;返回的 promise 在"该内容(或其后覆盖它的更新内容)真实落盘"后 settle,失败 reject */
25042
25296
  submit(key4, req, run) {
25043
25297
  const s = this.st.get(key4) ?? { lastEditAt: -Infinity, timer: null, pending: null, pendingRun: null, waiters: [] };
25044
- const guardedRun = AsyncLocalStorage6.bind(run);
25298
+ const guardedRun = AsyncLocalStorage7.bind(run);
25045
25299
  this.st.set(key4, s);
25046
25300
  return new Promise((resolve13, reject) => {
25047
25301
  const waiter = { resolve: resolve13, reject };
@@ -26227,9 +26481,6 @@ var QrManager = class {
26227
26481
  }
26228
26482
  };
26229
26483
 
26230
- // src/channels/whatsapp/socket.ts
26231
- import { HttpsProxyAgent as HttpsProxyAgent2 } from "https-proxy-agent";
26232
-
26233
26484
  // src/version.ts
26234
26485
  import { readFileSync as readFileSync12 } from "node:fs";
26235
26486
  import { dirname as dirname10, join as join22 } from "node:path";
@@ -26256,7 +26507,7 @@ function readEngineVersion() {
26256
26507
  }
26257
26508
 
26258
26509
  // src/channels/whatsapp/socket.ts
26259
- init_withRetry();
26510
+ init_adaptive_proxy();
26260
26511
  var VERSION_SOURCE_URL = "https://raw.githubusercontent.com/WhiskeySockets/Baileys/master/src/Defaults/index.ts";
26261
26512
  var VERSION_FETCH_TIMEOUT_MS = 3e3;
26262
26513
  var VERSION_FALLBACK_TIMEOUT_MS = 5e3;
@@ -26350,7 +26601,7 @@ async function makeWaSocket(opts) {
26350
26601
  connectTimeoutMs: 6e4,
26351
26602
  defaultQueryTimeoutMs: 6e4,
26352
26603
  // ws 层代理(https-proxy-agent,baileys 原生支持)
26353
- agent: opts.proxy ? new HttpsProxyAgent2(opts.proxy) : void 0,
26604
+ agent: opts.proxy ? createProxySocketAgent(opts.proxy) : void 0,
26354
26605
  // 媒体上传/下载走 native fetch,只认 undici dispatcher(防线 4,见文件头)
26355
26606
  fetchAgent: opts.proxy ? getProxyDispatcher(opts.proxy) : void 0,
26356
26607
  auth: { creds: auth.state.creds, keys },
@@ -27380,9 +27631,9 @@ function isPlanMode() {
27380
27631
  init_runtime_authority();
27381
27632
 
27382
27633
  // src/continuity/gateway-context.ts
27383
- import { AsyncLocalStorage as AsyncLocalStorage7 } from "node:async_hooks";
27384
- var contexts = new AsyncLocalStorage7();
27385
- var outputKinds = new AsyncLocalStorage7();
27634
+ import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
27635
+ var contexts = new AsyncLocalStorage8();
27636
+ var outputKinds = new AsyncLocalStorage8();
27386
27637
  var travelOutputKind = () => outputKinds.getStore() ?? "REPLY";
27387
27638
  function withTravelOutputKind(kind, run) {
27388
27639
  return outputKinds.run(kind, run);
@@ -27517,7 +27768,9 @@ function emitHookResponse(data) {
27517
27768
 
27518
27769
  // src/skills/skill-gate.ts
27519
27770
  init_strip_injected();
27771
+ init_writer();
27520
27772
  var USER_CHANNELS = /* @__PURE__ */ new Set(["discord", "feishu", "wechat", "telegram", "cli", "console", "voice-chat", "deskBuddy", "ccBridge"]);
27773
+ var SKILL_CHANNELS = /* @__PURE__ */ new Set([...USER_CHANNELS, "chan7", "webhook"]);
27521
27774
  var loadedBySession = /* @__PURE__ */ new Map();
27522
27775
  var MAX_TRACKED_SESSIONS = 100;
27523
27776
  function beginSkillGate(sessionId) {
@@ -29771,7 +30024,9 @@ var SEARCH_ALIASES = /* @__PURE__ */ new Map([
29771
30024
  ["gmail", ["\u90AE\u7BB1", "\u90AE\u4EF6"]],
29772
30025
  ["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"]],
29773
30026
  ["cc_ask", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]],
29774
- ["cc_progress", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]]
30027
+ ["cc_progress", ["\u5C0FC", "\u684C\u9762CC", "Claude Code"]],
30028
+ ["cc_new", ["\u5C0FC", "\u684C\u9762CC", "Claude Code", "\u65B0\u5EFA CC \u4F1A\u8BDD"]],
30029
+ ["cc_stop", ["\u5C0FC", "\u684C\u9762CC", "Claude Code", "\u505C\u6B62 CC \u4EFB\u52A1"]]
29775
30030
  ]);
29776
30031
  function toolSearchAliases(name) {
29777
30032
  return SEARCH_ALIASES.get(name) ?? [];
@@ -31017,12 +31272,12 @@ var QueryEngine = class _QueryEngine {
31017
31272
  try {
31018
31273
  const url = "https://localhost:8116/voice-reply";
31019
31274
  if (url.startsWith("https://")) {
31020
- const https = await import("node:https");
31275
+ const https2 = await import("node:https");
31021
31276
  const postData = JSON.stringify({ text: line, isPlaceholder: true });
31022
31277
  assertExternalEffectCurrent();
31023
31278
  beginHostTurnEffect();
31024
31279
  await new Promise((resolve13, reject) => {
31025
- const req = https.request(url, {
31280
+ const req = https2.request(url, {
31026
31281
  method: "POST",
31027
31282
  headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) },
31028
31283
  rejectUnauthorized: false
@@ -33969,11 +34224,10 @@ var DingTalkAdapter = class _DingTalkAdapter {
33969
34224
  throw new Error("dingtalk clientId/clientSecret \u672A\u914D\u7F6E\uFF08\u5F00\u53D1\u8005\u540E\u53F0 \u2192 \u5E94\u7528 \u2192 \u51ED\u8BC1\uFF09");
33970
34225
  }
33971
34226
  if (this.cfg.proxy) {
33972
- const { getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_withRetry(), withRetry_exports));
34227
+ const { createProxySocketAgent: createProxySocketAgent2, getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_adaptive_proxy(), adaptive_proxy_exports));
33973
34228
  const dispatcher = getProxyDispatcher2(this.cfg.proxy);
33974
34229
  this.baseFetch = (url, init) => this.fetchImpl(url, { ...init, dispatcher });
33975
- const { HttpsProxyAgent: HttpsProxyAgent3 } = await import("https-proxy-agent");
33976
- this.wsAgent = new HttpsProxyAgent3(this.cfg.proxy);
34230
+ this.wsAgent = createProxySocketAgent2(this.cfg.proxy);
33977
34231
  this.token = new DingTalkTokenManager(this.cfg.clientId, this.cfg.clientSecret, (u, i) => this.baseFetch(u, i), this.now);
33978
34232
  console.log(`[dingtalk] outbound via proxy ${this.cfg.proxy}`);
33979
34233
  }
@@ -34534,7 +34788,7 @@ var DING_EDIT_INTERVAL_MS = 300;
34534
34788
 
34535
34789
  // src/channels/wecom-stream.ts
34536
34790
  import { EventEmitter as EventEmitter2 } from "node:events";
34537
- import { AsyncLocalStorage as AsyncLocalStorage8 } from "node:async_hooks";
34791
+ import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
34538
34792
  import { createHash as createHash35 } from "node:crypto";
34539
34793
  var WECOM_WS_URL = "wss://openws.work.weixin.qq.com";
34540
34794
  var HEARTBEAT_MS2 = 3e4;
@@ -34860,7 +35114,7 @@ var WecomStreamClient = class extends EventEmitter2 {
34860
35114
  const item = {
34861
35115
  frame,
34862
35116
  // The ack event which pumps this queue has another async context. Keep the sender's guards.
34863
- send: AsyncLocalStorage8.bind((ws) => {
35117
+ send: AsyncLocalStorage9.bind((ws) => {
34864
35118
  assertExternalEffectCurrent();
34865
35119
  ws.send(JSON.stringify(frame));
34866
35120
  }),
@@ -35170,12 +35424,11 @@ var WecomAdapter = class {
35170
35424
  this.loadRoutes();
35171
35425
  let wsAgent;
35172
35426
  if (this.cfg.proxy) {
35173
- const { getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_withRetry(), withRetry_exports));
35427
+ const { createProxySocketAgent: createProxySocketAgent2, getProxyDispatcher: getProxyDispatcher2 } = await Promise.resolve().then(() => (init_adaptive_proxy(), adaptive_proxy_exports));
35174
35428
  const dispatcher = getProxyDispatcher2(this.cfg.proxy);
35175
35429
  const base = this.fetchImpl;
35176
35430
  this.fetchImpl = (url, init) => base(url, { ...init, dispatcher });
35177
- const { HttpsProxyAgent: HttpsProxyAgent3 } = await import("https-proxy-agent");
35178
- wsAgent = new HttpsProxyAgent3(this.cfg.proxy);
35431
+ wsAgent = createProxySocketAgent2(this.cfg.proxy);
35179
35432
  }
35180
35433
  let wsCtor = this.cfg.wsCtor;
35181
35434
  if (!wsCtor) {
@@ -35810,7 +36063,7 @@ async function deliverChannelGatewayEffect(adapter, effect, body, assertCurrent)
35810
36063
  // src/continuity/gateway-feishu.ts
35811
36064
  init_gateway_media();
35812
36065
  import * as lark2 from "@larksuiteoapi/node-sdk";
35813
- import { AsyncLocalStorage as AsyncLocalStorage9 } from "node:async_hooks";
36066
+ import { AsyncLocalStorage as AsyncLocalStorage10 } from "node:async_hooks";
35814
36067
  import { basename as basename6 } from "node:path";
35815
36068
 
35816
36069
  // src/continuity/gateway-feishu-render.ts
@@ -35843,7 +36096,7 @@ var quiet = { error: () => {
35843
36096
  }, debug: () => {
35844
36097
  }, trace: () => {
35845
36098
  } };
35846
- var dispatchContext = new AsyncLocalStorage9();
36099
+ var dispatchContext = new AsyncLocalStorage10();
35847
36100
  var format = "engine7-feishu-gateway-inbound-v1";
35848
36101
  function createFeishuGatewayDispatcher(options) {
35849
36102
  return new lark2.EventDispatcher({ verificationToken: options.verificationToken, encryptKey: options.encryptKey, logger: quiet }).register({
@@ -36029,9 +36282,9 @@ import { basename as basename7 } from "node:path";
36029
36282
  function createRemoteTravelChannel(block, stateDir, channel = "feishu") {
36030
36283
  if (!stateDir || !runtimeAuthorityFor(stateDir)) throw new Error("TRAVEL_GATEWAY_RUNTIME_REQUIRED");
36031
36284
  validateTravelChannels(stateDir, { [channel]: block });
36032
- const tls2 = block.gatewayTls;
36033
- if (!tls2 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls2[key4] !== "string" || !tls2[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
36034
- const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls2.caFile, 1024 * 1024), cert: readPrivateFile(tls2.certFile, 1024 * 1024), key: readPrivateFile(tls2.keyFile, 16384) });
36285
+ const tls3 = block.gatewayTls;
36286
+ if (!tls3 || ["caFile", "certFile", "keyFile"].some((key4) => typeof tls3[key4] !== "string" || !tls3[key4])) throw new Error("TRAVEL_GATEWAY_REMOTE_CONFIG_REQUIRED");
36287
+ const client = new TravelGatewayClient({ url: block.gatewayUrl, ca: readPrivateFile(tls3.caFile, 1024 * 1024), cert: readPrivateFile(tls3.certFile, 1024 * 1024), key: readPrivateFile(tls3.keyFile, 16384) });
36035
36288
  return new RemoteTravelChannel({ client, channel, permit: () => runtimeAuthorityFor(stateDir).assert("INPUT"), pollIntervalMs: block.gatewayPollIntervalMs });
36036
36289
  }
36037
36290
  var RemoteTravelChannel = class {
@@ -36628,8 +36881,8 @@ var ChannelManager = class {
36628
36881
  /** 停止所有 adapter */
36629
36882
  async stopAll() {
36630
36883
  const results = await Promise.allSettled(this.adapters.map(async (adapter) => adapter.disconnect()));
36631
- const errors2 = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
36632
- if (errors2.length) throw new AggregateError(errors2, "CHANNEL_STOP_FAILED");
36884
+ const errors3 = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
36885
+ if (errors3.length) throw new AggregateError(errors3, "CHANNEL_STOP_FAILED");
36633
36886
  }
36634
36887
  /** 通道是否有已注册 adapter(投递前置判断用;1105 inbox-poller route 白名单替代硬编码) */
36635
36888
  hasChannel(channelName) {
@@ -36742,7 +36995,7 @@ function path35(value) {
36742
36995
  if (typeof value !== "string" || !isAbsolute5(value)) throw new Error("TRAVEL_GATEWAY_ABSOLUTE_PATH_REQUIRED");
36743
36996
  return resolve11(value);
36744
36997
  }
36745
- function tls(config) {
36998
+ function tls2(config) {
36746
36999
  return { ca: readPrivateFile(path35(config?.caFile), 1024 * 1024), cert: readPrivateFile(path35(config?.certFile), 1024 * 1024), key: readPrivateFile(path35(config?.keyFile), 16384) };
36747
37000
  }
36748
37001
  async function startTravelGateway(config) {
@@ -36751,7 +37004,7 @@ async function startTravelGateway(config) {
36751
37004
  for (const [name, value] of Object.entries(config.channels ?? {})) if (value?.enabled && !["feishu", "discord", "wechat"].includes(name)) throw new Error("TRAVEL_CHANNEL_NOT_CONTROLLED");
36752
37005
  const feishuIngress = config.ingressEnabled !== false && config.feishu?.ingressEnabled !== false && config.channels?.feishu?.enabled !== false;
36753
37006
  if (feishuIngress && !/^cli_[0-9a-fA-F]{16}$/.test(config.feishu?.appId)) throw new Error("TRAVEL_FEISHU_INVALID_CONFIG");
36754
- const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls(config.keyService.tls), timeoutMs: 1e4 };
37007
+ const keyConfig = { url: config.keyService.url, identity: config.keyService.identity, minimumDeletionWatermark: config.keyService.minimumDeletionWatermark, ...tls2(config.keyService.tls), timeoutMs: 1e4 };
36755
37008
  const material = await fetchTravelKey(keyConfig);
36756
37009
  const keyDigest = createHash37("sha256").update(material.key).digest("hex");
36757
37010
  let keyWatermark = material.deletionWatermark;
@@ -36805,7 +37058,7 @@ async function startTravelGateway(config) {
36805
37058
  await store.migrateStoredInputs();
36806
37059
  if (config.previouslyProcessedPlatformIds) store.importProcessedInputs(config.previouslyProcessedPlatformIds);
36807
37060
  platform = createFeishuGatewayPlatform(config.feishu);
36808
- server = createTravelGatewayServer({ ...tls(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: async (effect, body, assertCurrent) => {
37061
+ server = createTravelGatewayServer({ ...tls2(config.tls), store, authority, allowedPeers: config.allowedPeers, recoveryPeers: config.recoveryPeers, assertReady: assertKey, platform: { deliver: async (effect, body, assertCurrent) => {
36809
37062
  const packet = effect.kind === "MEDIA" ? (await Promise.resolve().then(() => (init_gateway_media(), gateway_media_exports))).decodeGatewayMedia(body).metadata : JSON.parse(body.toString());
36810
37063
  const channel = packet.channel ?? "feishu";
36811
37064
  if (channel === "feishu") return platform.deliver(effect, body, () => {
@@ -36826,7 +37079,7 @@ async function startTravelGateway(config) {
36826
37079
  if (config.control) {
36827
37080
  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");
36828
37081
  controlServer = createTravelAuthorityServer({
36829
- ...tls(config.control.tls ?? config.tls),
37082
+ ...tls2(config.control.tls ?? config.tls),
36830
37083
  authority,
36831
37084
  proxyFingerprints: config.control.proxyFingerprints,
36832
37085
  allowedPeers: config.control.allowedPeers,
@@ -36963,7 +37216,7 @@ if (process.argv[1] && /[\\/](gateway-main\.ts|travel-gateway\.mjs)$/.test(proce
36963
37216
  // src/continuity/pairing-control.ts
36964
37217
  async function startPairingControl(config) {
36965
37218
  const directory2 = resolve12(config.directory), file2 = join32(directory2, "pairing.json"), read2 = (name) => readPrivateFile(join32(directory2, name), 65536);
36966
- const tls2 = { ca: read2("ca.pem"), cert: read2("server.pem"), key: read2("server.key") };
37219
+ const tls3 = { ca: read2("ca.pem"), cert: read2("server.pem"), key: read2("server.key") };
36967
37220
  const authority = new TravelAuthority({ directory: join32(directory2, "authority") });
36968
37221
  let binding;
36969
37222
  try {
@@ -36995,7 +37248,7 @@ async function startPairingControl(config) {
36995
37248
  } finally {
36996
37249
  key4.fill(0);
36997
37250
  }
36998
- const keyServer = createKeyServiceServer({ ...tls2, store: keys });
37251
+ const keyServer = createKeyServiceServer({ ...tls3, store: keys });
36999
37252
  await new Promise((done, reject) => {
37000
37253
  keyServer.once("error", reject);
37001
37254
  keyServer.listen(config.ports.key, "127.0.0.1", done);
@@ -37025,7 +37278,7 @@ async function startPairingControl(config) {
37025
37278
  let ingress = existsSync15(join32(directory2, "ingress-enabled.json"));
37026
37279
  let gateway = await startTravelGateway({ ...gatewayConfig, ingressEnabled: ingress, feishu: { ...gatewayConfig.feishu, ingressEnabled: ingress && config.channels?.feishu?.enabled === true } });
37027
37280
  let changing = false, closed = false;
37028
- const pairServer = createServer4({ ...tls2, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
37281
+ const pairServer = createServer4({ ...tls3, minVersion: "TLSv1.3", requestCert: true, rejectUnauthorized: true }, async (req, res) => {
37029
37282
  res.setHeader("Content-Type", "application/json");
37030
37283
  res.setHeader("Cache-Control", "no-store");
37031
37284
  try {
@@ -37086,7 +37339,7 @@ async function startPairingControl(config) {
37086
37339
  keyServer.closeAllConnections();
37087
37340
  await new Promise((done) => keyServer.close(() => done()));
37088
37341
  keys.close();
37089
- tls2.key.fill(0);
37342
+ tls3.key.fill(0);
37090
37343
  };
37091
37344
  return { binding, keyServer, pairServer, get gateway() {
37092
37345
  return gateway;