engine7 7.1.130 → 7.1.131

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.mjs CHANGED
@@ -29214,6 +29214,96 @@ var init_mem7_services_fixup = __esm({
29214
29214
  }
29215
29215
  });
29216
29216
 
29217
+ // src/free-tier-apply.ts
29218
+ function isFreeTierConfig(cfg) {
29219
+ const hasProvider = !!cfg?.models?.providers?.[FREE_TIER_PROVIDER_ID];
29220
+ const primary = String(cfg?.agents?.defaults?.model?.primary || "");
29221
+ return hasProvider && primary.startsWith(`${FREE_TIER_PROVIDER_ID}/`);
29222
+ }
29223
+ var init_free_tier_apply = __esm({
29224
+ "src/free-tier-apply.ts"() {
29225
+ "use strict";
29226
+ init_cli_init_config();
29227
+ init_provision_free();
29228
+ init_cli_init_config();
29229
+ }
29230
+ });
29231
+
29232
+ // src/startup/free-tier-nort-fixup.ts
29233
+ function legacyDefaultExtract(cfg) {
29234
+ const ex = cfg?.topics?.extract;
29235
+ if (typeof ex?.model !== "string") return false;
29236
+ const model = ex.model.trim();
29237
+ const provider = typeof ex.provider === "string" ? ex.provider.trim() : "";
29238
+ if (model === FREE_TIER_FAST_REF && (!provider || provider === FREE_TIER_PROVIDER_ID)) return true;
29239
+ return provider === FREE_TIER_PROVIDER_ID && (LANE_MODELS.some((id) => id === model) || model === FREE_TIER_NORT_REF);
29240
+ }
29241
+ function needsFreeTierNortFixup(cfg) {
29242
+ const free = isFreeTierConfig(cfg);
29243
+ if (!free && !legacyDefaultExtract(cfg)) return false;
29244
+ const provider = cfg?.models?.providers?.[FREE_TIER_PROVIDER_ID];
29245
+ if (!provider) return false;
29246
+ const lanes = free || readPath(cfg, "topics.clean.model") === void 0 ? LANE_MODELS : [FREE_TIER_NORT_MODEL];
29247
+ if (lanes.some((id) => !(provider.models || []).some((m) => m?.id === id))) return true;
29248
+ return free && Object.keys(FIELD_REFS).some((path86) => readPath(cfg, path86) === void 0) || legacyDefaultExtract(cfg);
29249
+ }
29250
+ function readPath(obj, dotPath) {
29251
+ return dotPath.split(".").reduce((acc, k) => acc == null ? void 0 : acc[k], obj);
29252
+ }
29253
+ async function applyFreeTierNortFixup(io) {
29254
+ const cfg = io.all();
29255
+ if (!needsFreeTierNortFixup(cfg)) return false;
29256
+ const provider = cfg.models.providers[FREE_TIER_PROVIDER_ID];
29257
+ const registry2 = PROVIDER_DEFS[FREE_TIER_PROVIDER_ID]?.models ?? [];
29258
+ const free = isFreeTierConfig(cfg);
29259
+ const lanes = free || readPath(cfg, "topics.clean.model") === void 0 ? LANE_MODELS : [FREE_TIER_NORT_MODEL];
29260
+ const missingEntries = lanes.filter((id) => !(provider.models || []).some((m) => m?.id === id)).map((id) => registry2.find((m) => m.id === id));
29261
+ if (missingEntries.some((entry) => !entry)) return false;
29262
+ const writes = [];
29263
+ if (missingEntries.length) {
29264
+ const newModels = [...provider.models || [], ...missingEntries.map((entry) => ({ ...entry }))];
29265
+ writes.push([`models.providers.${FREE_TIER_PROVIDER_ID}.models`, newModels]);
29266
+ const pCopy = cfg.providers?.[FREE_TIER_PROVIDER_ID];
29267
+ if (pCopy && pCopy !== provider) pCopy.models = newModels;
29268
+ }
29269
+ for (const [path86, ref] of Object.entries(FIELD_REFS)) {
29270
+ if (free && readPath(cfg, path86) === void 0) writes.push([path86, ref]);
29271
+ }
29272
+ if (!free && readPath(cfg, "topics.clean.model") === void 0) {
29273
+ writes.push(["topics.clean.model", FREE_TIER_FAST_REF]);
29274
+ }
29275
+ const migratedLegacyExtract = legacyDefaultExtract(cfg);
29276
+ if (migratedLegacyExtract) {
29277
+ writes.push(["topics.extract.model", FREE_TIER_NORT_REF]);
29278
+ if ("provider" in cfg.topics.extract) writes.push(["topics.extract.provider", void 0]);
29279
+ }
29280
+ if (!writes.length) return false;
29281
+ let persisted = true;
29282
+ for (const [path86, value] of writes) {
29283
+ if (await io.set(path86, value) === false) persisted = false;
29284
+ }
29285
+ if (!persisted) {
29286
+ console.error("[startup] \u540E\u53F0\u6A21\u578B\u8865\u9F50 **\u672A\u5168\u90E8\u843D\u76D8**\uFF08\u672C\u6B21\u8FD0\u884C\u5185\u5B58\u91CC\u5DF2\u751F\u6548\uFF0C\u914D\u7F6E\u6587\u4EF6\u4ECD\u662F\u65E7\u7684\u2014\u2014\u4E0B\u6B21\u542F\u52A8\u4F1A\u91CD\u653E\uFF09\u3002\u4E0A\u9762 [liveConfig] \u90A3\u51E0\u884C\u662F\u539F\u56E0\u3002");
29287
+ return true;
29288
+ }
29289
+ console.log(`[startup] \u540E\u53F0\u6A21\u578B\u914D\u7F6E\u5DF2\u8865\u9F50\uFF08${writes.map(([p]) => p).join(", ")}\uFF1B\u81EA\u5B9A\u4E49\u6A21\u578B\u4FDD\u7559${migratedLegacyExtract ? `\uFF1B\u65E7\u9ED8\u8BA4 extract \u5DF2\u8FC1 ${FREE_TIER_NORT_REF}` : ""}\uFF09`);
29290
+ return true;
29291
+ }
29292
+ var FIELD_REFS, LANE_MODELS;
29293
+ var init_free_tier_nort_fixup = __esm({
29294
+ "src/startup/free-tier-nort-fixup.ts"() {
29295
+ "use strict";
29296
+ init_cli_init_config();
29297
+ init_free_tier_apply();
29298
+ FIELD_REFS = {
29299
+ "topics.extract.model": FREE_TIER_NORT_REF,
29300
+ "topics.clean.model": FREE_TIER_FAST_REF,
29301
+ "innerVoice.model": FREE_TIER_NORT_REF
29302
+ };
29303
+ LANE_MODELS = [FREE_TIER_FAST_MODEL, FREE_TIER_NORT_MODEL];
29304
+ }
29305
+ });
29306
+
29217
29307
  // src/reload/orchestrator.ts
29218
29308
  function sliceEnabled(slice) {
29219
29309
  if (slice == null) return false;
@@ -29457,6 +29547,7 @@ async function doReloadConfigInner(config2, deps, provider, force = false) {
29457
29547
  });
29458
29548
  reloadOrchestrator.beginReload();
29459
29549
  liveConfig.assign(newConfig);
29550
+ await applyFreeTierNortFixup({ all: () => liveConfig.all(), set: (p, v) => liveConfig.set(p, v) });
29460
29551
  await applyMem7ServicesFixup({ all: () => liveConfig.all(), set: (p, v) => liveConfig.set(p, v) });
29461
29552
  console.log(`[reload-debug] newConfig.tools.my_voice.provider = ${newConfig?.tools?.my_voice?.provider}`);
29462
29553
  console.log(`[reload-debug] post-assign liveConfig.tools.my_voice = ${JSON.stringify(liveConfig.get("tools.my_voice"))}`);
@@ -29697,6 +29788,7 @@ function startSecretsWatcher(config2, deps, provider, watchFn = fs14.watch) {
29697
29788
  try {
29698
29789
  const content = fs14.readFileSync(p, "utf-8");
29699
29790
  let updated = 0;
29791
+ const changedKeys = [];
29700
29792
  for (const line of content.split("\n")) {
29701
29793
  const trimmed = line.trim();
29702
29794
  if (!trimmed || trimmed.startsWith("#")) continue;
@@ -29705,12 +29797,13 @@ function startSecretsWatcher(config2, deps, provider, watchFn = fs14.watch) {
29705
29797
  const k = trimmed.slice(0, eq).trim();
29706
29798
  const v = trimmed.slice(eq + 1).trim();
29707
29799
  if (k) {
29800
+ if (process.env[k] !== v) changedKeys.push(k);
29708
29801
  process.env[k] = v;
29709
29802
  updated++;
29710
29803
  }
29711
29804
  }
29712
29805
  }
29713
- console.log(`[secrets-watch] ${updated} keys reloaded from ${p}`);
29806
+ console.log(`[secrets-watch] ${updated} keys loaded, ${changedKeys.length} changed` + (changedKeys.length ? `: ${changedKeys.join(", ")} (values not logged)` : "") + ` \u2014 from ${p}`);
29714
29807
  console.log(`[secrets-watch] force reload\uFF08\u8DF3\u8FC7\u539F\u6587\u5BF9\u6BD4\uFF09`);
29715
29808
  const result = await doReloadConfig(config2, deps, provider, true);
29716
29809
  console.log(`[secrets-watch] config reloaded: ok=${result.ok} changes=${result.changes.join(",")}`);
@@ -29766,6 +29859,7 @@ var init_reload = __esm({
29766
29859
  "use strict";
29767
29860
  init_loader();
29768
29861
  init_mem7_services_fixup();
29862
+ init_free_tier_nort_fixup();
29769
29863
  init_live();
29770
29864
  init_secrets_env();
29771
29865
  init_orchestrator();
@@ -38608,6 +38702,27 @@ var init_ffmpeg_path = __esm({
38608
38702
  }
38609
38703
  });
38610
38704
 
38705
+ // src/utils/api-port.ts
38706
+ var api_port_exports = {};
38707
+ __export(api_port_exports, {
38708
+ computeApiPort: () => computeApiPort
38709
+ });
38710
+ function computeApiPort(config2) {
38711
+ const basePort = config2.api?.port || 16890;
38712
+ const profileId = config2.profile?.id;
38713
+ if (profileId && profileId !== "default") {
38714
+ let hash6 = 0;
38715
+ for (const ch of profileId) hash6 = (hash6 << 5) - hash6 + ch.charCodeAt(0) | 0;
38716
+ return basePort + Math.abs(hash6) % 100;
38717
+ }
38718
+ return basePort;
38719
+ }
38720
+ var init_api_port = __esm({
38721
+ "src/utils/api-port.ts"() {
38722
+ "use strict";
38723
+ }
38724
+ });
38725
+
38611
38726
  // src/startup/skill-sync.ts
38612
38727
  import * as fs22 from "node:fs";
38613
38728
  import * as path19 from "node:path";
@@ -43996,8 +44111,12 @@ ${conversationText}`
43996
44111
  let result = "";
43997
44112
  let completed = false;
43998
44113
  let hadError = false;
44114
+ let completionReason;
43999
44115
  for await (const chunk of extractEngine.query(extractMessages, void 0, toolContext)) {
44000
- if (chunk.type === "result") completed = chunk.completionReason === "completed";
44116
+ if (chunk.type === "result") {
44117
+ completionReason = chunk.completionReason;
44118
+ completed = completionReason === "completed";
44119
+ }
44001
44120
  if (chunk.type === "error" || chunk.type === "tool_result" && chunk.isError) hadError = true;
44002
44121
  if (chunk.type === "text" && chunk.text) {
44003
44122
  result += chunk.text;
@@ -44007,7 +44126,7 @@ ${conversationText}`
44007
44126
  }
44008
44127
  }
44009
44128
  if (!completed || hadError || generation !== (state2.generations.get(sessionId) ?? 0)) {
44010
- console.warn(`[memory] extractMemories incomplete \u2014 input remains eligible, tools=${toolCount}, error=${hadError}`);
44129
+ console.warn(`[memory] extractMemories incomplete \u2014 input remains eligible, tools=${toolCount}, error=${hadError}, reason=${completionReason ?? "unknown"}, reset=${generation !== (state2.generations.get(sessionId) ?? 0)}`);
44011
44130
  return;
44012
44131
  }
44013
44132
  if (maxNewTs > 0) state2.lastTs.set(sessionId, maxNewTs);
@@ -44034,11 +44153,15 @@ ${conversationText}`
44034
44153
  },
44035
44154
  execute(messages, provider, model, sessionId, disableThinking, intervalMinutes) {
44036
44155
  if (!enabled) return Promise.resolve();
44156
+ const generation = state2.generations.get(sessionId) ?? 0;
44037
44157
  const previous = state2.tail;
44038
44158
  const lastTime = state2.lastExtractTime.get(sessionId);
44039
44159
  const alreadyCoolingDown = Boolean(intervalMinutes && intervalMinutes > 0 && lastTime && Date.now() - lastTime < intervalMinutes * 6e4);
44040
44160
  const snapshot = structuredClone(messages);
44041
- const task = (previous ?? Promise.resolve()).then(() => extract(snapshot, provider, model, sessionId, disableThinking, previous && !alreadyCoolingDown ? 0 : intervalMinutes));
44161
+ const task = (previous ?? Promise.resolve()).then(() => {
44162
+ if (generation !== (state2.generations.get(sessionId) ?? 0)) return;
44163
+ return extract(snapshot, provider, model, sessionId, disableThinking, previous && !alreadyCoolingDown ? 0 : intervalMinutes);
44164
+ });
44042
44165
  const tail2 = task.finally(() => {
44043
44166
  if (state2.tail === tail2) state2.tail = void 0;
44044
44167
  });
@@ -48483,27 +48606,6 @@ var init_qr_render = __esm({
48483
48606
  }
48484
48607
  });
48485
48608
 
48486
- // src/utils/api-port.ts
48487
- var api_port_exports = {};
48488
- __export(api_port_exports, {
48489
- computeApiPort: () => computeApiPort
48490
- });
48491
- function computeApiPort(config2) {
48492
- const basePort = config2.api?.port || 16890;
48493
- const profileId = config2.profile?.id;
48494
- if (profileId && profileId !== "default") {
48495
- let hash6 = 0;
48496
- for (const ch of profileId) hash6 = (hash6 << 5) - hash6 + ch.charCodeAt(0) | 0;
48497
- return basePort + Math.abs(hash6) % 100;
48498
- }
48499
- return basePort;
48500
- }
48501
- var init_api_port = __esm({
48502
- "src/utils/api-port.ts"() {
48503
- "use strict";
48504
- }
48505
- });
48506
-
48507
48609
  // src/version.ts
48508
48610
  import { readFileSync as readFileSync57 } from "node:fs";
48509
48611
  import { dirname as dirname23, join as join77 } from "node:path";
@@ -49431,7 +49533,7 @@ __export(voice_chat_tts_daemon_exports, {
49431
49533
  stopTtsDaemon: () => stopTtsDaemon
49432
49534
  });
49433
49535
  import { spawn as spawn5 } from "child_process";
49434
- import net2 from "net";
49536
+ import net3 from "net";
49435
49537
  import path54 from "path";
49436
49538
  import fs53 from "fs";
49437
49539
  function _log(msg2) {
@@ -49439,7 +49541,7 @@ function _log(msg2) {
49439
49541
  }
49440
49542
  function _healthOnce() {
49441
49543
  return new Promise((resolve26) => {
49442
- const sock = net2.connect(SOCK_PATH);
49544
+ const sock = net3.connect(SOCK_PATH);
49443
49545
  sock.setTimeout(2e3);
49444
49546
  sock.on("connect", () => {
49445
49547
  sock.write(JSON.stringify({ action: "health" }) + "\n");
@@ -54706,12 +54808,18 @@ function splitBubbles(message) {
54706
54808
  init_providers();
54707
54809
  init_reload();
54708
54810
 
54811
+ // src/reload/channels-entry.ts
54812
+ function channelsSelectSlice(cfg) {
54813
+ return { enabled: true, channels: cfg?.channels ?? null };
54814
+ }
54815
+
54709
54816
  // src/startup/bootstrap.ts
54710
54817
  import * as fs24 from "node:fs";
54711
54818
  import * as path21 from "node:path";
54712
54819
 
54713
54820
  // src/pid-lock.ts
54714
54821
  import fs15 from "node:fs";
54822
+ import net from "node:net";
54715
54823
  import path14 from "node:path";
54716
54824
  import { execSync as execSync2 } from "node:child_process";
54717
54825
  function enginePidFile(stateDir) {
@@ -54723,7 +54831,25 @@ function isEngineImage(text) {
54723
54831
  function isPidAlive(pid) {
54724
54832
  try {
54725
54833
  process.kill(pid, 0);
54726
- return true;
54834
+ } catch (err) {
54835
+ return err?.code === "EPERM";
54836
+ }
54837
+ return !isPidZombie(pid);
54838
+ }
54839
+ function statFieldIsZombie(statContent) {
54840
+ const state2 = statContent.slice(statContent.lastIndexOf(")") + 2).trim().charAt(0);
54841
+ return state2 === "Z";
54842
+ }
54843
+ function isPidZombie(pid) {
54844
+ try {
54845
+ if (process.platform === "linux") {
54846
+ return statFieldIsZombie(fs15.readFileSync(`/proc/${pid}/stat`, "utf-8"));
54847
+ }
54848
+ if (process.platform === "darwin") {
54849
+ const st = execSync2(`ps -p ${pid} -o stat=`, { encoding: "utf-8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"] });
54850
+ return st.trim().startsWith("Z");
54851
+ }
54852
+ return false;
54727
54853
  } catch {
54728
54854
  return false;
54729
54855
  }
@@ -54806,6 +54932,206 @@ function ownEnginePid(stateDir, myPid = process.pid) {
54806
54932
  isEngineImage: probeEngineImage
54807
54933
  });
54808
54934
  }
54935
+ function decidePortEviction(probe) {
54936
+ if (probe.ownerPid === null) return { action: "none" };
54937
+ if (probe.ownerPid === probe.myPid) return { action: "skip-self", pid: probe.ownerPid };
54938
+ const image = probe.imageText ?? "";
54939
+ if (!isEngineImage(image)) return { action: "skip-foreign", pid: probe.ownerPid, reason: "image" };
54940
+ if (imageBasename(image) === "engine7") return { action: "kill", pid: probe.ownerPid };
54941
+ if (probe.commandLineOk === true) return { action: "kill", pid: probe.ownerPid };
54942
+ if (probe.commandLineOk === false) return { action: "skip-foreign", pid: probe.ownerPid, reason: "cmdline" };
54943
+ return { action: "skip-foreign", pid: probe.ownerPid, reason: "cmdline-unprobeable" };
54944
+ }
54945
+ function imageBasename(imageText) {
54946
+ const s = (imageText ?? "").trim();
54947
+ if (!s) return "";
54948
+ const firstField = s.split(",")[0].trim().replace(/^"|"$/g, "");
54949
+ const base = firstField.split(/[\\/]/).pop() ?? firstField;
54950
+ return base.replace(/\.exe$/i, "").toLowerCase();
54951
+ }
54952
+ function pickConflictingPortOwners(probeOutput, port, myPid = process.pid) {
54953
+ if (!probeOutput) return [];
54954
+ const out = /* @__PURE__ */ new Set();
54955
+ const conflict = (addr) => {
54956
+ let a = addr.replace(/^\[/, "").replace(/\]$/, "").toLowerCase();
54957
+ if (a.startsWith("::ffff:")) a = a.slice("::ffff:".length);
54958
+ return a === "*" || a === "0.0.0.0" || a === "127.0.0.1" || a === "::";
54959
+ };
54960
+ for (const line of probeOutput.split(/\r?\n/)) {
54961
+ const net5 = /^\s*TCP\s+(\S*?):(\d+)\s+\S+\s+LISTENING\s+(\d+)\s*$/i.exec(line);
54962
+ if (net5) {
54963
+ const pid = Number(net5[3]);
54964
+ if (Number(net5[2]) === port && conflict(net5[1]) && pid !== myPid) out.add(pid);
54965
+ continue;
54966
+ }
54967
+ const cols = line.trim().split(/\s+/);
54968
+ if (cols.length >= 9 && /^\d+$/.test(cols[1] ?? "")) {
54969
+ const pid = Number(cols[1]);
54970
+ let name = cols[cols.length - 1] ?? "";
54971
+ if (/^\(/.test(name)) name = cols[cols.length - 2] ?? "";
54972
+ const lp = name.lastIndexOf(":");
54973
+ if (lp > 0 && Number(name.slice(lp + 1)) === port && conflict(name.slice(0, lp)) && pid !== myPid) out.add(pid);
54974
+ continue;
54975
+ }
54976
+ if (line.includes("pid=")) {
54977
+ const m = /^\S+\s+\d+\s+\d+\s+(\S+?):(\d+)\s/.exec(line);
54978
+ const pids = [...line.matchAll(/pid=(\d+)/g)].map((x) => Number(x[1]));
54979
+ if (m && Number(m[2]) === port && conflict(m[1])) {
54980
+ for (const pid of pids) if (pid !== myPid) out.add(pid);
54981
+ }
54982
+ }
54983
+ }
54984
+ return [...out];
54985
+ }
54986
+ function probePortOwnersRaw(port) {
54987
+ try {
54988
+ if (process.platform === "win32") {
54989
+ return { output: execSync2("netstat -ano -p tcp", {
54990
+ encoding: "utf-8",
54991
+ timeout: 5e3,
54992
+ stdio: ["ignore", "pipe", "ignore"],
54993
+ windowsHide: true
54994
+ // 1011:GUI 宿主下别闪黑窗
54995
+ }), unknown: false };
54996
+ }
54997
+ if (process.platform === "darwin") {
54998
+ return { output: execSync2(`lsof -nP -iTCP:${port} -sTCP:LISTEN`, {
54999
+ encoding: "utf-8",
55000
+ timeout: 5e3,
55001
+ stdio: ["ignore", "pipe", "ignore"]
55002
+ }), unknown: false };
55003
+ }
55004
+ return { output: execSync2(`ss -lptn sport = :${port}`, {
55005
+ encoding: "utf-8",
55006
+ timeout: 5e3,
55007
+ stdio: ["ignore", "pipe", "ignore"]
55008
+ }), unknown: false };
55009
+ } catch (err) {
55010
+ const status = err?.status;
55011
+ const unknown = status === null || status === void 0 || status === 127 || status > 1 || err?.code === "ENOENT" || err?.code === "ETIMEDOUT";
55012
+ return { output: null, unknown };
55013
+ }
55014
+ }
55015
+ function engineCommandlineMentions(pid, stateDir) {
55016
+ let cmd = "";
55017
+ try {
55018
+ if (process.platform === "win32") {
55019
+ cmd = execSync2(
55020
+ `powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CommandLine"`,
55021
+ { encoding: "utf-8", timeout: 1e4, stdio: ["ignore", "pipe", "ignore"], windowsHide: true }
55022
+ );
55023
+ } else if (process.platform === "darwin") {
55024
+ cmd = execSync2(`ps -p ${pid} -o command=`, { encoding: "utf-8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"] });
55025
+ } else {
55026
+ cmd = fs15.readFileSync(`/proc/${pid}/cmdline`, "utf-8").replace(/\0/g, " ");
55027
+ }
55028
+ } catch {
55029
+ return false;
55030
+ }
55031
+ return commandlineMentionsEngine(cmd, stateDir);
55032
+ }
55033
+ function commandlineMentionsEngine(cmd, stateDir) {
55034
+ const normalized = (cmd || "").toLowerCase();
55035
+ const dir = (stateDir || "").toLowerCase();
55036
+ if (dir && normalized.includes(dir)) return true;
55037
+ return /(?:^|[\\/":\s])engine7(?=$|[\\/."'\s])/.test(normalized);
55038
+ }
55039
+ function classifyPortOwner(pid, stateDir, myPid) {
55040
+ const imageText = probeImage(pid);
55041
+ const commandLineOk = imageBasename(imageText) === "engine7" ? true : /^(node|electron)(\.exe)?$/i.test(imageBasename(imageText)) ? engineCommandlineMentions(pid, stateDir) : false;
55042
+ return { decision: decidePortEviction({ ownerPid: pid, imageText, commandLineOk, myPid }), imageText };
55043
+ }
55044
+ function skipReason(decision) {
55045
+ return decision.action === "skip-self" ? "\u672C\u8FDB\u7A0B" : decision.action === "skip-foreign" && decision.reason === "image" ? "\u975E\u5F15\u64CE\u6620\u50CF" : decision.action === "skip-foreign" && decision.reason === "cmdline" ? "\u547D\u4EE4\u884C\u4E0D\u542B engine7/stateDir\uFF08\u65E0\u5173 node \u7A0B\u5E8F\uFF09" : "\u547D\u4EE4\u884C\u63A2\u4E0D\u5230\uFF08\u4FDD\u5B88\u4E0D\u6740\uFF09";
55046
+ }
55047
+ async function evictEngineOnApiPort(stateDir, apiPort, myPid = process.pid) {
55048
+ const probe1 = probePortOwnersRaw(apiPort);
55049
+ if (probe1.unknown) {
55050
+ console.error(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u6E05\u573A\u63A2\u9488\u8DD1\u4E0D\u4E86\uFF08\u547D\u4EE4\u7F3A\u5931/\u8D85\u65F6\uFF09\u2014\u2014\u515C\u5E95\u8FD9\u8F6E\u5931\u6548\uFF0C\u7531\u62A2\u9501\u65B9\u8BD5\u7ED1\u7AEF\u53E3\u88C1\u51B3\u3002`);
55051
+ return { killed: [], blockedKind: "foreign", probeUnknown: true, remaining: [] };
55052
+ }
55053
+ const owners = pickConflictingPortOwners(probe1.output, apiPort, myPid);
55054
+ const killed = [];
55055
+ let sawUndead = false;
55056
+ for (const pid of owners) {
55057
+ const { decision, imageText } = classifyPortOwner(pid, stateDir, myPid);
55058
+ if (decision.action !== "kill") {
55059
+ console.error(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u88AB\u975E\u6E05\u573A\u76EE\u6807\u5360\u7528\uFF08pid ${pid}\uFF0C\u6620\u50CF ${(imageText ?? "").trim().slice(0, 60) || "\u63A2\u4E0D\u5230"}\uFF1B${skipReason(decision)}\uFF09\u2014\u2014\u4E0D\u52A8\u5B83\u3002`);
55060
+ continue;
55061
+ }
55062
+ console.log(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u88AB\u65E7\u5F15\u64CE\u5B9E\u4F8B\u5360\u7528\uFF08pid ${pid}\uFF09\uFF0C\u6E05\u573A...`);
55063
+ killAndLog(stateDir, pid, `api port ${apiPort} occupied by stale engine`);
55064
+ if (await waitForPidGone(pid)) killed.push(pid);
55065
+ else sawUndead = true;
55066
+ }
55067
+ const probe2 = probePortOwnersRaw(apiPort);
55068
+ if (probe2.unknown) {
55069
+ if (sawUndead) {
55070
+ console.error(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u7684\u65E7\u5F15\u64CE\u6CA1\u80FD\u6740\u6389\uFF0C\u4E14\u590D\u6838\u63A2\u9488\u4E5F\u5931\u6548\u2014\u2014\u6309\u53CC\u5F00\u98CE\u9669\u5904\u7406\uFF0C\u5F15\u64CE\u62D2\u7EDD\u5E26\u75C5\u542F\u52A8\u3002`);
55071
+ return { killed, blockedKind: "undead", probeUnknown: true, remaining: [] };
55072
+ }
55073
+ console.error(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u590D\u6838\u63A2\u9488\u5931\u6548\u2014\u2014\u7531\u62A2\u9501\u65B9\u8BD5\u7ED1\u7AEF\u53E3\u88C1\u51B3\u3002`);
55074
+ return { killed, blockedKind: "foreign", probeUnknown: true, remaining: [] };
55075
+ }
55076
+ for (const pid of pickConflictingPortOwners(probe2.output, apiPort, myPid)) {
55077
+ const { decision, imageText } = classifyPortOwner(pid, stateDir, myPid);
55078
+ if (decision.action !== "kill") {
55079
+ console.error(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u88AB\u975E\u6E05\u573A\u76EE\u6807\u5360\u7528\uFF08pid ${pid}\uFF0C\u6620\u50CF ${(imageText ?? "").trim().slice(0, 60) || "\u63A2\u4E0D\u5230"}\uFF1B${skipReason(decision)}\uFF09\u2014\u2014\u4E0D\u52A8\u5B83\u3002`);
55080
+ continue;
55081
+ }
55082
+ console.log(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u590D\u6838\u53D1\u73B0\u65B0\u5360\u7528\uFF08pid ${pid}\uFF09\uFF0C\u518D\u6E05\u4E00\u6B21...`);
55083
+ killAndLog(stateDir, pid, `api port ${apiPort} re-check kill`);
55084
+ if (await waitForPidGone(pid)) killed.push(pid);
55085
+ else sawUndead = true;
55086
+ }
55087
+ const probe3 = probePortOwnersRaw(apiPort);
55088
+ const remaining = probe3.unknown ? [] : pickConflictingPortOwners(probe3.output, apiPort, myPid);
55089
+ let remainingEngine = false;
55090
+ for (const pid of remaining) {
55091
+ const { decision, imageText } = classifyPortOwner(pid, stateDir, myPid);
55092
+ if (decision.action === "kill") {
55093
+ remainingEngine = true;
55094
+ continue;
55095
+ }
55096
+ console.error(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u88AB\u975E\u6E05\u573A\u76EE\u6807\u5360\u7528\uFF08pid ${pid}\uFF0C\u6620\u50CF ${(imageText ?? "").trim().slice(0, 60) || "\u63A2\u4E0D\u5230"}\uFF1B${skipReason(decision)}\uFF09\u2014\u2014\u4E0D\u52A8\u5B83\u3002`);
55097
+ }
55098
+ if (sawUndead || remainingEngine) {
55099
+ console.error(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u4ECD\u6709\u5F15\u64CE\u8EAB\u4EFD\u7684\u5360\u7528\u8005\uFF08${remaining.join(",")}\uFF09${sawUndead ? "\uFF08\u6216\u6709\u7B49\u6B7B\u5931\u8D25\uFF09" : ""}\u2014\u2014\u6309\u53CC\u5F00\u98CE\u9669\u5904\u7406\uFF0C\u5F15\u64CE\u62D2\u7EDD\u5E26\u75C5\u542F\u52A8\u3002`);
55100
+ return { killed, blockedKind: "undead", probeUnknown: false, remaining };
55101
+ }
55102
+ if (remaining.length > 0) return { killed, blockedKind: "foreign", probeUnknown: false, remaining };
55103
+ return { killed, blockedKind: "none", probeUnknown: false, remaining: [] };
55104
+ }
55105
+ var EngineLockConflictError = class extends Error {
55106
+ };
55107
+ function tryBindLoopback(port, timeoutMs = 3e3) {
55108
+ return new Promise((resolve26) => {
55109
+ let settled = false;
55110
+ const srv = net.createServer();
55111
+ const finish = (ok) => {
55112
+ if (settled) return;
55113
+ settled = true;
55114
+ clearTimeout(timer);
55115
+ try {
55116
+ srv.close();
55117
+ } catch {
55118
+ }
55119
+ resolve26(ok);
55120
+ };
55121
+ const timer = setTimeout(() => finish(false), timeoutMs);
55122
+ srv.once("error", () => finish(false));
55123
+ srv.listen({ port, host: "127.0.0.1" }, () => finish(true));
55124
+ });
55125
+ }
55126
+ function pickRacingLockOwner(probe) {
55127
+ const cur = parseInt((probe.pidFileContent ?? "").trim(), 10);
55128
+ if (!Number.isInteger(cur) || cur <= 0) return null;
55129
+ if (cur === probe.myPid) return null;
55130
+ if (cur === probe.stalePid) return null;
55131
+ if (!probe.isAlive(cur)) return null;
55132
+ if (!probe.isEngineImage(cur)) return null;
55133
+ return cur;
55134
+ }
54809
55135
  async function waitForPidGone(pid, timeoutMs = 5e3) {
54810
55136
  const t0 = Date.now();
54811
55137
  while (Date.now() - t0 < timeoutMs) {
@@ -54814,13 +55140,47 @@ async function waitForPidGone(pid, timeoutMs = 5e3) {
54814
55140
  }
54815
55141
  return !isPidAlive(pid);
54816
55142
  }
54817
- function acquireEngineLock(stateDir) {
55143
+ async function acquireEngineLock(stateDir, apiPort) {
54818
55144
  const lockFile = enginePidFile(stateDir);
54819
55145
  const myPid = process.pid;
54820
55146
  const stale = ownEnginePid(stateDir, myPid);
54821
55147
  if (stale !== null) {
54822
55148
  console.log(`[pid-lock] Stale engine PID ${stale} still alive (engine), killing tree...`);
54823
55149
  killAndLog(stateDir, stale, "stale engine in lock file");
55150
+ if (!await waitForPidGone(stale)) {
55151
+ throw new EngineLockConflictError(
55152
+ `pid \u6587\u4EF6\u91CC\u7684\u65E7\u5F15\u64CE\uFF08pid ${stale}\uFF09\u6740\u4E0D\u6389\uFF08\u63D0\u6743/\u6740\u8F6F\u63E1\u7740\uFF1F\uFF09\u2014\u2014\u62D2\u7EDD\u5E26\u75C5\u542F\u52A8\uFF0C\u907F\u514D\u4E0E\u5B83\u53CC\u5F00\u3002 \u5904\u7F6E\uFF1A\u4ECE\u4EFB\u52A1\u7BA1\u7406\u5668\u7ED3\u675F\u8BE5\u8FDB\u7A0B\uFF0C\u6216\u7528\u7BA1\u7406\u5458\u6743\u9650\u91CD\u8BD5\uFF0C\u518D\u542F\u52A8\u5F15\u64CE\u3002`
55153
+ );
55154
+ }
55155
+ }
55156
+ if (apiPort && apiPort > 0) {
55157
+ const evict = await evictEngineOnApiPort(stateDir, apiPort, myPid);
55158
+ if (evict.blockedKind === "undead") {
55159
+ throw new EngineLockConflictError(
55160
+ `API \u7AEF\u53E3 ${apiPort} \u88AB\u6740\u4E0D\u6389\u7684\u65E7\u5F15\u64CE\u5B9E\u4F8B\u5360\u7740\uFF08pid ${evict.remaining.join(",")}\uFF09\u2014\u2014\u62D2\u7EDD\u5E26\u75C5\u542F\u52A8\uFF0C\u907F\u514D\u53CC\u5F00\u3002 \u5904\u7F6E\uFF1A\u4ECE\u4EFB\u52A1\u7BA1\u7406\u5668\u7ED3\u675F\u8BE5\u8FDB\u7A0B\uFF0C\u6216\u6539 config \u7684 api.port\u3002`
55161
+ );
55162
+ }
55163
+ if (evict.probeUnknown) {
55164
+ if (!await tryBindLoopback(apiPort)) {
55165
+ throw new EngineLockConflictError(
55166
+ `API \u7AEF\u53E3 ${apiPort} \u88AB\u8EAB\u4EFD\u4E0D\u660E\u7684\u7A0B\u5E8F\u5360\u7528\uFF08\u6E05\u573A\u63A2\u9488\u5931\u6548\uFF0C\u8BD5\u7ED1\u5931\u8D25\uFF09\u2014\u2014\u62D2\u7EDD\u5E26\u75C5\u542F\u52A8\u3002 \u5904\u7F6E\uFF1A\u627E\u51FA\u5360\u7528\u8005\uFF08netstat -ano | findstr ":${apiPort}" / lsof -iTCP:${apiPort}\uFF09\u6216\u6539 config \u7684 api.port\u3002`
55167
+ );
55168
+ }
55169
+ }
55170
+ }
55171
+ {
55172
+ const racer = pickRacingLockOwner({
55173
+ pidFileContent: readOwnEnginePidText(stateDir),
55174
+ stalePid: stale,
55175
+ myPid,
55176
+ isAlive: isPidAlive,
55177
+ isEngineImage: probeEngineImage
55178
+ });
55179
+ if (racer !== null) {
55180
+ throw new EngineLockConflictError(
55181
+ `\u542F\u52A8\u671F\u95F4\u53E6\u4E00\u4E2A\u5F15\u64CE\uFF08pid ${racer}\uFF09\u5DF2\u62A2\u5230\u8FD9\u4EFD stateDir\u2014\u2014\u672C\u6B21\u542F\u52A8\u9000\u51FA\uFF0C\u907F\u514D\u53CC\u5F00\u3002`
55182
+ );
55183
+ }
54824
55184
  }
54825
55185
  try {
54826
55186
  fs15.mkdirSync(stateDir, { recursive: true });
@@ -56083,10 +56443,19 @@ async function registerMemoryTools(_engineConfig) {
56083
56443
  init_license();
56084
56444
  init_loader();
56085
56445
  init_ffmpeg_path();
56446
+ init_api_port();
56086
56447
  init_skill_sync();
56087
56448
  async function bootEnvironment(config2) {
56088
56449
  process.env.ENGINE_STATE_DIR = config2.stateDir;
56089
- acquireEngineLock(config2.stateDir);
56450
+ try {
56451
+ await acquireEngineLock(config2.stateDir, computeApiPort(config2));
56452
+ } catch (err) {
56453
+ if (err instanceof EngineLockConflictError) {
56454
+ console.error(`[pid-lock] ${err.message}`);
56455
+ process.exit(1);
56456
+ }
56457
+ throw err;
56458
+ }
56090
56459
  process.env.ENGINE_MEDIA_DIR = config2.mediaDir;
56091
56460
  process.env.ENGINE7_WORKSPACE = config2.workspace;
56092
56461
  process.env.ENGINE7_STATE_DIR = config2.stateDir;
@@ -56214,18 +56583,7 @@ function applyFreeTierVideoFixup(io) {
56214
56583
 
56215
56584
  // src/startup/free-tier-voice-fixup.ts
56216
56585
  init_cli_init_config();
56217
-
56218
- // src/free-tier-apply.ts
56219
- init_cli_init_config();
56220
- init_provision_free();
56221
- init_cli_init_config();
56222
- function isFreeTierConfig(cfg) {
56223
- const hasProvider = !!cfg?.models?.providers?.[FREE_TIER_PROVIDER_ID];
56224
- const primary = String(cfg?.agents?.defaults?.model?.primary || "");
56225
- return hasProvider && primary.startsWith(`${FREE_TIER_PROVIDER_ID}/`);
56226
- }
56227
-
56228
- // src/startup/free-tier-voice-fixup.ts
56586
+ init_free_tier_apply();
56229
56587
  function needsFreeTierVoiceFixup(cfg) {
56230
56588
  if (!isFreeTierConfig(cfg)) return false;
56231
56589
  return cfg?.tools?.my_voice === void 0;
@@ -56242,64 +56600,8 @@ async function applyFreeTierVoiceFixup(io) {
56242
56600
  return true;
56243
56601
  }
56244
56602
 
56245
- // src/startup/free-tier-nort-fixup.ts
56246
- init_cli_init_config();
56247
- var FIELD_REFS = {
56248
- "topics.extract.model": FREE_TIER_NORT_REF,
56249
- "topics.clean.model": FREE_TIER_FAST_REF,
56250
- "innerVoice.model": FREE_TIER_NORT_REF
56251
- };
56252
- var LANE_MODELS = [FREE_TIER_FAST_MODEL, FREE_TIER_NORT_MODEL];
56253
- function legacyTwoFieldExtract(cfg) {
56254
- const ex = cfg?.topics?.extract;
56255
- return typeof ex?.provider === "string" && ex.provider.trim() === FREE_TIER_PROVIDER_ID && typeof ex?.model === "string" && LANE_MODELS.some((id) => id === ex.model.trim());
56256
- }
56257
- function needsFreeTierNortFixup(cfg) {
56258
- if (!isFreeTierConfig(cfg)) return false;
56259
- const provider = cfg?.models?.providers?.[FREE_TIER_PROVIDER_ID];
56260
- if (!provider) return false;
56261
- if (LANE_MODELS.some((id) => !(provider.models || []).some((m) => m?.id === id))) return true;
56262
- return Object.keys(FIELD_REFS).some((path86) => readPath(cfg, path86) === void 0) || legacyTwoFieldExtract(cfg);
56263
- }
56264
- function readPath(obj, dotPath) {
56265
- return dotPath.split(".").reduce((acc, k) => acc == null ? void 0 : acc[k], obj);
56266
- }
56267
- async function applyFreeTierNortFixup(io) {
56268
- const cfg = io.all();
56269
- if (!needsFreeTierNortFixup(cfg)) return false;
56270
- const provider = cfg.models.providers[FREE_TIER_PROVIDER_ID];
56271
- const registry2 = PROVIDER_DEFS[FREE_TIER_PROVIDER_ID]?.models ?? [];
56272
- const missingEntries = LANE_MODELS.filter((id) => !(provider.models || []).some((m) => m?.id === id)).map((id) => registry2.find((m) => m.id === id));
56273
- if (missingEntries.some((entry) => !entry)) return false;
56274
- const writes = [];
56275
- if (missingEntries.length) {
56276
- const newModels = [...provider.models || [], ...missingEntries.map((entry) => ({ ...entry }))];
56277
- writes.push([`models.providers.${FREE_TIER_PROVIDER_ID}.models`, newModels]);
56278
- const pCopy = cfg.providers?.[FREE_TIER_PROVIDER_ID];
56279
- if (pCopy && pCopy !== provider) pCopy.models = newModels;
56280
- }
56281
- for (const [path86, ref] of Object.entries(FIELD_REFS)) {
56282
- if (readPath(cfg, path86) === void 0) writes.push([path86, ref]);
56283
- }
56284
- const migratedLegacyExtract = legacyTwoFieldExtract(cfg);
56285
- if (migratedLegacyExtract) {
56286
- writes.push(["topics.extract.model", FREE_TIER_NORT_REF]);
56287
- writes.push(["topics.extract.provider", void 0]);
56288
- }
56289
- if (!writes.length) return false;
56290
- let persisted = true;
56291
- for (const [path86, value] of writes) {
56292
- if (await io.set(path86, value) === false) persisted = false;
56293
- }
56294
- if (!persisted) {
56295
- console.error("[startup] \u514D\u8D39\u6863 nort \u8865\u9F50 **\u672A\u5168\u90E8\u843D\u76D8**\uFF08\u672C\u6B21\u8FD0\u884C\u5185\u5B58\u91CC\u5DF2\u751F\u6548\uFF0C\u914D\u7F6E\u6587\u4EF6\u4ECD\u662F\u65E7\u7684\u2014\u2014\u4E0B\u6B21\u542F\u52A8\u4F1A\u91CD\u653E\uFF09\u3002\u4E0A\u9762 [liveConfig] \u90A3\u51E0\u884C\u662F\u539F\u56E0\u3002");
56296
- return true;
56297
- }
56298
- console.log(`[startup] \u514D\u8D39\u6863\u8865\u9F50\u540E\u53F0\u8F66\u9053\uFF1Aextract/innerVoice \u2192 ${FREE_TIER_NORT_REF}\u3001clean \u2192 ${FREE_TIER_FAST_REF}\uFF08\u5B58\u91CF\u6E05\u6D17\u8D70\u5FEB\u6863\uFF09\uFF08${writes.map(([p]) => p).join(", ")}\uFF1B\u7528\u6237\u81EA\u5DF1\u914D\u8FC7\u7684\u4E0D\u52A8${migratedLegacyExtract ? "\uFF1B\u65E7\u4E24\u5B57\u6BB5 extract \u5DF2\u8FC1 nort" : ""}\uFF09`);
56299
- return true;
56300
- }
56301
-
56302
56603
  // src/engine-startup.ts
56604
+ init_free_tier_nort_fixup();
56303
56605
  init_mem7_services_fixup();
56304
56606
 
56305
56607
  // src/startup/extract-cooldown-fixup.ts
@@ -62381,7 +62683,7 @@ var VoiceChatPlugin = class {
62381
62683
 
62382
62684
  // src/memory/everos/plugin.ts
62383
62685
  import { spawn as spawn4 } from "node:child_process";
62384
- import net from "node:net";
62686
+ import net2 from "node:net";
62385
62687
  import path46 from "node:path";
62386
62688
  import fs48 from "node:fs";
62387
62689
 
@@ -62821,7 +63123,7 @@ var EverosPlugin = class {
62821
63123
  }
62822
63124
  async isPortAlive(port) {
62823
63125
  return new Promise((resolve26) => {
62824
- const socket = new net.Socket();
63126
+ const socket = new net2.Socket();
62825
63127
  socket.setTimeout(2e3);
62826
63128
  socket.on("connect", () => {
62827
63129
  socket.destroy();
@@ -68362,7 +68664,7 @@ import { promisify as promisify4 } from "node:util";
68362
68664
  import * as fs54 from "node:fs";
68363
68665
  import * as path55 from "node:path";
68364
68666
  import * as os6 from "node:os";
68365
- import net3 from "net";
68667
+ import net4 from "net";
68366
68668
  var execFileAsync2 = promisify4(execFile5);
68367
68669
  var VOICE_DIR = path55.join(os6.tmpdir(), "engine-voice");
68368
68670
  function wavDurationSec(buf) {
@@ -68538,7 +68840,7 @@ async function ttsCosyvoiceWorker(text, cfg, onChunk) {
68538
68840
  }
68539
68841
  }
68540
68842
  return new Promise((resolve26, reject) => {
68541
- const sock = net3.connect(getSockPath());
68843
+ const sock = net4.connect(getSockPath());
68542
68844
  let buf = "";
68543
68845
  const finish = (err) => {
68544
68846
  try {
@@ -68874,8 +69176,8 @@ var DeskBuddyAdapter = class {
68874
69176
  startAsr() {
68875
69177
  if (this.asrSock) return;
68876
69178
  const port = this.asrBackend === "sensevoice" ? 9790 : 9791;
68877
- const net4 = __require("node:net");
68878
- const sock = net4.connect(port, "127.0.0.1");
69179
+ const net5 = __require("node:net");
69180
+ const sock = net5.connect(port, "127.0.0.1");
68879
69181
  sock.setNoDelay(true);
68880
69182
  this.asrSock = sock;
68881
69183
  this.asrBuf = "";
@@ -82670,8 +82972,10 @@ async function startEngine(config2, opts) {
82670
82972
  };
82671
82973
  reloadOrchestrator.register({
82672
82974
  name: "channels",
82673
- // channels 段常开(空段 = 全拆,reconcile 自然处理)
82674
- select: (cfg) => ({ enabled: true, channels: cfg.channels ?? null }),
82975
+ // channels 段常开(空段 = 全拆,reconcile 自然处理)。select 抽出为纯函数——
82976
+ // 它吃的是 resolveEnv **之后**的活树,secrets-only 换 token 也要能触发重建
82977
+ // (1102:这条链没有回归钉害我误诊一轮,见 channels-entry.ts 头注)
82978
+ select: channelsSelectSlice,
82675
82979
  start: () => runChannelsReconcile(),
82676
82980
  // fire-and-forget:defer 重试不阻塞后续 entry
82677
82981
  stop: () => {