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.
@@ -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(config, 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(config, 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(config, 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(config, 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();
@@ -38474,6 +38568,27 @@ var init_ffmpeg_path = __esm({
38474
38568
  }
38475
38569
  });
38476
38570
 
38571
+ // src/utils/api-port.ts
38572
+ var api_port_exports = {};
38573
+ __export(api_port_exports, {
38574
+ computeApiPort: () => computeApiPort
38575
+ });
38576
+ function computeApiPort(config) {
38577
+ const basePort = config.api?.port || 16890;
38578
+ const profileId = config.profile?.id;
38579
+ if (profileId && profileId !== "default") {
38580
+ let hash6 = 0;
38581
+ for (const ch of profileId) hash6 = (hash6 << 5) - hash6 + ch.charCodeAt(0) | 0;
38582
+ return basePort + Math.abs(hash6) % 100;
38583
+ }
38584
+ return basePort;
38585
+ }
38586
+ var init_api_port = __esm({
38587
+ "src/utils/api-port.ts"() {
38588
+ "use strict";
38589
+ }
38590
+ });
38591
+
38477
38592
  // src/startup/skill-sync.ts
38478
38593
  import * as fs22 from "node:fs";
38479
38594
  import * as path19 from "node:path";
@@ -43862,8 +43977,12 @@ ${conversationText}`
43862
43977
  let result = "";
43863
43978
  let completed = false;
43864
43979
  let hadError = false;
43980
+ let completionReason;
43865
43981
  for await (const chunk of extractEngine.query(extractMessages, void 0, toolContext)) {
43866
- if (chunk.type === "result") completed = chunk.completionReason === "completed";
43982
+ if (chunk.type === "result") {
43983
+ completionReason = chunk.completionReason;
43984
+ completed = completionReason === "completed";
43985
+ }
43867
43986
  if (chunk.type === "error" || chunk.type === "tool_result" && chunk.isError) hadError = true;
43868
43987
  if (chunk.type === "text" && chunk.text) {
43869
43988
  result += chunk.text;
@@ -43873,7 +43992,7 @@ ${conversationText}`
43873
43992
  }
43874
43993
  }
43875
43994
  if (!completed || hadError || generation !== (state2.generations.get(sessionId) ?? 0)) {
43876
- console.warn(`[memory] extractMemories incomplete \u2014 input remains eligible, tools=${toolCount}, error=${hadError}`);
43995
+ console.warn(`[memory] extractMemories incomplete \u2014 input remains eligible, tools=${toolCount}, error=${hadError}, reason=${completionReason ?? "unknown"}, reset=${generation !== (state2.generations.get(sessionId) ?? 0)}`);
43877
43996
  return;
43878
43997
  }
43879
43998
  if (maxNewTs > 0) state2.lastTs.set(sessionId, maxNewTs);
@@ -43900,11 +44019,15 @@ ${conversationText}`
43900
44019
  },
43901
44020
  execute(messages, provider, model, sessionId, disableThinking, intervalMinutes) {
43902
44021
  if (!enabled) return Promise.resolve();
44022
+ const generation = state2.generations.get(sessionId) ?? 0;
43903
44023
  const previous = state2.tail;
43904
44024
  const lastTime = state2.lastExtractTime.get(sessionId);
43905
44025
  const alreadyCoolingDown = Boolean(intervalMinutes && intervalMinutes > 0 && lastTime && Date.now() - lastTime < intervalMinutes * 6e4);
43906
44026
  const snapshot = structuredClone(messages);
43907
- const task = (previous ?? Promise.resolve()).then(() => extract(snapshot, provider, model, sessionId, disableThinking, previous && !alreadyCoolingDown ? 0 : intervalMinutes));
44027
+ const task = (previous ?? Promise.resolve()).then(() => {
44028
+ if (generation !== (state2.generations.get(sessionId) ?? 0)) return;
44029
+ return extract(snapshot, provider, model, sessionId, disableThinking, previous && !alreadyCoolingDown ? 0 : intervalMinutes);
44030
+ });
43908
44031
  const tail2 = task.finally(() => {
43909
44032
  if (state2.tail === tail2) state2.tail = void 0;
43910
44033
  });
@@ -48349,27 +48472,6 @@ var init_qr_render = __esm({
48349
48472
  }
48350
48473
  });
48351
48474
 
48352
- // src/utils/api-port.ts
48353
- var api_port_exports = {};
48354
- __export(api_port_exports, {
48355
- computeApiPort: () => computeApiPort
48356
- });
48357
- function computeApiPort(config) {
48358
- const basePort = config.api?.port || 16890;
48359
- const profileId = config.profile?.id;
48360
- if (profileId && profileId !== "default") {
48361
- let hash6 = 0;
48362
- for (const ch of profileId) hash6 = (hash6 << 5) - hash6 + ch.charCodeAt(0) | 0;
48363
- return basePort + Math.abs(hash6) % 100;
48364
- }
48365
- return basePort;
48366
- }
48367
- var init_api_port = __esm({
48368
- "src/utils/api-port.ts"() {
48369
- "use strict";
48370
- }
48371
- });
48372
-
48373
48475
  // src/version.ts
48374
48476
  import { readFileSync as readFileSync57 } from "node:fs";
48375
48477
  import { dirname as dirname23, join as join77 } from "node:path";
@@ -49297,7 +49399,7 @@ __export(voice_chat_tts_daemon_exports, {
49297
49399
  stopTtsDaemon: () => stopTtsDaemon
49298
49400
  });
49299
49401
  import { spawn as spawn5 } from "child_process";
49300
- import net2 from "net";
49402
+ import net3 from "net";
49301
49403
  import path54 from "path";
49302
49404
  import fs53 from "fs";
49303
49405
  function _log(msg2) {
@@ -49305,7 +49407,7 @@ function _log(msg2) {
49305
49407
  }
49306
49408
  function _healthOnce() {
49307
49409
  return new Promise((resolve26) => {
49308
- const sock = net2.connect(SOCK_PATH);
49410
+ const sock = net3.connect(SOCK_PATH);
49309
49411
  sock.setTimeout(2e3);
49310
49412
  sock.on("connect", () => {
49311
49413
  sock.write(JSON.stringify({ action: "health" }) + "\n");
@@ -54344,12 +54446,18 @@ function splitBubbles(message) {
54344
54446
  init_providers();
54345
54447
  init_reload();
54346
54448
 
54449
+ // src/reload/channels-entry.ts
54450
+ function channelsSelectSlice(cfg) {
54451
+ return { enabled: true, channels: cfg?.channels ?? null };
54452
+ }
54453
+
54347
54454
  // src/startup/bootstrap.ts
54348
54455
  import * as fs24 from "node:fs";
54349
54456
  import * as path21 from "node:path";
54350
54457
 
54351
54458
  // src/pid-lock.ts
54352
54459
  import fs15 from "node:fs";
54460
+ import net from "node:net";
54353
54461
  import path14 from "node:path";
54354
54462
  import { execSync as execSync2 } from "node:child_process";
54355
54463
  function enginePidFile(stateDir) {
@@ -54361,7 +54469,25 @@ function isEngineImage(text) {
54361
54469
  function isPidAlive(pid) {
54362
54470
  try {
54363
54471
  process.kill(pid, 0);
54364
- return true;
54472
+ } catch (err) {
54473
+ return err?.code === "EPERM";
54474
+ }
54475
+ return !isPidZombie(pid);
54476
+ }
54477
+ function statFieldIsZombie(statContent) {
54478
+ const state2 = statContent.slice(statContent.lastIndexOf(")") + 2).trim().charAt(0);
54479
+ return state2 === "Z";
54480
+ }
54481
+ function isPidZombie(pid) {
54482
+ try {
54483
+ if (process.platform === "linux") {
54484
+ return statFieldIsZombie(fs15.readFileSync(`/proc/${pid}/stat`, "utf-8"));
54485
+ }
54486
+ if (process.platform === "darwin") {
54487
+ const st = execSync2(`ps -p ${pid} -o stat=`, { encoding: "utf-8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"] });
54488
+ return st.trim().startsWith("Z");
54489
+ }
54490
+ return false;
54365
54491
  } catch {
54366
54492
  return false;
54367
54493
  }
@@ -54444,6 +54570,206 @@ function ownEnginePid(stateDir, myPid = process.pid) {
54444
54570
  isEngineImage: probeEngineImage
54445
54571
  });
54446
54572
  }
54573
+ function decidePortEviction(probe) {
54574
+ if (probe.ownerPid === null) return { action: "none" };
54575
+ if (probe.ownerPid === probe.myPid) return { action: "skip-self", pid: probe.ownerPid };
54576
+ const image = probe.imageText ?? "";
54577
+ if (!isEngineImage(image)) return { action: "skip-foreign", pid: probe.ownerPid, reason: "image" };
54578
+ if (imageBasename(image) === "engine7") return { action: "kill", pid: probe.ownerPid };
54579
+ if (probe.commandLineOk === true) return { action: "kill", pid: probe.ownerPid };
54580
+ if (probe.commandLineOk === false) return { action: "skip-foreign", pid: probe.ownerPid, reason: "cmdline" };
54581
+ return { action: "skip-foreign", pid: probe.ownerPid, reason: "cmdline-unprobeable" };
54582
+ }
54583
+ function imageBasename(imageText) {
54584
+ const s = (imageText ?? "").trim();
54585
+ if (!s) return "";
54586
+ const firstField = s.split(",")[0].trim().replace(/^"|"$/g, "");
54587
+ const base = firstField.split(/[\\/]/).pop() ?? firstField;
54588
+ return base.replace(/\.exe$/i, "").toLowerCase();
54589
+ }
54590
+ function pickConflictingPortOwners(probeOutput, port, myPid = process.pid) {
54591
+ if (!probeOutput) return [];
54592
+ const out = /* @__PURE__ */ new Set();
54593
+ const conflict = (addr) => {
54594
+ let a = addr.replace(/^\[/, "").replace(/\]$/, "").toLowerCase();
54595
+ if (a.startsWith("::ffff:")) a = a.slice("::ffff:".length);
54596
+ return a === "*" || a === "0.0.0.0" || a === "127.0.0.1" || a === "::";
54597
+ };
54598
+ for (const line of probeOutput.split(/\r?\n/)) {
54599
+ const net5 = /^\s*TCP\s+(\S*?):(\d+)\s+\S+\s+LISTENING\s+(\d+)\s*$/i.exec(line);
54600
+ if (net5) {
54601
+ const pid = Number(net5[3]);
54602
+ if (Number(net5[2]) === port && conflict(net5[1]) && pid !== myPid) out.add(pid);
54603
+ continue;
54604
+ }
54605
+ const cols = line.trim().split(/\s+/);
54606
+ if (cols.length >= 9 && /^\d+$/.test(cols[1] ?? "")) {
54607
+ const pid = Number(cols[1]);
54608
+ let name = cols[cols.length - 1] ?? "";
54609
+ if (/^\(/.test(name)) name = cols[cols.length - 2] ?? "";
54610
+ const lp = name.lastIndexOf(":");
54611
+ if (lp > 0 && Number(name.slice(lp + 1)) === port && conflict(name.slice(0, lp)) && pid !== myPid) out.add(pid);
54612
+ continue;
54613
+ }
54614
+ if (line.includes("pid=")) {
54615
+ const m = /^\S+\s+\d+\s+\d+\s+(\S+?):(\d+)\s/.exec(line);
54616
+ const pids = [...line.matchAll(/pid=(\d+)/g)].map((x) => Number(x[1]));
54617
+ if (m && Number(m[2]) === port && conflict(m[1])) {
54618
+ for (const pid of pids) if (pid !== myPid) out.add(pid);
54619
+ }
54620
+ }
54621
+ }
54622
+ return [...out];
54623
+ }
54624
+ function probePortOwnersRaw(port) {
54625
+ try {
54626
+ if (process.platform === "win32") {
54627
+ return { output: execSync2("netstat -ano -p tcp", {
54628
+ encoding: "utf-8",
54629
+ timeout: 5e3,
54630
+ stdio: ["ignore", "pipe", "ignore"],
54631
+ windowsHide: true
54632
+ // 1011:GUI 宿主下别闪黑窗
54633
+ }), unknown: false };
54634
+ }
54635
+ if (process.platform === "darwin") {
54636
+ return { output: execSync2(`lsof -nP -iTCP:${port} -sTCP:LISTEN`, {
54637
+ encoding: "utf-8",
54638
+ timeout: 5e3,
54639
+ stdio: ["ignore", "pipe", "ignore"]
54640
+ }), unknown: false };
54641
+ }
54642
+ return { output: execSync2(`ss -lptn sport = :${port}`, {
54643
+ encoding: "utf-8",
54644
+ timeout: 5e3,
54645
+ stdio: ["ignore", "pipe", "ignore"]
54646
+ }), unknown: false };
54647
+ } catch (err) {
54648
+ const status = err?.status;
54649
+ const unknown = status === null || status === void 0 || status === 127 || status > 1 || err?.code === "ENOENT" || err?.code === "ETIMEDOUT";
54650
+ return { output: null, unknown };
54651
+ }
54652
+ }
54653
+ function engineCommandlineMentions(pid, stateDir) {
54654
+ let cmd = "";
54655
+ try {
54656
+ if (process.platform === "win32") {
54657
+ cmd = execSync2(
54658
+ `powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CommandLine"`,
54659
+ { encoding: "utf-8", timeout: 1e4, stdio: ["ignore", "pipe", "ignore"], windowsHide: true }
54660
+ );
54661
+ } else if (process.platform === "darwin") {
54662
+ cmd = execSync2(`ps -p ${pid} -o command=`, { encoding: "utf-8", timeout: 3e3, stdio: ["ignore", "pipe", "ignore"] });
54663
+ } else {
54664
+ cmd = fs15.readFileSync(`/proc/${pid}/cmdline`, "utf-8").replace(/\0/g, " ");
54665
+ }
54666
+ } catch {
54667
+ return false;
54668
+ }
54669
+ return commandlineMentionsEngine(cmd, stateDir);
54670
+ }
54671
+ function commandlineMentionsEngine(cmd, stateDir) {
54672
+ const normalized = (cmd || "").toLowerCase();
54673
+ const dir = (stateDir || "").toLowerCase();
54674
+ if (dir && normalized.includes(dir)) return true;
54675
+ return /(?:^|[\\/":\s])engine7(?=$|[\\/."'\s])/.test(normalized);
54676
+ }
54677
+ function classifyPortOwner(pid, stateDir, myPid) {
54678
+ const imageText = probeImage(pid);
54679
+ const commandLineOk = imageBasename(imageText) === "engine7" ? true : /^(node|electron)(\.exe)?$/i.test(imageBasename(imageText)) ? engineCommandlineMentions(pid, stateDir) : false;
54680
+ return { decision: decidePortEviction({ ownerPid: pid, imageText, commandLineOk, myPid }), imageText };
54681
+ }
54682
+ function skipReason(decision) {
54683
+ 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";
54684
+ }
54685
+ async function evictEngineOnApiPort(stateDir, apiPort, myPid = process.pid) {
54686
+ const probe1 = probePortOwnersRaw(apiPort);
54687
+ if (probe1.unknown) {
54688
+ 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`);
54689
+ return { killed: [], blockedKind: "foreign", probeUnknown: true, remaining: [] };
54690
+ }
54691
+ const owners = pickConflictingPortOwners(probe1.output, apiPort, myPid);
54692
+ const killed = [];
54693
+ let sawUndead = false;
54694
+ for (const pid of owners) {
54695
+ const { decision, imageText } = classifyPortOwner(pid, stateDir, myPid);
54696
+ if (decision.action !== "kill") {
54697
+ 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`);
54698
+ continue;
54699
+ }
54700
+ console.log(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u88AB\u65E7\u5F15\u64CE\u5B9E\u4F8B\u5360\u7528\uFF08pid ${pid}\uFF09\uFF0C\u6E05\u573A...`);
54701
+ killAndLog(stateDir, pid, `api port ${apiPort} occupied by stale engine`);
54702
+ if (await waitForPidGone(pid)) killed.push(pid);
54703
+ else sawUndead = true;
54704
+ }
54705
+ const probe2 = probePortOwnersRaw(apiPort);
54706
+ if (probe2.unknown) {
54707
+ if (sawUndead) {
54708
+ 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`);
54709
+ return { killed, blockedKind: "undead", probeUnknown: true, remaining: [] };
54710
+ }
54711
+ 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`);
54712
+ return { killed, blockedKind: "foreign", probeUnknown: true, remaining: [] };
54713
+ }
54714
+ for (const pid of pickConflictingPortOwners(probe2.output, apiPort, myPid)) {
54715
+ const { decision, imageText } = classifyPortOwner(pid, stateDir, myPid);
54716
+ if (decision.action !== "kill") {
54717
+ 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`);
54718
+ continue;
54719
+ }
54720
+ console.log(`[pid-lock] \u7AEF\u53E3 ${apiPort} \u590D\u6838\u53D1\u73B0\u65B0\u5360\u7528\uFF08pid ${pid}\uFF09\uFF0C\u518D\u6E05\u4E00\u6B21...`);
54721
+ killAndLog(stateDir, pid, `api port ${apiPort} re-check kill`);
54722
+ if (await waitForPidGone(pid)) killed.push(pid);
54723
+ else sawUndead = true;
54724
+ }
54725
+ const probe3 = probePortOwnersRaw(apiPort);
54726
+ const remaining = probe3.unknown ? [] : pickConflictingPortOwners(probe3.output, apiPort, myPid);
54727
+ let remainingEngine = false;
54728
+ for (const pid of remaining) {
54729
+ const { decision, imageText } = classifyPortOwner(pid, stateDir, myPid);
54730
+ if (decision.action === "kill") {
54731
+ remainingEngine = true;
54732
+ continue;
54733
+ }
54734
+ 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`);
54735
+ }
54736
+ if (sawUndead || remainingEngine) {
54737
+ 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`);
54738
+ return { killed, blockedKind: "undead", probeUnknown: false, remaining };
54739
+ }
54740
+ if (remaining.length > 0) return { killed, blockedKind: "foreign", probeUnknown: false, remaining };
54741
+ return { killed, blockedKind: "none", probeUnknown: false, remaining: [] };
54742
+ }
54743
+ var EngineLockConflictError = class extends Error {
54744
+ };
54745
+ function tryBindLoopback(port, timeoutMs = 3e3) {
54746
+ return new Promise((resolve26) => {
54747
+ let settled = false;
54748
+ const srv = net.createServer();
54749
+ const finish = (ok) => {
54750
+ if (settled) return;
54751
+ settled = true;
54752
+ clearTimeout(timer);
54753
+ try {
54754
+ srv.close();
54755
+ } catch {
54756
+ }
54757
+ resolve26(ok);
54758
+ };
54759
+ const timer = setTimeout(() => finish(false), timeoutMs);
54760
+ srv.once("error", () => finish(false));
54761
+ srv.listen({ port, host: "127.0.0.1" }, () => finish(true));
54762
+ });
54763
+ }
54764
+ function pickRacingLockOwner(probe) {
54765
+ const cur = parseInt((probe.pidFileContent ?? "").trim(), 10);
54766
+ if (!Number.isInteger(cur) || cur <= 0) return null;
54767
+ if (cur === probe.myPid) return null;
54768
+ if (cur === probe.stalePid) return null;
54769
+ if (!probe.isAlive(cur)) return null;
54770
+ if (!probe.isEngineImage(cur)) return null;
54771
+ return cur;
54772
+ }
54447
54773
  async function waitForPidGone(pid, timeoutMs = 5e3) {
54448
54774
  const t0 = Date.now();
54449
54775
  while (Date.now() - t0 < timeoutMs) {
@@ -54452,13 +54778,47 @@ async function waitForPidGone(pid, timeoutMs = 5e3) {
54452
54778
  }
54453
54779
  return !isPidAlive(pid);
54454
54780
  }
54455
- function acquireEngineLock(stateDir) {
54781
+ async function acquireEngineLock(stateDir, apiPort) {
54456
54782
  const lockFile = enginePidFile(stateDir);
54457
54783
  const myPid = process.pid;
54458
54784
  const stale = ownEnginePid(stateDir, myPid);
54459
54785
  if (stale !== null) {
54460
54786
  console.log(`[pid-lock] Stale engine PID ${stale} still alive (engine), killing tree...`);
54461
54787
  killAndLog(stateDir, stale, "stale engine in lock file");
54788
+ if (!await waitForPidGone(stale)) {
54789
+ throw new EngineLockConflictError(
54790
+ `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`
54791
+ );
54792
+ }
54793
+ }
54794
+ if (apiPort && apiPort > 0) {
54795
+ const evict = await evictEngineOnApiPort(stateDir, apiPort, myPid);
54796
+ if (evict.blockedKind === "undead") {
54797
+ throw new EngineLockConflictError(
54798
+ `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`
54799
+ );
54800
+ }
54801
+ if (evict.probeUnknown) {
54802
+ if (!await tryBindLoopback(apiPort)) {
54803
+ throw new EngineLockConflictError(
54804
+ `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`
54805
+ );
54806
+ }
54807
+ }
54808
+ }
54809
+ {
54810
+ const racer = pickRacingLockOwner({
54811
+ pidFileContent: readOwnEnginePidText(stateDir),
54812
+ stalePid: stale,
54813
+ myPid,
54814
+ isAlive: isPidAlive,
54815
+ isEngineImage: probeEngineImage
54816
+ });
54817
+ if (racer !== null) {
54818
+ throw new EngineLockConflictError(
54819
+ `\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`
54820
+ );
54821
+ }
54462
54822
  }
54463
54823
  try {
54464
54824
  fs15.mkdirSync(stateDir, { recursive: true });
@@ -55816,10 +56176,19 @@ if (!verifyPublicKeyIntegrity()) {
55816
56176
  // src/startup/bootstrap.ts
55817
56177
  init_loader();
55818
56178
  init_ffmpeg_path();
56179
+ init_api_port();
55819
56180
  init_skill_sync();
55820
56181
  async function bootEnvironment(config) {
55821
56182
  process.env.ENGINE_STATE_DIR = config.stateDir;
55822
- acquireEngineLock(config.stateDir);
56183
+ try {
56184
+ await acquireEngineLock(config.stateDir, computeApiPort(config));
56185
+ } catch (err) {
56186
+ if (err instanceof EngineLockConflictError) {
56187
+ console.error(`[pid-lock] ${err.message}`);
56188
+ process.exit(1);
56189
+ }
56190
+ throw err;
56191
+ }
55823
56192
  process.env.ENGINE_MEDIA_DIR = config.mediaDir;
55824
56193
  process.env.ENGINE7_WORKSPACE = config.workspace;
55825
56194
  process.env.ENGINE7_STATE_DIR = config.stateDir;
@@ -55947,18 +56316,7 @@ function applyFreeTierVideoFixup(io) {
55947
56316
 
55948
56317
  // src/startup/free-tier-voice-fixup.ts
55949
56318
  init_cli_init_config();
55950
-
55951
- // src/free-tier-apply.ts
55952
- init_cli_init_config();
55953
- init_provision_free();
55954
- init_cli_init_config();
55955
- function isFreeTierConfig(cfg) {
55956
- const hasProvider = !!cfg?.models?.providers?.[FREE_TIER_PROVIDER_ID];
55957
- const primary = String(cfg?.agents?.defaults?.model?.primary || "");
55958
- return hasProvider && primary.startsWith(`${FREE_TIER_PROVIDER_ID}/`);
55959
- }
55960
-
55961
- // src/startup/free-tier-voice-fixup.ts
56319
+ init_free_tier_apply();
55962
56320
  function needsFreeTierVoiceFixup(cfg) {
55963
56321
  if (!isFreeTierConfig(cfg)) return false;
55964
56322
  return cfg?.tools?.my_voice === void 0;
@@ -55975,64 +56333,8 @@ async function applyFreeTierVoiceFixup(io) {
55975
56333
  return true;
55976
56334
  }
55977
56335
 
55978
- // src/startup/free-tier-nort-fixup.ts
55979
- init_cli_init_config();
55980
- var FIELD_REFS = {
55981
- "topics.extract.model": FREE_TIER_NORT_REF,
55982
- "topics.clean.model": FREE_TIER_FAST_REF,
55983
- "innerVoice.model": FREE_TIER_NORT_REF
55984
- };
55985
- var LANE_MODELS = [FREE_TIER_FAST_MODEL, FREE_TIER_NORT_MODEL];
55986
- function legacyTwoFieldExtract(cfg) {
55987
- const ex = cfg?.topics?.extract;
55988
- return typeof ex?.provider === "string" && ex.provider.trim() === FREE_TIER_PROVIDER_ID && typeof ex?.model === "string" && LANE_MODELS.some((id) => id === ex.model.trim());
55989
- }
55990
- function needsFreeTierNortFixup(cfg) {
55991
- if (!isFreeTierConfig(cfg)) return false;
55992
- const provider = cfg?.models?.providers?.[FREE_TIER_PROVIDER_ID];
55993
- if (!provider) return false;
55994
- if (LANE_MODELS.some((id) => !(provider.models || []).some((m) => m?.id === id))) return true;
55995
- return Object.keys(FIELD_REFS).some((path86) => readPath(cfg, path86) === void 0) || legacyTwoFieldExtract(cfg);
55996
- }
55997
- function readPath(obj, dotPath) {
55998
- return dotPath.split(".").reduce((acc, k) => acc == null ? void 0 : acc[k], obj);
55999
- }
56000
- async function applyFreeTierNortFixup(io) {
56001
- const cfg = io.all();
56002
- if (!needsFreeTierNortFixup(cfg)) return false;
56003
- const provider = cfg.models.providers[FREE_TIER_PROVIDER_ID];
56004
- const registry2 = PROVIDER_DEFS[FREE_TIER_PROVIDER_ID]?.models ?? [];
56005
- const missingEntries = LANE_MODELS.filter((id) => !(provider.models || []).some((m) => m?.id === id)).map((id) => registry2.find((m) => m.id === id));
56006
- if (missingEntries.some((entry) => !entry)) return false;
56007
- const writes = [];
56008
- if (missingEntries.length) {
56009
- const newModels = [...provider.models || [], ...missingEntries.map((entry) => ({ ...entry }))];
56010
- writes.push([`models.providers.${FREE_TIER_PROVIDER_ID}.models`, newModels]);
56011
- const pCopy = cfg.providers?.[FREE_TIER_PROVIDER_ID];
56012
- if (pCopy && pCopy !== provider) pCopy.models = newModels;
56013
- }
56014
- for (const [path86, ref] of Object.entries(FIELD_REFS)) {
56015
- if (readPath(cfg, path86) === void 0) writes.push([path86, ref]);
56016
- }
56017
- const migratedLegacyExtract = legacyTwoFieldExtract(cfg);
56018
- if (migratedLegacyExtract) {
56019
- writes.push(["topics.extract.model", FREE_TIER_NORT_REF]);
56020
- writes.push(["topics.extract.provider", void 0]);
56021
- }
56022
- if (!writes.length) return false;
56023
- let persisted = true;
56024
- for (const [path86, value] of writes) {
56025
- if (await io.set(path86, value) === false) persisted = false;
56026
- }
56027
- if (!persisted) {
56028
- 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");
56029
- return true;
56030
- }
56031
- 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`);
56032
- return true;
56033
- }
56034
-
56035
56336
  // src/engine-startup.ts
56337
+ init_free_tier_nort_fixup();
56036
56338
  init_mem7_services_fixup();
56037
56339
 
56038
56340
  // src/startup/extract-cooldown-fixup.ts
@@ -62114,7 +62416,7 @@ var VoiceChatPlugin = class {
62114
62416
 
62115
62417
  // src/memory/everos/plugin.ts
62116
62418
  import { spawn as spawn4 } from "node:child_process";
62117
- import net from "node:net";
62419
+ import net2 from "node:net";
62118
62420
  import path46 from "node:path";
62119
62421
  import fs48 from "node:fs";
62120
62422
 
@@ -62554,7 +62856,7 @@ var EverosPlugin = class {
62554
62856
  }
62555
62857
  async isPortAlive(port) {
62556
62858
  return new Promise((resolve26) => {
62557
- const socket = new net.Socket();
62859
+ const socket = new net2.Socket();
62558
62860
  socket.setTimeout(2e3);
62559
62861
  socket.on("connect", () => {
62560
62862
  socket.destroy();
@@ -68095,7 +68397,7 @@ import { promisify as promisify4 } from "node:util";
68095
68397
  import * as fs54 from "node:fs";
68096
68398
  import * as path55 from "node:path";
68097
68399
  import * as os6 from "node:os";
68098
- import net3 from "net";
68400
+ import net4 from "net";
68099
68401
  var execFileAsync2 = promisify4(execFile5);
68100
68402
  var VOICE_DIR = path55.join(os6.tmpdir(), "engine-voice");
68101
68403
  function wavDurationSec(buf) {
@@ -68271,7 +68573,7 @@ async function ttsCosyvoiceWorker(text, cfg, onChunk) {
68271
68573
  }
68272
68574
  }
68273
68575
  return new Promise((resolve26, reject) => {
68274
- const sock = net3.connect(getSockPath());
68576
+ const sock = net4.connect(getSockPath());
68275
68577
  let buf = "";
68276
68578
  const finish = (err) => {
68277
68579
  try {
@@ -68607,8 +68909,8 @@ var DeskBuddyAdapter = class {
68607
68909
  startAsr() {
68608
68910
  if (this.asrSock) return;
68609
68911
  const port = this.asrBackend === "sensevoice" ? 9790 : 9791;
68610
- const net4 = __require("node:net");
68611
- const sock = net4.connect(port, "127.0.0.1");
68912
+ const net5 = __require("node:net");
68913
+ const sock = net5.connect(port, "127.0.0.1");
68612
68914
  sock.setNoDelay(true);
68613
68915
  this.asrSock = sock;
68614
68916
  this.asrBuf = "";
@@ -82589,8 +82891,10 @@ async function startEngine(config, opts) {
82589
82891
  };
82590
82892
  reloadOrchestrator.register({
82591
82893
  name: "channels",
82592
- // channels 段常开(空段 = 全拆,reconcile 自然处理)
82593
- select: (cfg) => ({ enabled: true, channels: cfg.channels ?? null }),
82894
+ // channels 段常开(空段 = 全拆,reconcile 自然处理)。select 抽出为纯函数——
82895
+ // 它吃的是 resolveEnv **之后**的活树,secrets-only 换 token 也要能触发重建
82896
+ // (1102:这条链没有回归钉害我误诊一轮,见 channels-entry.ts 头注)
82897
+ select: channelsSelectSlice,
82594
82898
  start: () => runChannelsReconcile(),
82595
82899
  // fire-and-forget:defer 重试不阻塞后续 entry
82596
82900
  stop: () => {