bnpanel-fpqd 0.4.1 → 0.6.6

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/index.js CHANGED
@@ -9,7 +9,10 @@ var __export = (target, all) => {
9
9
  import path15 from "node:path";
10
10
 
11
11
  // packages/panel/src/host/app.js
12
- import crypto7 from "node:crypto";
12
+ import { spawn as spawn2 } from "node:child_process";
13
+ import { once } from "node:events";
14
+ import { finished } from "node:stream/promises";
15
+ import crypto8 from "node:crypto";
13
16
  import fs14 from "node:fs";
14
17
  import path14 from "node:path";
15
18
  import { fileURLToPath as fileURLToPath2 } from "node:url";
@@ -7121,6 +7124,8 @@ var EntitlementsSchema = external_exports.object({
7121
7124
  expiresAt: external_exports.string(),
7122
7125
  graceUntil: external_exports.string(),
7123
7126
  issuedAt: external_exports.string(),
7127
+ /** 代理归属码,激活许可证时由服务端根据 license.reseller_id 写入,面板据此区分代理。 */
7128
+ resellerCode: external_exports.string().optional(),
7124
7129
  /** Detached ed25519 signature over the other fields; verified offline by the panel. */
7125
7130
  signature: external_exports.string().optional()
7126
7131
  });
@@ -7158,7 +7163,8 @@ var ReleaseSummarySchema = external_exports.object({
7158
7163
  sizeBytes: external_exports.number().int().nonnegative(),
7159
7164
  downloadUrl: external_exports.string().optional(),
7160
7165
  notes: external_exports.string().optional(),
7161
- publishedAt: external_exports.string()
7166
+ publishedAt: external_exports.string(),
7167
+ distribution: external_exports.enum(["npm", "archive"]).optional()
7162
7168
  });
7163
7169
  var ActivateRequestSchema = external_exports.object({
7164
7170
  key: external_exports.string().min(8).max(64),
@@ -7193,7 +7199,9 @@ var DeviceViewSchema = external_exports.object({
7193
7199
  appVersion: external_exports.string(),
7194
7200
  firstSeen: external_exports.string(),
7195
7201
  lastSeen: external_exports.string(),
7196
- status: external_exports.enum(["active", "released", "blocked"])
7202
+ status: external_exports.enum(["active", "released", "blocked"]),
7203
+ runCount: external_exports.number().int().nonnegative().default(0),
7204
+ lastRunAt: external_exports.string().nullable().default(null)
7197
7205
  });
7198
7206
 
7199
7207
  // packages/panel-core/src/verify.ts
@@ -7305,7 +7313,7 @@ function listInstalled(paths) {
7305
7313
  function listVersions(paths, id) {
7306
7314
  const base = path3.join(paths.agents, id);
7307
7315
  if (!fs3.existsSync(base)) return [];
7308
- return fs3.readdirSync(base).filter((name2) => fs3.statSync(path3.join(base, name2)).isDirectory()).map((version) => {
7316
+ return fs3.readdirSync(base).filter((name2) => !name2.startsWith(".") && fs3.statSync(path3.join(base, name2)).isDirectory()).map((version) => {
7309
7317
  const dir = path3.join(base, version);
7310
7318
  return { version, dir, mtime: fs3.statSync(dir).mtimeMs };
7311
7319
  }).sort((a, b2) => b2.mtime - a.mtime);
@@ -7315,7 +7323,51 @@ function listVersions(paths, id) {
7315
7323
  import fs4 from "node:fs";
7316
7324
  import os3 from "node:os";
7317
7325
  import path4 from "node:path";
7326
+
7327
+ // packages/panel-core/src/npm-dist.ts
7328
+ import crypto2 from "node:crypto";
7329
+ var AGENT_NPM_PACKAGES = {
7330
+ biureel: "@biunow/agent-biureel",
7331
+ biutalk: "@biunow/agent-biutalk",
7332
+ biuremtion: "@biunow/agent-biuremtion",
7333
+ biuvibe: "@biunow/agent-biuvibe",
7334
+ biuart: "@biunow/agent-biuart"
7335
+ };
7336
+ function agentNpmPackage(slug) {
7337
+ const key = String(slug || "").trim();
7338
+ return AGENT_NPM_PACKAGES[key] ?? null;
7339
+ }
7340
+ function registryPackageUrl(registry, name2, version) {
7341
+ const base = String(registry || "").replace(/\/$/, "");
7342
+ const scoped = name2.startsWith("@") ? name2.replace("/", "%2f") : name2;
7343
+ return version ? `${base}/${scoped}/${version}` : `${base}/${scoped}`;
7344
+ }
7345
+ function mirrorTarball(registry, tarball) {
7346
+ const base = String(registry || "").replace(/\/$/, "");
7347
+ return String(tarball || "").replace(/^https:\/\/registry\.npmjs\.org/i, base);
7348
+ }
7349
+ function verifyNpmIntegrity(buf, integrity) {
7350
+ const raw = String(integrity || "").trim();
7351
+ if (!raw) return true;
7352
+ const token = raw.split(/\s+/).find((part) => part.startsWith("sha512-"));
7353
+ const match = token ? /^sha512-([A-Za-z0-9+/]+={0,2})$/.exec(token) : null;
7354
+ if (!match) return true;
7355
+ const expected = Buffer.from(match[1], "base64");
7356
+ const actual = crypto2.createHash("sha512").update(buf).digest();
7357
+ return expected.length === actual.length && crypto2.timingSafeEqual(expected, actual);
7358
+ }
7359
+
7360
+ // packages/panel-core/src/installer.ts
7318
7361
  var SKIP = /* @__PURE__ */ new Set([".git", "node_modules", ".DS_Store"]);
7362
+ function entryFileOf(dir, manifest) {
7363
+ const host = String(manifest.entry?.host || "").trim();
7364
+ const entry = path4.resolve(dir, host);
7365
+ const rel = path4.relative(dir, entry);
7366
+ if (!host || !rel || rel.startsWith("..") || path4.isAbsolute(rel)) {
7367
+ throw new Error(`manifest.json \u7684\u5165\u53E3\u4E0D\u5408\u6CD5\uFF1A${host || "(\u7A7A)"}`);
7368
+ }
7369
+ return entry;
7370
+ }
7319
7371
  async function installAgent(opts) {
7320
7372
  const { paths, publicKeys, source } = opts;
7321
7373
  const now = opts.now ?? (() => /* @__PURE__ */ new Date());
@@ -7343,16 +7395,39 @@ async function installAgent(opts) {
7343
7395
  }
7344
7396
  }
7345
7397
  const dest = agentDir(paths, manifest.id, manifest.version);
7346
- fs4.rmSync(dest, { recursive: true, force: true });
7347
- fs4.mkdirSync(dest, { recursive: true });
7348
- fs4.cpSync(staging, dest, {
7349
- recursive: true,
7350
- filter: (src) => !SKIP.has(path4.basename(src))
7351
- });
7352
- fs4.writeFileSync(path4.join(dest, "manifest.json"), JSON.stringify(manifest, null, 2));
7353
- if (!verifyContentDigest(dest, manifest.integrity.sha256)) {
7354
- fs4.rmSync(dest, { recursive: true, force: true });
7355
- throw new Error("package content does not match the signed digest");
7398
+ const incoming = path4.join(path4.dirname(dest), `.installing-${process.pid}-${Date.now()}`);
7399
+ fs4.mkdirSync(path4.dirname(dest), { recursive: true });
7400
+ for (const name2 of fs4.readdirSync(path4.dirname(dest))) {
7401
+ if (!name2.startsWith(".old-")) continue;
7402
+ try {
7403
+ fs4.rmSync(path4.join(path4.dirname(dest), name2), { recursive: true, force: true });
7404
+ } catch {
7405
+ }
7406
+ }
7407
+ try {
7408
+ fs4.rmSync(incoming, { recursive: true, force: true });
7409
+ fs4.cpSync(staging, incoming, {
7410
+ recursive: true,
7411
+ filter: (src) => !SKIP.has(path4.basename(src))
7412
+ });
7413
+ fs4.writeFileSync(path4.join(incoming, "manifest.json"), JSON.stringify(manifest, null, 2));
7414
+ if (!verifyContentDigest(incoming, manifest.integrity.sha256)) {
7415
+ throw new Error("package content does not match the signed digest");
7416
+ }
7417
+ if (!fs4.existsSync(entryFileOf(incoming, manifest))) {
7418
+ throw new Error(`package is missing entry file "${manifest.entry?.host}"`);
7419
+ }
7420
+ if (fs4.existsSync(dest)) {
7421
+ const trash = path4.join(path4.dirname(dest), `.old-${process.pid}-${Date.now()}`);
7422
+ fs4.renameSync(dest, trash);
7423
+ try {
7424
+ fs4.rmSync(trash, { recursive: true, force: true });
7425
+ } catch {
7426
+ }
7427
+ }
7428
+ fs4.renameSync(incoming, dest);
7429
+ } finally {
7430
+ fs4.rmSync(incoming, { recursive: true, force: true });
7356
7431
  }
7357
7432
  const current = readCurrent(paths, manifest.id);
7358
7433
  writeCurrent(paths, manifest.id, {
@@ -7416,61 +7491,105 @@ async function installFromUrl(opts) {
7416
7491
  fs4.writeFileSync(file, buf);
7417
7492
  return installAgent({ paths: opts.paths, publicKeys: opts.publicKeys, source: { kind: "tgz", file }, expectedSha256: actual });
7418
7493
  }
7494
+ async function installFromNpmRegistry(opts) {
7495
+ const version = String(opts.version || "").trim();
7496
+ if (!version) throw new Error(`\u7F3A\u5C11 ${opts.name} \u7684\u7248\u672C\u53F7`);
7497
+ const metaUrl = registryPackageUrl(opts.registry, opts.name, version);
7498
+ const metaRes = await fetch(metaUrl, { headers: { accept: "application/json" } });
7499
+ if (metaRes.status === 404) {
7500
+ throw Object.assign(new Error("\u5B89\u88C5\u5305\u8FD8\u5728\u540C\u6B65\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5"), { code: "PACKAGE_SYNCING" });
7501
+ }
7502
+ if (!metaRes.ok) {
7503
+ throw new Error("\u5B89\u88C5\u5305\u6682\u65F6\u4E0B\u8F7D\u4E0D\u4E86\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
7504
+ }
7505
+ const meta = await metaRes.json();
7506
+ const tarball = mirrorTarball(opts.registry, meta.dist?.tarball || "");
7507
+ if (!tarball) throw new Error("\u5B89\u88C5\u5305\u6682\u65F6\u4E0B\u8F7D\u4E0D\u4E86\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
7508
+ const res = await fetch(tarball, { redirect: "follow" });
7509
+ if (!res.ok) throw new Error("\u5B89\u88C5\u5305\u6682\u65F6\u4E0B\u8F7D\u4E0D\u4E86\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
7510
+ const buf = Buffer.from(await res.arrayBuffer());
7511
+ if (!verifyNpmIntegrity(buf, meta.dist?.integrity)) {
7512
+ throw new Error("\u5B89\u88C5\u5305\u65E0\u6CD5\u9A8C\u8BC1\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
7513
+ }
7514
+ fs4.mkdirSync(opts.paths.downloads, { recursive: true });
7515
+ const file = path4.join(opts.paths.downloads, `${sha256File(buf)}.tgz`);
7516
+ fs4.writeFileSync(file, buf);
7517
+ return installAgent({ paths: opts.paths, publicKeys: opts.publicKeys, source: { kind: "tgz", file } });
7518
+ }
7419
7519
 
7420
7520
  // packages/panel-core/src/runtime.ts
7421
7521
  import fs5 from "node:fs";
7422
7522
  import path5 from "node:path";
7423
- import crypto2 from "node:crypto";
7523
+ import crypto3 from "node:crypto";
7424
7524
  function parseRuntimeSpec(spec) {
7425
7525
  const [name2, version] = spec.split("@");
7426
7526
  if (!name2) throw new Error(`bad runtime spec "${spec}"`);
7427
7527
  return { name: name2, major: version ? Number.parseInt(version, 10) : 0 };
7428
7528
  }
7529
+ function runtimePlatform() {
7530
+ return `${process.platform}-${process.arch}`;
7531
+ }
7429
7532
  function runtimeDir(paths, spec) {
7430
7533
  return path5.join(paths.runtime, spec.name, String(spec.major));
7431
7534
  }
7432
- function resolveRuntime(paths, spec) {
7535
+ function resolveRuntime(paths, spec, platform = runtimePlatform()) {
7433
7536
  const parsed = parseRuntimeSpec(spec);
7434
7537
  const dir = runtimeDir(paths, parsed);
7435
- return fs5.existsSync(path5.join(dir, "manifest.json")) ? dir : null;
7538
+ const manifestPath = path5.join(dir, "manifest.json");
7539
+ if (!fs5.existsSync(manifestPath)) return null;
7540
+ try {
7541
+ const manifest = JSON.parse(fs5.readFileSync(manifestPath, "utf8"));
7542
+ if (manifest?.platform && manifest.platform !== platform) return null;
7543
+ } catch {
7544
+ }
7545
+ return dir;
7436
7546
  }
7437
- function missingRuntime(paths, specs) {
7438
- return specs.filter((s3) => !resolveRuntime(paths, s3));
7547
+ function missingRuntime(paths, specs, platform = runtimePlatform()) {
7548
+ return specs.filter((s3) => !resolveRuntime(paths, s3, platform));
7439
7549
  }
7440
7550
  async function ensureRuntime(paths, spec, source) {
7441
7551
  const parsed = parseRuntimeSpec(spec);
7442
7552
  const dir = runtimeDir(paths, parsed);
7443
- if (fs5.existsSync(path5.join(dir, "manifest.json"))) return dir;
7553
+ const exist = resolveRuntime(paths, spec);
7554
+ if (exist) return exist;
7444
7555
  const staging = path5.join(paths.runtime, ".staging", `${parsed.name}-${parsed.major}-${Date.now()}`);
7445
- fs5.mkdirSync(staging, { recursive: true });
7446
- const archive = path5.join(staging, "payload");
7447
- if (source.kind === "file") {
7448
- fs5.copyFileSync(source.file, archive);
7449
- } else {
7450
- const res = await fetch(source.url);
7451
- if (!res.ok) throw new Error(`runtime download failed: ${res.status} ${res.statusText}`);
7452
- const buf = Buffer.from(await res.arrayBuffer());
7453
- const actual = crypto2.createHash("sha256").update(buf).digest("hex");
7454
- if (actual !== source.sha256) throw new Error(`runtime checksum mismatch for ${spec}`);
7455
- fs5.writeFileSync(archive, buf);
7456
- }
7457
- const unpacked = path5.join(staging, "unpacked");
7458
- fs5.mkdirSync(unpacked, { recursive: true });
7459
- await So({ file: archive, cwd: unpacked });
7460
- const manifestPath = path5.join(unpacked, "manifest.json");
7461
- if (!fs5.existsSync(manifestPath)) throw new Error(`runtime archive for ${spec} has no manifest.json`);
7462
- const manifest = JSON.parse(fs5.readFileSync(manifestPath, "utf8"));
7463
- for (const entry of manifest.files ?? []) {
7464
- const file = path5.join(unpacked, entry.path);
7465
- if (!fs5.existsSync(file)) throw new Error(`runtime file missing: ${entry.path}`);
7466
- const hash = crypto2.createHash("sha256").update(fs5.readFileSync(file)).digest("hex");
7467
- if (hash !== entry.sha256) throw new Error(`runtime file hash mismatch: ${entry.path}`);
7468
- }
7469
- fs5.rmSync(dir, { recursive: true, force: true });
7470
- fs5.mkdirSync(path5.dirname(dir), { recursive: true });
7471
- fs5.renameSync(unpacked, dir);
7472
- fs5.rmSync(staging, { recursive: true, force: true });
7473
- return dir;
7556
+ try {
7557
+ fs5.mkdirSync(staging, { recursive: true });
7558
+ const archive = path5.join(staging, "payload");
7559
+ if (source.kind === "file") {
7560
+ fs5.copyFileSync(source.file, archive);
7561
+ } else {
7562
+ const res = await fetch(source.url);
7563
+ if (!res.ok) throw new Error(`runtime download failed: ${res.status} ${res.statusText}`);
7564
+ const buf = Buffer.from(await res.arrayBuffer());
7565
+ const actual = crypto3.createHash("sha256").update(buf).digest("hex");
7566
+ if (actual !== source.sha256) throw new Error(`runtime checksum mismatch for ${spec}`);
7567
+ fs5.writeFileSync(archive, buf);
7568
+ }
7569
+ const unpacked = path5.join(staging, "unpacked");
7570
+ fs5.mkdirSync(unpacked, { recursive: true });
7571
+ await So({ file: archive, cwd: unpacked });
7572
+ const manifestPath = path5.join(unpacked, "manifest.json");
7573
+ if (!fs5.existsSync(manifestPath)) throw new Error(`runtime archive for ${spec} has no manifest.json`);
7574
+ const manifest = JSON.parse(fs5.readFileSync(manifestPath, "utf8"));
7575
+ if (manifest.platform && manifest.platform !== runtimePlatform()) {
7576
+ throw new Error(`runtime ${spec} \u662F\u4E3A ${manifest.platform} \u6784\u5EFA\u7684\uFF0C\u5F53\u524D\u8BBE\u5907\u4E3A ${runtimePlatform()}`);
7577
+ }
7578
+ for (const entry of manifest.files ?? []) {
7579
+ const file = path5.join(unpacked, entry.path);
7580
+ if (!fs5.existsSync(file)) throw new Error(`runtime file missing: ${entry.path}`);
7581
+ const hash = crypto3.createHash("sha256").update(fs5.readFileSync(file)).digest("hex");
7582
+ if (hash !== entry.sha256) throw new Error(`runtime file hash mismatch: ${entry.path}`);
7583
+ }
7584
+ fs5.rmSync(dir, { recursive: true, force: true });
7585
+ fs5.mkdirSync(path5.dirname(dir), { recursive: true });
7586
+ fs5.renameSync(unpacked, dir);
7587
+ fs5.rmSync(staging, { recursive: true, force: true });
7588
+ return dir;
7589
+ } catch (err) {
7590
+ fs5.rmSync(staging, { recursive: true, force: true });
7591
+ throw err;
7592
+ }
7474
7593
  }
7475
7594
  async function importRuntimeArchive(paths, file) {
7476
7595
  const os5 = await import("node:os");
@@ -7506,6 +7625,23 @@ function npmModuleRoot(runtimeDirPath, manifest) {
7506
7625
  const fallback = path5.join(runtimeDirPath, "node_modules");
7507
7626
  return fs5.existsSync(fallback) ? fallback : null;
7508
7627
  }
7628
+ function runtimeEnvironment(paths, specs) {
7629
+ const env = {};
7630
+ const pathPrepend = [];
7631
+ for (const spec of specs) {
7632
+ const dir = resolveRuntime(paths, spec);
7633
+ if (!dir) continue;
7634
+ const manifest = readRuntimeManifest(paths, spec);
7635
+ if (!manifest) continue;
7636
+ for (const [key, value] of Object.entries(manifest.env ?? {})) {
7637
+ if (typeof value === "string") env[key] = value.replaceAll("${dir}", dir);
7638
+ }
7639
+ for (const rel of manifest.pathPrepend ?? []) {
7640
+ if (typeof rel === "string" && rel) pathPrepend.push(path5.join(dir, rel));
7641
+ }
7642
+ }
7643
+ return { env, pathPrepend };
7644
+ }
7509
7645
  function linkAgentNpmRuntimes(paths, agentDir2, specs) {
7510
7646
  const engineDir = path5.join(agentDir2, "engine");
7511
7647
  if (!fs5.existsSync(engineDir)) return [];
@@ -7545,7 +7681,7 @@ function ensureDirLink(target, linkPath) {
7545
7681
  }
7546
7682
 
7547
7683
  // packages/panel-core/src/license.ts
7548
- import crypto3 from "node:crypto";
7684
+ import crypto4 from "node:crypto";
7549
7685
  import fs6 from "node:fs";
7550
7686
  import os4 from "node:os";
7551
7687
  import path6 from "node:path";
@@ -7665,6 +7801,37 @@ var LicenseClient = class {
7665
7801
  if (body.state === "revoked") return { state: "revoked", notices: (body.notices ?? []).map((n) => n.body), product: cache.product };
7666
7802
  return { state: body.state, notices: (body.notices ?? []).map((n) => n.body), product: cache.product };
7667
7803
  }
7804
+ /** 在线能力(如诊断)用:令牌临近过期先续期,避免用了 24 小时后突然失效。 */
7805
+ async ensureToken(product) {
7806
+ const cache = this.readCache(product);
7807
+ if (!cache) return null;
7808
+ const expires = cache.tokenExpiresAt ? Date.parse(cache.tokenExpiresAt) : 0;
7809
+ if (expires && expires - Date.now() > 5 * 6e4) return cache.token;
7810
+ return await this.refreshToken(product) ?? cache.token;
7811
+ }
7812
+ async refreshToken(product) {
7813
+ const cache = this.readCache(product);
7814
+ if (!cache) return null;
7815
+ try {
7816
+ const res = await fetch(`${this.cfg.baseUrl}/v1/refresh`, {
7817
+ method: "POST",
7818
+ headers: { "content-type": "application/json", authorization: `Bearer ${cache.token}` },
7819
+ body: JSON.stringify({ device: this.device(), token: cache.token })
7820
+ });
7821
+ const body = await res.json();
7822
+ if (!res.ok || !body?.token) return null;
7823
+ const store = this.readStore();
7824
+ store.products[cache.product] = {
7825
+ ...cache,
7826
+ token: String(body.token),
7827
+ tokenExpiresAt: String(body.expiresAt ?? cache.tokenExpiresAt)
7828
+ };
7829
+ this.writeStore(store);
7830
+ return String(body.token);
7831
+ } catch {
7832
+ return null;
7833
+ }
7834
+ }
7668
7835
  statusFor(product) {
7669
7836
  const cache = this.readCache(product);
7670
7837
  if (!cache) {
@@ -7711,6 +7878,11 @@ var LicenseClient = class {
7711
7878
  canUseProduct(product) {
7712
7879
  return this.statusFor(product).canExport;
7713
7880
  }
7881
+ /** 从已缓存的签名 entitlements 中取代理归属码;未激活或官方直售时返回 null。 */
7882
+ resellerCode(product) {
7883
+ const cache = this.readCache(product);
7884
+ return cache?.entitlements?.resellerCode ?? null;
7885
+ }
7714
7886
  tokenFor(product) {
7715
7887
  return this.readCache(product)?.token ?? null;
7716
7888
  }
@@ -7742,9 +7914,9 @@ var LicenseClient = class {
7742
7914
  function deviceFingerprint(root) {
7743
7915
  fs6.mkdirSync(root, { recursive: true });
7744
7916
  const idFile = path6.join(root, "device-id");
7745
- if (!fs6.existsSync(idFile)) fs6.writeFileSync(idFile, crypto3.randomBytes(16).toString("hex"), { mode: 384 });
7917
+ if (!fs6.existsSync(idFile)) fs6.writeFileSync(idFile, crypto4.randomBytes(16).toString("hex"), { mode: 384 });
7746
7918
  const installId = fs6.readFileSync(idFile, "utf8").trim();
7747
- return crypto3.createHash("sha256").update(`${installId}:${os4.hostname()}:${process.platform}`).digest("hex");
7919
+ return crypto4.createHash("sha256").update(`${installId}:${os4.hostname()}:${process.platform}`).digest("hex");
7748
7920
  }
7749
7921
 
7750
7922
  // packages/panel-core/src/supervisor.ts
@@ -7752,6 +7924,16 @@ import fs7 from "node:fs";
7752
7924
  import net from "node:net";
7753
7925
  import path7 from "node:path";
7754
7926
  import { spawn } from "node:child_process";
7927
+ function resolveNodeRuntime(env = process.env) {
7928
+ const explicit = env.PANEL_NODE_BIN || env.NODE_BIN;
7929
+ if (explicit) return { command: explicit, env: {} };
7930
+ const npmNode = env.npm_node_execpath;
7931
+ if (npmNode && fs7.existsSync(npmNode)) return { command: npmNode, env: {} };
7932
+ if (process.versions.electron) {
7933
+ return { command: process.execPath, env: { ELECTRON_RUN_AS_NODE: "1" } };
7934
+ }
7935
+ return { command: process.execPath, env: {} };
7936
+ }
7755
7937
  var Supervisor = class {
7756
7938
  constructor(paths, spawnImpl = spawn) {
7757
7939
  this.paths = paths;
@@ -7770,8 +7952,24 @@ var Supervisor = class {
7770
7952
  if (this.running.has(agent.id)) return this.list().find((r) => r.id === agent.id);
7771
7953
  const port = await freePort();
7772
7954
  const entry = path7.resolve(agent.dir, agent.manifest.entry.host);
7773
- const workspace = path7.join(this.paths.workspaces, agent.id);
7774
- fs7.mkdirSync(workspace, { recursive: true });
7955
+ if (!fs7.existsSync(entry)) {
7956
+ throw new Error(
7957
+ `Agent \u5B89\u88C5\u6587\u4EF6\u4E0D\u5B8C\u6574\uFF1A\u7F3A\u5C11 ${entry}\u3002\u8BF7\u5728\u9762\u677F\u4E2D\u91CD\u65B0\u5B89\u88C5\u300C${agent.manifest.name || agent.id}\u300D\u3002`
7958
+ );
7959
+ }
7960
+ const workspaceRoot = opts.workspaceRoot ? path7.isAbsolute(opts.workspaceRoot) ? opts.workspaceRoot : path7.resolve(opts.workspaceRoot) : this.paths.workspaces;
7961
+ const workspace = path7.join(workspaceRoot, agent.id);
7962
+ try {
7963
+ fs7.mkdirSync(workspace, { recursive: true });
7964
+ const probe = path7.join(workspace, `.write-probe-${process.pid}`);
7965
+ fs7.writeFileSync(probe, "");
7966
+ fs7.rmSync(probe, { force: true });
7967
+ } catch (err) {
7968
+ const e = err;
7969
+ throw new Error(
7970
+ `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u53EF\u7528\uFF1A${workspace}\uFF08${e.code ?? "ERROR"}: ${e.message}\uFF09\u3002\u8BF7\u5728\u8BBE\u7F6E\u91CC\u6362\u6210\u672C\u673A\u53EF\u5199\u7684\u76EE\u5F55\u540E\u91CD\u8BD5\u3002`
7971
+ );
7972
+ }
7775
7973
  const env = {
7776
7974
  ...process.env,
7777
7975
  PANEL_PORT: String(port),
@@ -7788,15 +7986,47 @@ var Supervisor = class {
7788
7986
  ...opts.panelCallbackToken ? { PANEL_CALLBACK_TOKEN: opts.panelCallbackToken } : {},
7789
7987
  ...opts.extraEnv ?? {}
7790
7988
  };
7791
- const child = this.spawnImpl(process.execPath, [entry], { cwd: agent.dir, env });
7989
+ const node = resolveNodeRuntime();
7990
+ const child = this.spawnImpl(node.command, [entry], { cwd: agent.dir, env: { ...env, ...node.env } });
7792
7991
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
7793
7992
  const record = { id: agent.id, pid: child.pid ?? -1, port, url: `http://127.0.0.1:${port}`, startedAt, child, restarts: 0 };
7794
7993
  this.running.set(agent.id, record);
7994
+ let tail = "";
7995
+ let spawnError = null;
7996
+ const capture = (chunk) => {
7997
+ tail = (tail + chunk.toString()).slice(-1200);
7998
+ };
7999
+ child.stdout?.on("data", capture);
8000
+ child.stderr?.on("data", capture);
8001
+ child.once("error", (err) => {
8002
+ spawnError = err;
8003
+ });
7795
8004
  child.once("exit", () => {
7796
8005
  const current = this.running.get(agent.id);
7797
8006
  if (current?.child === child) this.running.delete(agent.id);
7798
8007
  });
7799
- await waitForPort(port, opts.timeoutMs ?? 2e4);
8008
+ const exitWatcher = new Promise((_2, reject) => {
8009
+ child.once("error", (err) => reject(new Error(`Agent \u8FDB\u7A0B\u542F\u52A8\u5931\u8D25\uFF1A${err.message}`)));
8010
+ child.once("exit", (code) => reject(new Error(`Agent \u8FDB\u7A0B\u542F\u52A8\u540E\u7ACB\u5373\u9000\u51FA\uFF08exitCode=${code}\uFF09`)));
8011
+ });
8012
+ exitWatcher.catch(() => {
8013
+ });
8014
+ try {
8015
+ const waiter = waitForPort(port, opts.timeoutMs ?? 2e4);
8016
+ waiter.catch(() => {
8017
+ });
8018
+ await Promise.race([waiter, exitWatcher]);
8019
+ } catch (err) {
8020
+ this.running.delete(agent.id);
8021
+ if (!child.killed) child.kill("SIGKILL");
8022
+ const lines = [`${err.message}`];
8023
+ if (spawnError) lines.push(`\u542F\u52A8\u5931\u8D25\uFF1A${spawnError.message}`);
8024
+ else if (child.exitCode !== null) lines.push(`Agent \u8FDB\u7A0B\u5DF2\u9000\u51FA\uFF0CexitCode=${child.exitCode}`);
8025
+ lines.push(`workspace=${workspace}`, `command=${node.command}`);
8026
+ if (tail.trim()) lines.push(`--- agent output ---
8027
+ ${tail.trim()}`);
8028
+ throw new Error(lines.join("\n"));
8029
+ }
7800
8030
  return this.list().find((r) => r.id === agent.id);
7801
8031
  }
7802
8032
  async stop(id) {
@@ -7848,7 +8078,7 @@ async function waitForPort(port, timeoutMs) {
7848
8078
  }
7849
8079
 
7850
8080
  // packages/panel-core/src/tasks.ts
7851
- import crypto4 from "node:crypto";
8081
+ import crypto5 from "node:crypto";
7852
8082
  var TaskQueue = class {
7853
8083
  constructor(concurrency = 2) {
7854
8084
  this.concurrency = concurrency;
@@ -7857,7 +8087,7 @@ var TaskQueue = class {
7857
8087
  tasks = /* @__PURE__ */ new Map();
7858
8088
  active = 0;
7859
8089
  submit(input) {
7860
- const id = crypto4.randomUUID();
8090
+ const id = crypto5.randomUUID();
7861
8091
  const task = {
7862
8092
  id,
7863
8093
  agentId: input.agentId,
@@ -7949,12 +8179,14 @@ var DEFAULT_SETTINGS = {
7949
8179
  maxAgents: 8,
7950
8180
  autoUpdate: true,
7951
8181
  autoInstallUpdates: false,
7952
- telemetry: false,
8182
+ /** Kept for old settings files. The panel always reports installs; users cannot turn this off. */
8183
+ telemetry: true,
7953
8184
  mirror: null,
7954
8185
  engineRoots: {},
7955
8186
  permissionsAck: {},
7956
8187
  autoKickoffInDsh: true,
7957
- panelNpmRegistry: "https://registry.npmmirror.com"
8188
+ panelNpmRegistry: "https://registry.npmmirror.com",
8189
+ workspaceRoot: null
7958
8190
  };
7959
8191
  function readSettings(paths) {
7960
8192
  if (!fs8.existsSync(paths.settings)) return { ...DEFAULT_SETTINGS };
@@ -7972,7 +8204,7 @@ function writeSettings(paths, patch) {
7972
8204
  }
7973
8205
 
7974
8206
  // packages/panel-core/src/run-permit.ts
7975
- import crypto5 from "node:crypto";
8207
+ import crypto6 from "node:crypto";
7976
8208
  import fs9 from "node:fs";
7977
8209
  import path9 from "node:path";
7978
8210
  var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -7985,7 +8217,7 @@ function loadOrCreatePermitSecret(paths) {
7985
8217
  if (fs9.existsSync(file)) {
7986
8218
  return fs9.readFileSync(file);
7987
8219
  }
7988
- const secret = crypto5.randomBytes(32);
8220
+ const secret = crypto6.randomBytes(32);
7989
8221
  fs9.writeFileSync(file, secret);
7990
8222
  try {
7991
8223
  fs9.chmodSync(file, 384);
@@ -8006,7 +8238,7 @@ function canonical(payload) {
8006
8238
  }
8007
8239
  function signRunPermit(payload, secret) {
8008
8240
  const body = canonical(payload);
8009
- const signature = crypto5.createHmac("sha256", secret).update(body).digest("base64url");
8241
+ const signature = crypto6.createHmac("sha256", secret).update(body).digest("base64url");
8010
8242
  return { ...JSON.parse(body), signature };
8011
8243
  }
8012
8244
  function verifyRunPermit(permit, secret, opts = {}) {
@@ -8038,11 +8270,11 @@ function verifyRunPermit(permit, secret, opts = {}) {
8038
8270
  if (opts.expectProjectPath && path9.resolve(opts.expectProjectPath) !== payload.projectPath) {
8039
8271
  return { ok: false, reason: "project-mismatch" };
8040
8272
  }
8041
- const expected = crypto5.createHmac("sha256", secret).update(canonical(payload)).digest("base64url");
8273
+ const expected = crypto6.createHmac("sha256", secret).update(canonical(payload)).digest("base64url");
8042
8274
  const given = String(permit.signature);
8043
8275
  const a = Buffer.from(expected);
8044
8276
  const b2 = Buffer.from(given);
8045
- if (a.length !== b2.length || !crypto5.timingSafeEqual(a, b2)) {
8277
+ if (a.length !== b2.length || !crypto6.timingSafeEqual(a, b2)) {
8046
8278
  return { ok: false, reason: "bad-signature" };
8047
8279
  }
8048
8280
  return { ok: true, permit: { ...payload, signature: given } };
@@ -8058,7 +8290,7 @@ function mintRunPermit(paths, input) {
8058
8290
  jobId: input.jobId,
8059
8291
  iat: now,
8060
8292
  exp: now + (input.ttlMs ?? DEFAULT_TTL_MS),
8061
- nonce: crypto5.randomBytes(12).toString("hex")
8293
+ nonce: crypto6.randomBytes(12).toString("hex")
8062
8294
  },
8063
8295
  secret
8064
8296
  );
@@ -8265,7 +8497,7 @@ ${wrapSkillContent(
8265
8497
  }
8266
8498
 
8267
8499
  // packages/panel/src/host/dsh-chat.js
8268
- import crypto6 from "node:crypto";
8500
+ import crypto7 from "node:crypto";
8269
8501
  import fs11 from "node:fs";
8270
8502
  import path11 from "node:path";
8271
8503
  function extractKickoffPrompt(kickoffPathOrText) {
@@ -8296,16 +8528,13 @@ function createChatBridge() {
8296
8528
  recent.unshift(entry);
8297
8529
  if (recent.length > 30) recent.length = 30;
8298
8530
  }
8299
- async function startSkillRun(opts) {
8300
- const skill = String(opts.skill || "").trim();
8531
+ async function openSession(opts) {
8301
8532
  const projectPath = path11.resolve(String(opts.projectPath || ""));
8302
8533
  const promptText = String(opts.promptText || "").trim();
8303
- const agentId = opts.agentId || skill;
8304
- if (!skill) return { ok: false, reason: "missing-skill" };
8534
+ const agentId = opts.agentId || "panel";
8535
+ const skill = opts.skill || "prompt";
8305
8536
  if (!promptText) return { ok: false, reason: "missing-prompt" };
8306
- if (!projectPath || !fs11.existsSync(projectPath)) {
8307
- return { ok: false, reason: "missing-project", error: `project path not found: ${projectPath}` };
8308
- }
8537
+ if (!projectPath) return { ok: false, reason: "missing-project", error: "project path is empty" };
8309
8538
  if (!available()) {
8310
8539
  const entry = {
8311
8540
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -8316,7 +8545,7 @@ function createChatBridge() {
8316
8545
  error: "sessionController unavailable (not running inside DSH)",
8317
8546
  projectPath
8318
8547
  };
8319
- remember(entry);
8548
+ if (opts.rememberRun !== false) remember(entry);
8320
8549
  return { ok: false, reason: "chat-unavailable", ...entry };
8321
8550
  }
8322
8551
  try {
@@ -8330,7 +8559,10 @@ function createChatBridge() {
8330
8559
  } catch {
8331
8560
  }
8332
8561
  }
8333
- const requestId = crypto6.randomUUID();
8562
+ if (typeof opts.beforePrompt === "function") {
8563
+ await opts.beforePrompt(sessionId);
8564
+ }
8565
+ const requestId = crypto7.randomUUID();
8334
8566
  await sessionController.prompt(
8335
8567
  {
8336
8568
  sessionId,
@@ -8348,8 +8580,8 @@ function createChatBridge() {
8348
8580
  ok: true,
8349
8581
  projectPath
8350
8582
  };
8351
- remember(entry);
8352
- return { ok: true, sessionId, skill, projectPath };
8583
+ if (opts.rememberRun !== false) remember(entry);
8584
+ return { ok: true, sessionId, projectPath };
8353
8585
  } catch (err) {
8354
8586
  const entry = {
8355
8587
  at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -8360,14 +8592,28 @@ function createChatBridge() {
8360
8592
  error: err?.message || String(err),
8361
8593
  projectPath
8362
8594
  };
8363
- remember(entry);
8595
+ if (opts.rememberRun !== false) remember(entry);
8364
8596
  return { ok: false, reason: "kickoff-failed", error: entry.error, projectPath };
8365
8597
  }
8366
8598
  }
8599
+ async function startSkillRun(opts) {
8600
+ const skill = String(opts.skill || "").trim();
8601
+ if (!skill) return { ok: false, reason: "missing-skill" };
8602
+ const projectPath = path11.resolve(String(opts.projectPath || ""));
8603
+ if (!projectPath || !fs11.existsSync(projectPath)) {
8604
+ return { ok: false, reason: "missing-project", error: `project path not found: ${projectPath}` };
8605
+ }
8606
+ const result = await openSession({ ...opts, agentId: opts.agentId || skill, skill });
8607
+ return result.ok ? { ...result, skill } : result;
8608
+ }
8609
+ async function startPromptRun(opts) {
8610
+ return openSession({ ...opts, rememberRun: false });
8611
+ }
8367
8612
  return {
8368
8613
  setSessionController,
8369
8614
  available,
8370
8615
  startSkillRun,
8616
+ startPromptRun,
8371
8617
  listRecent,
8372
8618
  extractKickoffPrompt
8373
8619
  };
@@ -8381,13 +8627,17 @@ function chatDenialCopy(name2, kind) {
8381
8627
  if (kind === "trial") {
8382
8628
  return `\u300C${who}\u300D\u514D\u8D39\u4F53\u9A8C\u6B21\u6570\u5DF2\u7528\u5B8C\uFF0C\u8FD9\u4E2A\u5BF9\u8BDD\u4E0D\u80FD\u518D\u5F00\u65B0\u4EFB\u52A1\u3002\u8BF7\u5230\u9762\u677F\u300C\u6211\u7684\u6388\u6743\u300D\u6FC0\u6D3B\u540E\u518D\u4ECE Studio \u7ACB\u9879\u3002`;
8383
8629
  }
8630
+ if (kind === "session") {
8631
+ return `\u300C${who}\u300D\u8FD9\u6B21\u4F53\u9A8C\u5DF2\u7ECF\u5728\u8FD9\u4E2A\u5BF9\u8BDD\u91CC\u7528\u8FC7\u4E86\u3002\u8BF7\u56DE\u5230 Studio \u518D\u7ACB\u9879\u4E00\u6B21\uFF0C\u4E0D\u8981\u5728\u8FD9\u4E2A\u5BF9\u8BDD\u91CC\u5F00\u65B0\u4EFB\u52A1\u3002`;
8632
+ }
8384
8633
  return `\u300C${who}\u300D\u5F53\u524D\u672A\u6FC0\u6D3B\uFF0C\u8FD9\u4E2A\u5BF9\u8BDD\u4E0D\u80FD\u518D\u5F00\u65B0\u4EFB\u52A1\u3002\u8BF7\u5230\u9762\u677F\u300C\u6211\u7684\u6388\u6743\u300D\u91CD\u65B0\u6FC0\u6D3B\u540E\u518D\u4ECE Studio \u7ACB\u9879\u3002`;
8385
8634
  }
8386
8635
  function classifyChatTurn(input) {
8387
8636
  if (input.licensed) return { action: "allow", remember: true };
8637
+ if (input.trialRun && !input.seen) return { action: "allow", remember: true };
8388
8638
  const remaining = Number(input.trialRemaining) || 0;
8389
8639
  if (remaining > 0 && !input.seen) return { action: "allow", remember: true };
8390
- if (remaining > 0) return { action: "block", kind: "unlicensed" };
8640
+ if (remaining > 0) return { action: "block", kind: "session" };
8391
8641
  if (input.trialGranted) return { action: "block", kind: "trial" };
8392
8642
  return { action: "block", kind: "unlicensed" };
8393
8643
  }
@@ -8402,18 +8652,34 @@ function cwdOf(agent) {
8402
8652
  function isSubagent(agent) {
8403
8653
  return agent?.session?.header?.origin === "subagent";
8404
8654
  }
8405
- function hasNewUserInput(messages) {
8406
- if (!Array.isArray(messages) || !messages.length) return false;
8407
- return messages.some((message) => {
8408
- const content = message?.content;
8409
- if (typeof content === "string") return content.trim().length > 0;
8410
- if (!Array.isArray(content)) return false;
8411
- return content.some((block) => {
8412
- if (!block || typeof block !== "object") return false;
8413
- if (block.type === "text") return String(block.text || "").trim().length > 0;
8414
- return block.type === "image" || block.type === "file" || block.type === "attachment";
8415
- });
8416
- });
8655
+ function isUserMessage(message) {
8656
+ const role = message?.role || message?.type;
8657
+ if (role === "assistant" || role === "tool" || role === "system" || role === "developer") return false;
8658
+ const kind = message?.source?.kind;
8659
+ if (kind && kind !== "user") return false;
8660
+ return true;
8661
+ }
8662
+ function textOf(message) {
8663
+ const content = message?.content;
8664
+ if (typeof content === "string") return content.trim();
8665
+ if (!Array.isArray(content)) return "";
8666
+ return content.map((block) => {
8667
+ if (!block || typeof block !== "object") return "";
8668
+ if (block.type === "text") return String(block.text || "").trim();
8669
+ if (block.type === "image" || block.type === "file" || block.type === "attachment") return block.type;
8670
+ return "";
8671
+ }).filter(Boolean).join("\n").trim();
8672
+ }
8673
+ function userTurnKey(messages) {
8674
+ if (!Array.isArray(messages) || !messages.length) return "";
8675
+ const parts = [];
8676
+ for (const message of messages) {
8677
+ if (!isUserMessage(message)) continue;
8678
+ const text = textOf(message);
8679
+ if (!text) continue;
8680
+ parts.push(message.id ? `${message.id}:${text.slice(0, 160)}` : text.slice(0, 160));
8681
+ }
8682
+ return parts.join("\n");
8417
8683
  }
8418
8684
  function annotate(messages, sentence) {
8419
8685
  const note = [
@@ -8434,38 +8700,56 @@ function annotate(messages, sentence) {
8434
8700
  });
8435
8701
  return copy;
8436
8702
  }
8437
- function readIds(file) {
8703
+ function readState(file) {
8438
8704
  try {
8439
8705
  const data = JSON.parse(fs12.readFileSync(file, "utf8"));
8440
- const ids = Array.isArray(data?.ids) ? data.ids : [];
8441
- return ids.map((id) => String(id)).filter(Boolean);
8706
+ const ids = Array.isArray(data?.ids) ? data.ids.map((id) => String(id)).filter(Boolean) : [];
8707
+ const open = {};
8708
+ if (data?.open && typeof data.open === "object") {
8709
+ for (const [id, key] of Object.entries(data.open)) {
8710
+ if (id && typeof key === "string" && key) open[id] = key;
8711
+ }
8712
+ }
8713
+ return { ids, open };
8442
8714
  } catch {
8443
- return [];
8715
+ return { ids: [], open: {} };
8444
8716
  }
8445
8717
  }
8446
8718
  function createTurnGate() {
8447
8719
  let assess = () => ({ action: "ignore" });
8448
8720
  const seen = /* @__PURE__ */ new Set();
8449
8721
  const blocked = /* @__PURE__ */ new Map();
8722
+ const openTurn = /* @__PURE__ */ new Map();
8450
8723
  let turnsFile = "";
8451
8724
  function setAssessor(fn, file) {
8452
8725
  if (typeof fn === "function") assess = fn;
8453
8726
  if (file && file !== turnsFile) {
8454
8727
  turnsFile = file;
8455
- for (const id of readIds(file)) seen.add(id);
8728
+ const state = readState(file);
8729
+ for (const id of state.ids) seen.add(id);
8730
+ for (const [id, key] of Object.entries(state.open)) openTurn.set(id, key);
8456
8731
  }
8457
8732
  }
8458
- function remember(id) {
8459
- if (!id || seen.has(id)) return;
8460
- seen.add(id);
8733
+ function persist() {
8461
8734
  if (!turnsFile) return;
8462
8735
  const ids = [...seen].slice(-4e3);
8736
+ const open = {};
8737
+ for (const id of ids) {
8738
+ const key = openTurn.get(id);
8739
+ if (key) open[id] = key;
8740
+ }
8463
8741
  try {
8464
8742
  fs12.mkdirSync(path12.dirname(turnsFile), { recursive: true });
8465
- fs12.writeFileSync(turnsFile, JSON.stringify({ ids }, null, 2));
8743
+ fs12.writeFileSync(turnsFile, JSON.stringify({ ids, open }, null, 2));
8466
8744
  } catch {
8467
8745
  }
8468
8746
  }
8747
+ function remember(id, key) {
8748
+ if (!id) return;
8749
+ seen.add(id);
8750
+ if (key) openTurn.set(id, key);
8751
+ persist();
8752
+ }
8469
8753
  async function onPreStep(payload, next) {
8470
8754
  let forwarded = false;
8471
8755
  const forward = () => {
@@ -8474,12 +8758,17 @@ function createTurnGate() {
8474
8758
  };
8475
8759
  try {
8476
8760
  const messages = payload?.messages;
8477
- if (!hasNewUserInput(messages)) return forward();
8761
+ const key = userTurnKey(messages);
8762
+ if (!key) return forward();
8478
8763
  if (isSubagent(payload?.agent)) return forward();
8479
8764
  const cwd = cwdOf(payload?.agent);
8480
8765
  if (!cwd) return forward();
8481
8766
  const id = sessionIdOf(payload.agent);
8482
- const verdict = assess(String(cwd), id ? seen.has(id) : false) || { action: "ignore" };
8767
+ if (id && openTurn.get(id) === key) {
8768
+ blocked.delete(id);
8769
+ return forward();
8770
+ }
8771
+ const verdict = assess(String(cwd), id ? seen.has(id) : false, id) || { action: "ignore" };
8483
8772
  const downstream = await forward();
8484
8773
  if (downstream?.kind === "reject") return downstream;
8485
8774
  if (verdict.action === "block" && verdict.message) {
@@ -8492,7 +8781,7 @@ function createTurnGate() {
8492
8781
  }
8493
8782
  }
8494
8783
  if (id) blocked.delete(id);
8495
- if (verdict.action === "allow" && id) remember(id);
8784
+ if (verdict.action === "allow" && id) remember(id, key);
8496
8785
  return downstream;
8497
8786
  } catch (err) {
8498
8787
  console.warn("[biunow-panel] chat turn gate failed:", err?.message || err);
@@ -8573,7 +8862,29 @@ function resolveIconsDir() {
8573
8862
  return candidates[0];
8574
8863
  }
8575
8864
  var ICONS_DIR = resolveIconsDir();
8865
+ function resolveDiagnoseSkillDir(skillName = "account-diagnosis") {
8866
+ const here = path14.dirname(fileURLToPath2(import.meta.url));
8867
+ const candidates = [
8868
+ path14.join(here, "assets", "diagnose", skillName),
8869
+ path14.join(here, "..", "..", "assets", "diagnose", skillName)
8870
+ ];
8871
+ return candidates.find((dir) => fs14.existsSync(path14.join(dir, "SKILL.md"))) || null;
8872
+ }
8873
+ var DIAGNOSE_SKILL_DIRS = {
8874
+ "account-diagnosis": resolveDiagnoseSkillDir("account-diagnosis"),
8875
+ "creator-research": resolveDiagnoseSkillDir("creator-research"),
8876
+ "topic-planner": resolveDiagnoseSkillDir("topic-planner")
8877
+ };
8878
+ function seedDiagnoseSkill(projectDir, skillName = "account-diagnosis") {
8879
+ const sourceDir = DIAGNOSE_SKILL_DIRS[skillName];
8880
+ if (!sourceDir) throw new Error("\u8D26\u53F7\u589E\u957F\u5185\u6838\u7F3A\u5931\uFF0C\u8BF7\u66F4\u65B0\u9762\u677F");
8881
+ const destDir = path14.join(projectDir, ".agents", "skills", skillName);
8882
+ fs14.mkdirSync(path14.dirname(destDir), { recursive: true });
8883
+ fs14.cpSync(sourceDir, destDir, { recursive: true, force: true });
8884
+ return destDir;
8885
+ }
8576
8886
  var MAX_BODY = 256 * 1024;
8887
+ var GROWTH_LABELS = { research: "\u5BF9\u6807\u8C03\u7814", planner: "\u9009\u9898\u89C4\u5212", followup: "\u590D\u8BCA\u5BF9\u6BD4" };
8577
8888
  function send(res, status, body) {
8578
8889
  const data = JSON.stringify(body);
8579
8890
  res.writeHead(status, {
@@ -8602,16 +8913,25 @@ function createPanelApp(options = {}) {
8602
8913
  const getPanelPublicUrl = typeof options.getPanelPublicUrl === "function" ? options.getPanelPublicUrl : () => options.panelPublicUrl ?? null;
8603
8914
  const dsh = options.dsh ?? null;
8604
8915
  let settings = readSettings(paths);
8916
+ const pinnedLicense = String(options.licenseBaseUrl || DEFAULT_SETTINGS.licenseBaseUrl).replace(/\/$/, "");
8917
+ if (String(settings.licenseBaseUrl || "").replace(/\/$/, "") !== pinnedLicense) {
8918
+ settings = writeSettings(paths, { licenseBaseUrl: pinnedLicense });
8919
+ }
8605
8920
  const accountId = options.accountId ?? settings.accountId ?? "local-dev";
8606
8921
  const packageName = panelPackageName(options.packageName);
8607
- const resellerCode = panelResellerCode(options.resellerCode);
8608
- const buyPageUrl = () => withReseller(`${String(settings.licenseBaseUrl || "").replace(/\/$/, "")}/buy`, resellerCode);
8922
+ const configResellerCode = panelResellerCode(options.resellerCode);
8923
+ const resellerCode = () => {
8924
+ const fromLicense = license.resellerCode();
8925
+ if (fromLicense) return fromLicense;
8926
+ return configResellerCode;
8927
+ };
8928
+ const buyPageUrl = () => withReseller(`${String(settings.licenseBaseUrl || "").replace(/\/$/, "")}/buy`, resellerCode());
8609
8929
  const commerceUrl = (pathname) => {
8610
8930
  const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
8611
8931
  if (!base) return "";
8612
- return withReseller(`${base}${pathname}`, resellerCode);
8932
+ return withReseller(`${base}${pathname}`, resellerCode());
8613
8933
  };
8614
- const panelInstallHint = (updating) => updating ? `DSH \u2192 \u6DFB\u52A0\u63D2\u4EF6 / \u63D2\u4EF6\u5217\u8868 \u2192 \u66F4\u65B0 ${packageName}\uFF08\u5EFA\u8BAE\u4E2D\u56FD\u5927\u9646\u955C\u50CF\uFF09\u540E\u91CD\u542F DSH` : `DSH \u2192 \u6DFB\u52A0\u63D2\u4EF6 \u2192 \u5305\u540D ${packageName}\uFF08\u5EFA\u8BAE\u4E2D\u56FD\u5927\u9646\u955C\u50CF\uFF09`;
8934
+ const panelInstallHint = (updating) => updating ? `\u5728 DSH \u7684\u63D2\u4EF6\u5217\u8868\u91CC\u66F4\u65B0\u9762\u677F\uFF0C\u7136\u540E\u91CD\u542F` : `\u5728 DSH \u91CC\u6DFB\u52A0\u63D2\u4EF6\u5E76\u5B89\u88C5\u9762\u677F`;
8615
8935
  const license = new LicenseClient({
8616
8936
  paths,
8617
8937
  baseUrl: settings.licenseBaseUrl,
@@ -8640,7 +8960,7 @@ function createPanelApp(options = {}) {
8640
8960
  }
8641
8961
  const keys = [...publicKeys, ...publisherKeys];
8642
8962
  if (!keys.length) {
8643
- throw new Error("\u65E0\u6CD5\u9A8C\u7B7E\uFF1A\u670D\u52A1\u5668\u672A\u767B\u8BB0\u53D1\u5E03\u8005\u516C\u94A5\u3002\u8BF7\u5728\u7BA1\u7406\u540E\u53F0\u300C\u53D1\u5E03\u8005\u300D\u9875\u914D\u7F6E\u5BC6\u94A5\u540E\u518D\u5B89\u88C5\u3002");
8963
+ throw new Error("\u5B89\u88C5\u6682\u65F6\u4E0D\u53EF\u7528\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
8644
8964
  }
8645
8965
  return keys;
8646
8966
  }
@@ -8651,9 +8971,26 @@ function createPanelApp(options = {}) {
8651
8971
  registry: null,
8652
8972
  error: null
8653
8973
  };
8974
+ const fallbackRegistry = "https://registry.npmmirror.com";
8975
+ let remoteRegistry = "";
8976
+ let registryFetchedAt = 0;
8654
8977
  function panelRegistryBase() {
8655
- const raw = String(settings.panelNpmRegistry || "https://registry.npmmirror.com").replace(/\/$/, "");
8656
- return raw || "https://registry.npmmirror.com";
8978
+ const raw = String(remoteRegistry || fallbackRegistry).replace(/\/$/, "");
8979
+ return raw || fallbackRegistry;
8980
+ }
8981
+ async function refreshPanelRegistry() {
8982
+ if (remoteRegistry && Date.now() - registryFetchedAt < 10 * 60 * 1e3) return;
8983
+ registryFetchedAt = Date.now();
8984
+ const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
8985
+ if (!base) return;
8986
+ try {
8987
+ const res = await fetch(`${base}/v1/commerce/site`, { cache: "no-store" });
8988
+ if (!res.ok) return;
8989
+ const body = await res.json();
8990
+ const url = String(body?.site?.panelRegistry || "").trim().replace(/\/$/, "");
8991
+ if (/^https?:\/\//i.test(url)) remoteRegistry = url;
8992
+ } catch {
8993
+ }
8657
8994
  }
8658
8995
  async function fetchPanelLatestFromRegistry(registry) {
8659
8996
  const url = `${registry.replace(/\/$/, "")}/${encodeURIComponent(packageName)}`;
@@ -8665,13 +9002,14 @@ function createPanelApp(options = {}) {
8665
9002
  },
8666
9003
  cache: "no-store"
8667
9004
  });
8668
- if (!res.ok) throw new Error(`npm registry HTTP ${res.status}`);
9005
+ if (!res.ok) throw new Error("\u6682\u65F6\u65E0\u6CD5\u68C0\u67E5\u66F4\u65B0");
8669
9006
  const data = await res.json();
8670
9007
  const latest = data?.["dist-tags"]?.latest || null;
8671
- if (!latest) throw new Error("registry \u672A\u8FD4\u56DE dist-tags.latest");
9008
+ if (!latest) throw new Error("\u6682\u65F6\u65E0\u6CD5\u68C0\u67E5\u66F4\u65B0");
8672
9009
  return String(latest);
8673
9010
  }
8674
9011
  async function checkPanelSelfUpdate({ force = false } = {}) {
9012
+ await refreshPanelRegistry();
8675
9013
  const registry = panelRegistryBase();
8676
9014
  const official = "https://registry.npmjs.org";
8677
9015
  const now = Date.now();
@@ -8685,7 +9023,7 @@ function createPanelApp(options = {}) {
8685
9023
  const hits = settled.map((s3, i) => s3.status === "fulfilled" ? { registry: targets[i], version: s3.value } : null).filter(Boolean);
8686
9024
  if (!hits.length) {
8687
9025
  const err = settled.find((s3) => s3.status === "rejected");
8688
- throw err?.reason || new Error("\u6240\u6709 npm registry \u5747\u4E0D\u53EF\u8FBE");
9026
+ throw err?.reason || new Error("\u6682\u65F6\u65E0\u6CD5\u68C0\u67E5\u66F4\u65B0");
8689
9027
  }
8690
9028
  hits.sort((a, b2) => compareVersions(b2.version, a.version));
8691
9029
  const best = hits[0];
@@ -8751,7 +9089,7 @@ function createPanelApp(options = {}) {
8751
9089
  function ensureCallbackToken(agentId) {
8752
9090
  let token = callbackTokens.get(agentId);
8753
9091
  if (!token) {
8754
- token = crypto7.randomBytes(24).toString("base64url");
9092
+ token = crypto8.randomBytes(24).toString("base64url");
8755
9093
  callbackTokens.set(agentId, token);
8756
9094
  }
8757
9095
  return token;
@@ -8759,6 +9097,24 @@ function createPanelApp(options = {}) {
8759
9097
  function callbackBaseUrl() {
8760
9098
  return getPanelPublicUrl();
8761
9099
  }
9100
+ const DEFAULT_TRIAL_RUNS = 3;
9101
+ let trialRuns = DEFAULT_TRIAL_RUNS;
9102
+ let trialRunsAt = 0;
9103
+ async function refreshTrialRuns() {
9104
+ if (trialRunsAt && Date.now() - trialRunsAt < 10 * 60 * 1e3) return trialRuns;
9105
+ trialRunsAt = Date.now();
9106
+ const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
9107
+ if (!base) return trialRuns;
9108
+ try {
9109
+ const res = await fetch(`${base}/v1/commerce/site`, { cache: "no-store" });
9110
+ if (!res.ok) return trialRuns;
9111
+ const body = await res.json();
9112
+ const n = Number(body?.site?.trialRuns);
9113
+ if (Number.isFinite(n)) trialRuns = Math.max(0, Math.min(99, Math.floor(n)));
9114
+ } catch {
9115
+ }
9116
+ return trialRuns;
9117
+ }
8762
9118
  function trialsPath() {
8763
9119
  return path14.join(paths.root, "trials.json");
8764
9120
  }
@@ -8774,14 +9130,15 @@ function createPanelApp(options = {}) {
8774
9130
  fs14.mkdirSync(paths.root, { recursive: true });
8775
9131
  fs14.writeFileSync(trialsPath(), JSON.stringify(data, null, 2));
8776
9132
  }
8777
- function grantTrial(product) {
9133
+ async function grantTrial(product) {
8778
9134
  if (!product) return;
9135
+ if (readTrials()[product]?.granted) return readTrials()[product];
9136
+ await refreshTrialRuns();
8779
9137
  const all = readTrials();
8780
9138
  if (all[product]?.granted) return all[product];
8781
- all[product] = { remaining: 1, granted: true, grantedAt: (/* @__PURE__ */ new Date()).toISOString() };
9139
+ all[product] = { remaining: trialRuns, granted: true, grantedAt: (/* @__PURE__ */ new Date()).toISOString() };
8782
9140
  writeTrials(all);
8783
- void syncTrialCheck(product);
8784
- return all[product];
9141
+ return await syncTrialCheck(product) || all[product];
8785
9142
  }
8786
9143
  function trialOf(product) {
8787
9144
  if (!product) return { remaining: 0, granted: false };
@@ -8800,11 +9157,14 @@ function createPanelApp(options = {}) {
8800
9157
  if (!res.ok) return null;
8801
9158
  const data = await res.json();
8802
9159
  const all = readTrials();
9160
+ const prev = all[product] || {};
9161
+ const remaining = Number(data.remaining);
8803
9162
  all[product] = {
8804
- remaining: Number(data.remaining) || 0,
9163
+ remaining: Number.isFinite(remaining) ? remaining : 0,
8805
9164
  granted: true,
8806
- grantedAt: data.grantedAt || (/* @__PURE__ */ new Date()).toISOString(),
8807
- lastUsedAt: data.usedAt || all[product]?.lastUsedAt,
9165
+ grantedAt: data.grantedAt || prev.grantedAt || (/* @__PURE__ */ new Date()).toISOString(),
9166
+ lastUsedAt: data.usedAt || prev.lastUsedAt,
9167
+ charged: prev.charged,
8808
9168
  server: true
8809
9169
  };
8810
9170
  writeTrials(all);
@@ -8813,12 +9173,31 @@ function createPanelApp(options = {}) {
8813
9173
  return null;
8814
9174
  }
8815
9175
  }
8816
- function consumeTrial(product) {
9176
+ function consumeTrial(product, keys) {
8817
9177
  if (!product) return false;
8818
9178
  if (license.canUseProduct(product)) return false;
9179
+ const ids = [...new Set((Array.isArray(keys) ? keys : []).map((k2) => String(k2 || "").trim()).filter(Boolean))];
9180
+ if (!ids.length) return false;
8819
9181
  const all = readTrials();
8820
9182
  const row = all[product];
8821
9183
  if (!row || !(row.remaining > 0)) return false;
9184
+ const charged = new Set(Array.isArray(row.charged) ? row.charged.map(String) : []);
9185
+ if (ids.some((id) => charged.has(id))) {
9186
+ let dirty = false;
9187
+ for (const id of ids) {
9188
+ if (!charged.has(id)) {
9189
+ charged.add(id);
9190
+ dirty = true;
9191
+ }
9192
+ }
9193
+ if (dirty) {
9194
+ row.charged = [...charged].slice(-400);
9195
+ writeTrials(all);
9196
+ }
9197
+ return false;
9198
+ }
9199
+ for (const id of ids) charged.add(id);
9200
+ row.charged = [...charged].slice(-400);
8822
9201
  row.remaining -= 1;
8823
9202
  row.lastUsedAt = (/* @__PURE__ */ new Date()).toISOString();
8824
9203
  writeTrials(all);
@@ -8836,6 +9215,9 @@ function createPanelApp(options = {}) {
8836
9215
  })();
8837
9216
  return true;
8838
9217
  }
9218
+ function trialChargeKeys(parts) {
9219
+ return (parts || []).map((k2) => String(k2 || "").trim()).filter(Boolean);
9220
+ }
8839
9221
  function healTrialIfJobDone(product, agentId) {
8840
9222
  if (!product || license.canUseProduct(product)) return;
8841
9223
  const row = trialOf(product);
@@ -8845,11 +9227,48 @@ function createPanelApp(options = {}) {
8845
9227
  const jobsFile = path14.join(ws2, "jobs", "index.json");
8846
9228
  if (!fs14.existsSync(jobsFile)) return;
8847
9229
  const jobs = JSON.parse(fs14.readFileSync(jobsFile, "utf8"))?.jobs || [];
8848
- const done = jobs.some((j2) => j2 && (j2.status === "done" || j2.outputMp4 || j2.phase === "film"));
8849
- if (done) consumeTrial(product);
9230
+ const grantedAt = Date.parse(row.grantedAt || "");
9231
+ for (const j2 of jobs) {
9232
+ if (!j2 || !(j2.status === "done" || j2.outputMp4 || j2.phase === "film")) continue;
9233
+ const stamp = Date.parse(j2.filmAt || j2.updatedAt || j2.createdAt || "");
9234
+ if (Number.isFinite(grantedAt) && Number.isFinite(stamp) && stamp < grantedAt) continue;
9235
+ const keys = trialChargeKeys([
9236
+ j2.panelTaskId ? `task:${j2.panelTaskId}` : "",
9237
+ j2.id ? `job:${j2.id}` : "",
9238
+ j2.projectPath ? `path:${j2.projectPath}` : "",
9239
+ j2.outputMp4 ? `artifact:${j2.outputMp4}` : ""
9240
+ ]);
9241
+ if (keys.length) consumeTrial(product, keys);
9242
+ }
8850
9243
  } catch {
8851
9244
  }
8852
9245
  }
9246
+ const trialRunSessions = /* @__PURE__ */ new Set();
9247
+ function trialRunsPath() {
9248
+ return path14.join(paths.root, "trial-runs.json");
9249
+ }
9250
+ function loadTrialRuns() {
9251
+ try {
9252
+ const data = JSON.parse(fs14.readFileSync(trialRunsPath(), "utf8"));
9253
+ const ids = Array.isArray(data?.ids) ? data.ids : [];
9254
+ for (const id of ids) {
9255
+ if (id) trialRunSessions.add(String(id));
9256
+ }
9257
+ } catch {
9258
+ }
9259
+ }
9260
+ function rememberTrialRun(sessionId) {
9261
+ const id = String(sessionId || "");
9262
+ if (!id || trialRunSessions.has(id)) return;
9263
+ trialRunSessions.add(id);
9264
+ const ids = [...trialRunSessions].slice(-400);
9265
+ try {
9266
+ fs14.mkdirSync(paths.root, { recursive: true });
9267
+ fs14.writeFileSync(trialRunsPath(), JSON.stringify({ ids }, null, 2));
9268
+ } catch {
9269
+ }
9270
+ }
9271
+ loadTrialRuns();
8853
9272
  function canRunProduct(product) {
8854
9273
  if (!product) return license.canExport();
8855
9274
  if (license.canUseProduct(product)) return true;
@@ -8871,13 +9290,24 @@ function createPanelApp(options = {}) {
8871
9290
  }
8872
9291
  const body = await res.json();
8873
9292
  const store = Array.isArray(body.store) ? body.store : [];
8874
- if (!store.length) storeError = `\u5546\u5E97\u4E3A\u7A7A\uFF1A\u8BF7\u5230\u7BA1\u7406\u540E\u53F0\u6DFB\u52A0\u4EA7\u54C1\u5E76\u53D1\u5E03\u7248\u672C\uFF08${base}\uFF09`;
9293
+ if (!store.length) storeError = "\u5546\u5E97\u6682\u65F6\u6CA1\u6709\u53EF\u5B89\u88C5\u7684\u5185\u5BB9";
8875
9294
  return store;
8876
9295
  } catch (err) {
8877
9296
  storeError = `\u65E0\u6CD5\u8FDE\u63A5\u6388\u6743\u670D\u52A1 ${base}\uFF1A${err?.message || err}`;
8878
9297
  return [];
8879
9298
  }
8880
9299
  }
9300
+ function userFacingInstallError(err) {
9301
+ const msg = err?.message || String(err);
9302
+ console.warn("[biunow-panel] install:", msg);
9303
+ if (err?.code === "PACKAGE_SYNCING" || /还在同步/.test(msg)) return new Error("\u5B89\u88C5\u5305\u8FD8\u5728\u540C\u6B65\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9304
+ if (/验签|signature|not trusted|digest|无法验证|校验失败|hash mismatch/i.test(msg)) {
9305
+ return new Error("\u5B89\u88C5\u5305\u65E0\u6CD5\u9A8C\u8BC1\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9306
+ }
9307
+ if (/超时/.test(msg)) return new Error("\u4E0B\u8F7D\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9308
+ if (/暂时下载不了/.test(msg)) return new Error("\u5B89\u88C5\u5305\u6682\u65F6\u4E0B\u8F7D\u4E0D\u4E86\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9309
+ return new Error("\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9310
+ }
8881
9311
  function submitStoreInstall(item) {
8882
9312
  const product = item.slug;
8883
9313
  const version = item.latest?.version;
@@ -8888,27 +9318,17 @@ function createPanelApp(options = {}) {
8888
9318
  title: `\u5B89\u88C5 ${item.name || product}`,
8889
9319
  run: async (ctx) => {
8890
9320
  ctx.setProgress(5, "\u51C6\u5907\u4E0B\u8F7D");
8891
- const q2 = new URLSearchParams({ product });
8892
- if (version) q2.set("version", version);
8893
- const url = `${settings.licenseBaseUrl}/v1/store/download?${q2}`;
9321
+ await supervisor.stop(product).catch(() => {
9322
+ });
8894
9323
  let result;
8895
9324
  try {
8896
- ctx.setProgress(15, "\u4E0B\u8F7D\u5B89\u88C5\u5305");
8897
- result = await installFromUrl({
8898
- paths,
8899
- publicKeys: await trustedKeys(),
8900
- url,
8901
- expectedSha256: sha && !/^0+$/.test(sha) ? sha : void 0
8902
- });
9325
+ ctx.setProgress(15, "\u6B63\u5728\u4E0B\u8F7D");
9326
+ result = await installPublishedAgent(product, version, sha, item.latest?.distribution);
8903
9327
  } catch (err) {
8904
- const msg = err?.message || String(err);
8905
- if (/无法验签|验签失败|signature|not trusted/i.test(msg)) throw err;
8906
- if (/下载失败|download failed|HTTP/i.test(msg)) throw err;
8907
- if (/hash mismatch|校验失败/i.test(msg)) throw err;
8908
- throw new Error(`\u5B89\u88C5 ${product} \u5931\u8D25\uFF1A${msg}`);
8909
- }
8910
- grantTrial(productOf({ manifest: result.manifest }) || product);
8911
- ctx.setProgress(55, "Agent \u5DF2\u843D\u76D8\uFF0C\u5B89\u88C5\u8FD0\u884C\u65F6");
9328
+ throw userFacingInstallError(err);
9329
+ }
9330
+ await grantTrial(productOf({ manifest: result.manifest }) || product);
9331
+ ctx.setProgress(55, "\u6B63\u5728\u51C6\u5907\u8FD0\u884C\u73AF\u5883");
8912
9332
  await ensureAgentRuntimes(result.dir, result.manifest.runtime?.shared ?? [], ctx);
8913
9333
  try {
8914
9334
  const installed = listInstalled(paths).find(
@@ -8918,6 +9338,7 @@ function createPanelApp(options = {}) {
8918
9338
  } catch {
8919
9339
  }
8920
9340
  ctx.setProgress(100, "\u5B8C\u6210");
9341
+ void reportInstalls(true);
8921
9342
  return { artifact: result.dir };
8922
9343
  }
8923
9344
  });
@@ -8947,12 +9368,16 @@ function createPanelApp(options = {}) {
8947
9368
  if (!dsh?.chat?.startSkillRun) {
8948
9369
  return { ok: false, reason: "chat-unavailable", promptText: text };
8949
9370
  }
9371
+ const product = agent ? productOf(agent) || agent.id : agentId;
8950
9372
  return dsh.chat.startSkillRun({
8951
9373
  agentId,
8952
9374
  skill: skill || agentId,
8953
9375
  projectPath,
8954
9376
  promptText: text,
8955
- title: title || `${skill || agentId} \xB7 \u521B\u4F5C`
9377
+ title: title || `${skill || agentId} \xB7 \u521B\u4F5C`,
9378
+ beforePrompt: (sessionId) => {
9379
+ if (!license.canUseProduct(product)) rememberTrialRun(sessionId);
9380
+ }
8956
9381
  });
8957
9382
  }
8958
9383
  function isRequiredNpmRuntime(spec) {
@@ -8967,16 +9392,16 @@ function createPanelApp(options = {}) {
8967
9392
  for (const spec of missing) {
8968
9393
  const [name2, major] = String(spec).split("@");
8969
9394
  if (!name2 || !major) continue;
8970
- ctx?.setProgress?.(70, `\u5B89\u88C5\u8FD0\u884C\u65F6 ${spec}`);
9395
+ ctx?.setProgress?.(70, "\u6B63\u5728\u51C6\u5907\u8FD0\u884C\u73AF\u5883");
8971
9396
  try {
8972
9397
  await installRuntimeFromStore(name2, Number(major));
8973
9398
  installed.push(spec);
8974
9399
  } catch (err) {
8975
- const msg = err?.message || String(err);
9400
+ console.warn("[biunow-panel] runtime:", spec, err?.message || err);
8976
9401
  if (isRequiredNpmRuntime(spec)) {
8977
- throw new Error(`\u5FC5\u9700\u8FD0\u884C\u65F6 ${spec} \u5B89\u88C5\u5931\u8D25\uFF1A${msg}\u3002\u8BF7\u786E\u8BA4\u7BA1\u7406\u540E\u53F0\u5DF2\u4E0A\u4F20\u5BF9\u5E94\u8FD0\u884C\u65F6\u3002`);
9402
+ throw new Error("\u8FD0\u884C\u73AF\u5883\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
8978
9403
  }
8979
- softErrors.push(`${spec}: ${msg}`);
9404
+ softErrors.push(spec);
8980
9405
  }
8981
9406
  }
8982
9407
  try {
@@ -8987,10 +9412,10 @@ function createPanelApp(options = {}) {
8987
9412
  }
8988
9413
  const stillMissingNpm = missingRuntime(paths, list).filter(isRequiredNpmRuntime);
8989
9414
  if (stillMissingNpm.length) {
8990
- throw new Error(`\u7F3A\u5C11\u5FC5\u9700 npm \u8FD0\u884C\u65F6: ${stillMissingNpm.join(", ")}\u3002\u8BF7\u5230\u7BA1\u7406\u540E\u53F0\u300C\u8FD0\u884C\u65F6\u300D\u4E0A\u4F20\u540E\u91CD\u8BD5\u3002`);
9415
+ throw new Error("\u8FD0\u884C\u73AF\u5883\u8FD8\u6CA1\u51C6\u5907\u597D\uFF0C\u8BF7\u91CD\u65B0\u5B89\u88C5");
8991
9416
  }
8992
9417
  if (softErrors.length) {
8993
- ctx?.setProgress?.(85, `\u90E8\u5206\u53EF\u9009\u8FD0\u884C\u65F6\u672A\u88C5\u4E0A\uFF08\u53EF\u7A0D\u540E\u8865\uFF09: ${softErrors.map((e) => e.split(":")[0]).join(", ")}`);
9418
+ ctx?.setProgress?.(85, "\u90E8\u5206\u529F\u80FD\u672A\u5C31\u7EEA\uFF0C\u53EF\u4EE5\u7A0D\u540E\u8865\u9F50");
8994
9419
  }
8995
9420
  return {
8996
9421
  installed,
@@ -8999,38 +9424,166 @@ function createPanelApp(options = {}) {
8999
9424
  stillMissing: missingRuntime(paths, list)
9000
9425
  };
9001
9426
  }
9002
- async function installRuntimeFromStore(name2, major) {
9003
- const url = `${settings.licenseBaseUrl}/v1/store/runtimes/download?name=${encodeURIComponent(name2)}&major=${major}`;
9004
- const res2 = await fetch(url);
9005
- if (!res2.ok) throw new Error(`\u8FD0\u884C\u65F6 ${name2}@${major} \u4E0B\u8F7D\u5931\u8D25\uFF08HTTP ${res2.status}\uFF09\u3002\u8BF7\u786E\u8BA4\u7BA1\u7406\u540E\u53F0\u5DF2\u4E0A\u4F20\u8BE5\u8FD0\u884C\u65F6\u3002`);
9006
- fs14.mkdirSync(paths.downloads, { recursive: true });
9007
- const file = path14.join(paths.downloads, `runtime-${name2}-${major}.tar.gz`);
9427
+ async function sha256OfFile(file) {
9428
+ const hash = crypto8.createHash("sha256");
9429
+ await new Promise((resolve, reject) => {
9430
+ const input = fs14.createReadStream(file);
9431
+ input.on("error", reject);
9432
+ hash.on("error", reject);
9433
+ hash.on("finish", resolve);
9434
+ input.pipe(hash);
9435
+ });
9436
+ return hash.digest("hex");
9437
+ }
9438
+ function assertNpmRuntimeReady(dir) {
9439
+ let manifest;
9440
+ try {
9441
+ manifest = JSON.parse(fs14.readFileSync(path14.join(dir, "manifest.json"), "utf8"));
9442
+ } catch {
9443
+ return;
9444
+ }
9445
+ if (manifest.kind !== "npm") return;
9446
+ const here = `${process.platform}-${process.arch}`;
9447
+ if (manifest.platform && manifest.platform !== here) {
9448
+ fs14.rmSync(dir, { recursive: true, force: true });
9449
+ console.warn("[biunow-panel] runtime platform", manifest.platform, "!=", here);
9450
+ throw new Error("\u8FD0\u884C\u73AF\u5883\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9451
+ }
9452
+ if (!fs14.existsSync(path14.join(dir, manifest.moduleRoot || "node_modules"))) {
9453
+ fs14.rmSync(dir, { recursive: true, force: true });
9454
+ console.warn("[biunow-panel] runtime archive has no node_modules");
9455
+ throw new Error("\u8FD0\u884C\u73AF\u5883\u5B89\u88C5\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9456
+ }
9457
+ }
9458
+ async function downloadToFile(url, file) {
9459
+ const res2 = await fetch(url, { redirect: "follow" });
9460
+ if (!res2.ok) throw new Error(`\u4E0B\u8F7D\u5931\u8D25 HTTP ${res2.status}\uFF1A${url}`);
9008
9461
  const { createWriteStream } = await import("node:fs");
9009
9462
  const { pipeline } = await import("node:stream/promises");
9010
9463
  const { Readable } = await import("node:stream");
9011
9464
  if (!res2.body) {
9012
- const buf = Buffer.from(await res2.arrayBuffer());
9013
- fs14.writeFileSync(file, buf);
9465
+ fs14.writeFileSync(file, Buffer.from(await res2.arrayBuffer()));
9466
+ return;
9467
+ }
9468
+ await pipeline(Readable.fromWeb(res2.body), createWriteStream(file));
9469
+ }
9470
+ async function installRuntimeFromStore(name2, major) {
9471
+ const platform = `${process.platform}-${process.arch}`;
9472
+ const url = `${settings.licenseBaseUrl}/v1/store/runtimes/download?name=${encodeURIComponent(name2)}&major=${major}&platform=${encodeURIComponent(platform)}`;
9473
+ const res2 = await fetch(url, { headers: { accept: "application/json, application/gzip" } });
9474
+ if (!res2.ok) throw new Error("\u7EC4\u4EF6\u6682\u65F6\u4E0B\u8F7D\u4E0D\u4E86\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9475
+ fs14.mkdirSync(paths.downloads, { recursive: true });
9476
+ const file = path14.join(paths.downloads, `runtime-${name2}-${major}-${platform}.tar.gz`);
9477
+ const type = String(res2.headers.get("content-type") || "");
9478
+ if (type.includes("json")) {
9479
+ const body = await res2.json();
9480
+ if (!body?.url) throw new Error("\u7EC4\u4EF6\u6682\u65F6\u4E0B\u8F7D\u4E0D\u4E86\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9481
+ await downloadToFile(body.url, file);
9482
+ if (body.sha256 && !/^0+$/.test(String(body.sha256))) {
9483
+ const actual = await sha256OfFile(file);
9484
+ if (actual !== body.sha256) throw new Error("\u7EC4\u4EF6\u65E0\u6CD5\u9A8C\u8BC1\uFF0C\u8BF7\u7A0D\u540E\u518D\u8BD5");
9485
+ }
9486
+ } else if (!res2.body) {
9487
+ fs14.writeFileSync(file, Buffer.from(await res2.arrayBuffer()));
9014
9488
  } else {
9489
+ const { createWriteStream } = await import("node:fs");
9490
+ const { pipeline } = await import("node:stream/promises");
9491
+ const { Readable } = await import("node:stream");
9015
9492
  await pipeline(Readable.fromWeb(res2.body), createWriteStream(file));
9016
9493
  }
9017
- return importRuntimeArchive(paths, file);
9494
+ const imported = await importRuntimeArchive(paths, file);
9495
+ assertNpmRuntimeReady(imported.dir);
9496
+ return imported;
9497
+ }
9498
+ async function installPublishedAgent(product, version, sha, distribution) {
9499
+ await refreshPanelRegistry();
9500
+ const npmName = agentNpmPackage(product);
9501
+ if (npmName && version) {
9502
+ try {
9503
+ return await installFromNpmRegistry({
9504
+ paths,
9505
+ publicKeys: await trustedKeys(),
9506
+ registry: panelRegistryBase(),
9507
+ name: npmName,
9508
+ version
9509
+ });
9510
+ } catch (err) {
9511
+ console.warn("[biunow-panel] package:", err?.message || err);
9512
+ if (distribution === "npm" || err?.code !== "PACKAGE_SYNCING") throw err;
9513
+ }
9514
+ }
9515
+ const q2 = new URLSearchParams({ product });
9516
+ if (version) q2.set("version", version);
9517
+ const url = `${settings.licenseBaseUrl}/v1/store/download?${q2}`;
9518
+ return installFromUrl({
9519
+ paths,
9520
+ publicKeys: await trustedKeys(),
9521
+ url,
9522
+ expectedSha256: sha && !/^0+$/.test(sha) ? sha : void 0
9523
+ });
9524
+ }
9525
+ function agentFilesBroken(agent) {
9526
+ if (!agent) return true;
9527
+ try {
9528
+ const host = agent.manifest?.entry?.host;
9529
+ return !host || !fs14.existsSync(path14.resolve(agent.dir, host));
9530
+ } catch {
9531
+ return true;
9532
+ }
9533
+ }
9534
+ const repairing = /* @__PURE__ */ new Set();
9535
+ function submitRepair(agent) {
9536
+ if (repairing.has(agent.id)) return null;
9537
+ repairing.add(agent.id);
9538
+ const product = productOf(agent) || agent.id;
9539
+ return queue.submit({
9540
+ agentId: agent.id,
9541
+ kind: "install",
9542
+ title: `\u4FEE\u590D ${agent.manifest?.name || agent.id} \u5B89\u88C5`,
9543
+ run: async (ctx) => {
9544
+ try {
9545
+ ctx.setProgress(10, "\u6B63\u5728\u91CD\u65B0\u4E0B\u8F7D\u5B89\u88C5\u5305");
9546
+ await supervisor.stop(agent.id).catch(() => {
9547
+ });
9548
+ const result = await installPublishedAgent(product, agent.version, void 0, void 0);
9549
+ ctx.setProgress(60, "\u6B63\u5728\u51C6\u5907\u8FD0\u884C\u73AF\u5883");
9550
+ await ensureAgentRuntimes(result.dir, result.manifest.runtime?.shared ?? [], ctx);
9551
+ const installed = listInstalled(paths).find((a) => a.id === agent.id);
9552
+ if (installed) syncAgentSkills(installed);
9553
+ ctx.setProgress(100, "\u5B89\u88C5\u5DF2\u4FEE\u590D");
9554
+ void reportInstalls(true);
9555
+ return { artifact: result.dir };
9556
+ } catch (err) {
9557
+ throw userFacingInstallError(err);
9558
+ } finally {
9559
+ repairing.delete(agent.id);
9560
+ }
9561
+ }
9562
+ });
9563
+ }
9564
+ function repairBrokenInstalls() {
9565
+ for (const agent of listInstalled(paths)) {
9566
+ if (!agentFilesBroken(agent)) continue;
9567
+ const busy = queue.list().some((t) => t.agentId === agent.id && (t.status === "queued" || t.status === "running"));
9568
+ if (busy) continue;
9569
+ console.warn("[biunow-panel] agent files missing:", agent.id, agent.version, agent.dir);
9570
+ submitRepair(agent);
9571
+ }
9018
9572
  }
9019
9573
  function submitUpdate(agent, next) {
9020
9574
  const product = productOf(agent) ?? next.product ?? settings.productSlug;
9021
9575
  return queue.submit({
9022
9576
  agentId: agent.id,
9023
9577
  kind: "update",
9024
- title: `\u66F4\u65B0 ${agent.id} \u2192 ${next.version}`,
9578
+ title: `\u66F4\u65B0 ${agent.manifest?.name || "\u521B\u4F5C\u5DE5\u5177"}`,
9025
9579
  run: async (ctx) => {
9026
- ctx.setProgress(15, "\u4E0B\u8F7D\u5236\u54C1");
9027
- const url = `${settings.licenseBaseUrl}/v1/store/download?product=${encodeURIComponent(product)}&version=${encodeURIComponent(next.version)}`;
9028
- const result = await installFromUrl({
9029
- paths,
9030
- publicKeys: await trustedKeys(),
9031
- url,
9032
- expectedSha256: next.sha256 && !/^0+$/.test(next.sha256) ? next.sha256 : void 0
9033
- });
9580
+ ctx.setProgress(15, "\u6B63\u5728\u4E0B\u8F7D\u66F4\u65B0");
9581
+ let result;
9582
+ try {
9583
+ result = await installPublishedAgent(product, next.version, next.sha256, next.distribution);
9584
+ } catch (err) {
9585
+ throw userFacingInstallError(err);
9586
+ }
9034
9587
  await ensureAgentRuntimes(result.dir, result.manifest.runtime?.shared ?? [], ctx);
9035
9588
  try {
9036
9589
  const installed = listInstalled(paths).find((a) => a.id === agent.id);
@@ -9038,30 +9591,48 @@ function createPanelApp(options = {}) {
9038
9591
  } catch {
9039
9592
  }
9040
9593
  ctx.setProgress(90, "\u5B8C\u6210");
9594
+ void reportInstalls(true);
9041
9595
  return { artifact: result.dir };
9042
9596
  }
9043
9597
  });
9044
9598
  }
9045
9599
  let lastReport = 0;
9046
9600
  async function reportInstalls(force = false) {
9047
- if (!settings.telemetry) return;
9048
9601
  if (!force && Date.now() - lastReport < 6 * 36e5) return;
9049
- const installs = listInstalled(paths).map((a) => ({ id: a.id, version: a.version }));
9050
- if (!installs.length) return;
9051
- const first = license.listProducts().find((p2) => p2.status.canExport);
9052
- const token = first ? license.tokenFor(first.product) : null;
9053
- if (!token) return;
9054
- try {
9055
- await fetch(`${settings.licenseBaseUrl}/v1/installs`, {
9056
- method: "POST",
9057
- headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
9058
- body: JSON.stringify({ product: first.product, os: process.platform, installs })
9059
- });
9060
- lastReport = Date.now();
9061
- } catch {
9602
+ const installed = listInstalled(paths);
9603
+ if (!installed.length) return;
9604
+ const groups = /* @__PURE__ */ new Map();
9605
+ for (const agent of installed) {
9606
+ const product = productOf(agent) || agent.id;
9607
+ if (!groups.has(product)) groups.set(product, []);
9608
+ groups.get(product).push({ id: agent.id, version: agent.version });
9609
+ }
9610
+ const tokenFor = /* @__PURE__ */ new Map();
9611
+ for (const row of license.listProducts()) {
9612
+ const token = row?.product ? license.tokenFor(row.product) : null;
9613
+ if (token) tokenFor.set(row.product, token);
9614
+ }
9615
+ const deviceHash = license.deviceHash();
9616
+ let reported = false;
9617
+ for (const [product, installs] of groups) {
9618
+ const token = tokenFor.get(product) || null;
9619
+ try {
9620
+ const res = await fetch(`${settings.licenseBaseUrl}/v1/installs`, {
9621
+ method: "POST",
9622
+ headers: {
9623
+ "content-type": "application/json",
9624
+ ...token ? { authorization: `Bearer ${token}` } : {}
9625
+ },
9626
+ body: JSON.stringify({ product, os: process.platform, installs, deviceHash })
9627
+ });
9628
+ if (res.ok) reported = true;
9629
+ } catch {
9630
+ }
9062
9631
  }
9632
+ if (reported) lastReport = Date.now();
9063
9633
  }
9064
9634
  async function autoUpdateTick() {
9635
+ void reportInstalls();
9065
9636
  if (!settings.autoUpdate) return;
9066
9637
  for (const agent of listInstalled(paths)) {
9067
9638
  await loadReleases(true, productOf(agent));
@@ -9101,6 +9672,13 @@ function createPanelApp(options = {}) {
9101
9672
  err.code = "PERMISSIONS_REQUIRED";
9102
9673
  throw err;
9103
9674
  }
9675
+ if (agentFilesBroken(agent)) {
9676
+ submitRepair(agent);
9677
+ const err = new Error("\u5B89\u88C5\u6587\u4EF6\u4E0D\u5B8C\u6574\uFF0C\u5DF2\u5F00\u59CB\u81EA\u52A8\u4FEE\u590D\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5");
9678
+ err.status = 409;
9679
+ err.code = "AGENT_INSTALL_BROKEN";
9680
+ throw err;
9681
+ }
9104
9682
  const token = ensureCallbackToken(agent.id);
9105
9683
  const publicBase = callbackBaseUrl();
9106
9684
  const licensed = product ? license.canUseProduct(product) : license.canExport();
@@ -9111,7 +9689,7 @@ function createPanelApp(options = {}) {
9111
9689
  const shared = agent.manifest.runtime?.shared ?? [];
9112
9690
  const missingNpm = missingRuntime(paths, shared).filter(isRequiredNpmRuntime);
9113
9691
  if (missingNpm.length) {
9114
- const err = new Error(`\u7F3A\u5C11\u5F15\u64CE\u4F9D\u8D56\u8FD0\u884C\u65F6 ${missingNpm.join(", ")}\uFF0C\u8BF7\u5148\u70B9\u300C\u5B89\u88C5\u73AF\u5883\u300D\u6216\u91CD\u65B0\u5B89\u88C5 Agent`);
9692
+ const err = new Error("\u8FD0\u884C\u73AF\u5883\u8FD8\u6CA1\u51C6\u5907\u597D\uFF0C\u8BF7\u5148\u70B9\u300C\u88C5\u73AF\u5883\u300D\uFF0C\u6216\u91CD\u65B0\u5B89\u88C5");
9115
9693
  err.status = 409;
9116
9694
  err.code = "RUNTIME_MISSING";
9117
9695
  throw err;
@@ -9124,18 +9702,38 @@ function createPanelApp(options = {}) {
9124
9702
  e.code = "RUNTIME_LINK_FAILED";
9125
9703
  throw e;
9126
9704
  }
9705
+ const runtimeEnv = runtimeEnvironment(paths, shared);
9706
+ if (runtimeEnv.pathPrepend.length) {
9707
+ const pathKey = Object.keys(process.env).find((key) => key.toUpperCase() === "PATH") || "PATH";
9708
+ runtimeEnv.env[pathKey] = [...runtimeEnv.pathPrepend, process.env[pathKey] || ""].filter(Boolean).join(path14.delimiter);
9709
+ }
9127
9710
  const running = await supervisor.start(agent, {
9128
9711
  engineRoot,
9129
9712
  panelCallbackUrl: publicBase ? `${publicBase}${basePath}/agents/progress` : void 0,
9130
9713
  panelCallbackToken: token,
9131
9714
  product: product ?? agent.id,
9132
9715
  canExport: entitled,
9133
- trial: !licensed && trialLeft > 0
9716
+ trial: !licensed && trialLeft > 0,
9717
+ extraEnv: { ...runtimeEnv.env, PANEL_MEMBER: licensed ? "1" : "0" },
9718
+ workspaceRoot: settings.workspaceRoot || void 0
9134
9719
  });
9135
9720
  started.set(agent.id, running);
9136
9721
  syncAgentSkills(agent);
9722
+ void reportUsage(product);
9137
9723
  return running;
9138
9724
  }
9725
+ function reportUsage(product) {
9726
+ if (!product || !license.canUseProduct(product)) return;
9727
+ const token = license.tokenFor(product);
9728
+ const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
9729
+ if (!token || !base) return;
9730
+ fetch(`${base}/v1/usage`, {
9731
+ method: "POST",
9732
+ headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
9733
+ body: "{}"
9734
+ }).catch(() => {
9735
+ });
9736
+ }
9139
9737
  function agentSummary(agent) {
9140
9738
  const product = productOf(agent);
9141
9739
  const lic = product ? license.statusFor(product) : license.status();
@@ -9151,6 +9749,7 @@ function createPanelApp(options = {}) {
9151
9749
  description: agent.manifest.description ?? null,
9152
9750
  previousVersion: agent.previousVersion,
9153
9751
  installedAt: agent.installedAt,
9752
+ broken: agentFilesBroken(agent),
9154
9753
  icon: agent.manifest.panel?.icon || `icon://${agent.id}`,
9155
9754
  accent: agent.manifest.panel?.accent ?? null,
9156
9755
  studio: agent.manifest.panel?.studio !== false,
@@ -9191,7 +9790,478 @@ function createPanelApp(options = {}) {
9191
9790
  queue.cancel(t.id);
9192
9791
  }
9193
9792
  }
9793
+ function memberInfo() {
9794
+ const rows = license.listProducts();
9795
+ const isOn = (status) => status && (status.state === "active" || status.state === "grace");
9796
+ const pick = rows.find((row) => row.product === "biupro" && isOn(row.status)) ?? null;
9797
+ const expiresAt = pick?.status?.expiresAt || null;
9798
+ const at2 = expiresAt ? Date.parse(expiresAt) : 0;
9799
+ return {
9800
+ active: !!isOn(pick?.status),
9801
+ product: pick?.product ?? null,
9802
+ expiresAt,
9803
+ daysLeft: at2 ? Math.max(0, Math.ceil((at2 - Date.now()) / 864e5)) : 0
9804
+ };
9805
+ }
9806
+ const DIAGNOSE_DIR = path14.join(paths.root, "diagnose");
9807
+ const GROWTH_DIR = path14.join(paths.root, "growth");
9808
+ const DIAGNOSE_MEDIA_DIR = path14.join(paths.root, "diagnose-media");
9809
+ const DIAGNOSE_SESSIONS_DIR = path14.join(paths.root, "diagnose-sessions");
9810
+ const DIAGNOSE_MAX_REPORTS = 60;
9811
+ const DIAGNOSE_MAX_UPLOAD = 300 * 1024 * 1024;
9812
+ const DIAGNOSE_IMAGE_EXT = /* @__PURE__ */ new Set([".jpg", ".jpeg", ".png", ".webp", ".gif", ".bmp", ".heic"]);
9813
+ const DIAGNOSE_VIDEO_EXT = /* @__PURE__ */ new Set([".mp4", ".mov", ".m4v", ".webm", ".avi", ".mkv"]);
9814
+ const DIAGNOSE_MEDIA_TYPES = /* @__PURE__ */ new Map([
9815
+ [".jpg", "image/jpeg"],
9816
+ [".jpeg", "image/jpeg"],
9817
+ [".png", "image/png"],
9818
+ [".webp", "image/webp"],
9819
+ [".gif", "image/gif"],
9820
+ [".bmp", "image/bmp"],
9821
+ [".heic", "image/heic"],
9822
+ [".mp4", "video/mp4"],
9823
+ [".m4v", "video/mp4"],
9824
+ [".mov", "video/quicktime"],
9825
+ [".webm", "video/webm"],
9826
+ [".avi", "video/x-msvideo"],
9827
+ [".mkv", "video/x-matroska"]
9828
+ ]);
9829
+ function assertDiagnoseMember() {
9830
+ const info = memberInfo();
9831
+ if (!info.active) throw Object.assign(new Error("\u53F7\u8109\u53CA\u589E\u957F\u80FD\u529B\u662F BiuPro \u4E13\u5C5E\u529F\u80FD\uFF0C\u8BF7\u5148\u5F00\u901A BiuPro"), { status: 403 });
9832
+ }
9833
+ async function saveDiagnoseUpload(req, query) {
9834
+ assertDiagnoseMember();
9835
+ const rawName = String(query.get("name") || "\u7D20\u6750").slice(0, 160);
9836
+ const ext = path14.extname(rawName).toLowerCase();
9837
+ const kind = DIAGNOSE_IMAGE_EXT.has(ext) ? "image" : DIAGNOSE_VIDEO_EXT.has(ext) ? "video" : "";
9838
+ if (!kind) throw Object.assign(new Error("\u53EA\u652F\u6301\u56FE\u7247\u6216\u89C6\u9891\uFF08jpg/png/webp/mp4/mov \u7B49\uFF09"), { status: 400 });
9839
+ const id = crypto8.randomUUID();
9840
+ const dir = path14.join(DIAGNOSE_MEDIA_DIR, id);
9841
+ fs14.mkdirSync(dir, { recursive: true });
9842
+ const file = path14.join(dir, `source${ext}`);
9843
+ const out = fs14.createWriteStream(file);
9844
+ let size = 0;
9845
+ try {
9846
+ for await (const chunk of req) {
9847
+ size += chunk.length;
9848
+ if (size > DIAGNOSE_MAX_UPLOAD) {
9849
+ throw Object.assign(new Error("\u6587\u4EF6\u592A\u5927\uFF0C\u5355\u4E2A\u7D20\u6750\u4E0A\u9650 300MB"), { status: 413 });
9850
+ }
9851
+ if (!out.write(chunk)) await once(out, "drain");
9852
+ }
9853
+ await new Promise((resolve, reject) => {
9854
+ out.once("error", reject);
9855
+ out.end(resolve);
9856
+ });
9857
+ await finished(out);
9858
+ } catch (error) {
9859
+ out.destroy();
9860
+ fs14.rmSync(dir, { recursive: true, force: true });
9861
+ throw error;
9862
+ }
9863
+ return {
9864
+ id,
9865
+ name: rawName,
9866
+ kind,
9867
+ size,
9868
+ mime: String(req.headers["content-type"] || "").split(";")[0] || DIAGNOSE_MEDIA_TYPES.get(ext) || "",
9869
+ url: `${basePath}/diagnose/media/${id}`,
9870
+ path: file
9871
+ };
9872
+ }
9873
+ function normalizeDiagnoseMedia(input) {
9874
+ const rows = Array.isArray(input) ? input : [];
9875
+ const out = [];
9876
+ for (const item of rows.slice(0, 12)) {
9877
+ const id = String(item?.id || "");
9878
+ if (!/^[0-9a-f-]{36}$/i.test(id)) continue;
9879
+ const dir = path14.join(DIAGNOSE_MEDIA_DIR, id);
9880
+ if (!fs14.existsSync(dir)) continue;
9881
+ const name2 = fs14.readdirSync(dir).find((entry) => entry.startsWith("source."));
9882
+ if (!name2) continue;
9883
+ const file = path14.join(dir, name2);
9884
+ const ext = path14.extname(name2).toLowerCase();
9885
+ out.push({
9886
+ id,
9887
+ name: String(item?.name || name2).slice(0, 120),
9888
+ kind: DIAGNOSE_IMAGE_EXT.has(ext) ? "image" : "video",
9889
+ size: Number(item?.size) || fs14.statSync(file).size,
9890
+ path: file
9891
+ });
9892
+ }
9893
+ return out;
9894
+ }
9895
+ function materializeDiagnoseMedia(projectPath, media) {
9896
+ if (!media.length) return [];
9897
+ const assetsDir = path14.join(projectPath, "assets");
9898
+ fs14.mkdirSync(assetsDir, { recursive: true });
9899
+ return media.map((item, index) => {
9900
+ const ext = path14.extname(item.path);
9901
+ const raw = String(item.name || path14.basename(item.path)).replace(/[^\w.\-]+/g, "_").slice(-60);
9902
+ const safe = raw || `media-${index + 1}${ext}`;
9903
+ const target = path14.join(assetsDir, `${String(index + 1).padStart(2, "0")}-${safe}`);
9904
+ if (!fs14.existsSync(target)) {
9905
+ try {
9906
+ fs14.linkSync(item.path, target);
9907
+ } catch {
9908
+ fs14.copyFileSync(item.path, target);
9909
+ }
9910
+ }
9911
+ return { ...item, path: target };
9912
+ });
9913
+ }
9914
+ function serveDiagnoseMedia(req, res, id) {
9915
+ assertDiagnoseMember();
9916
+ if (!/^[0-9a-f-]{36}$/i.test(id)) return send(res, 404, { error: "\u627E\u4E0D\u5230\u7D20\u6750" });
9917
+ const dir = path14.join(DIAGNOSE_MEDIA_DIR, id);
9918
+ if (!fs14.existsSync(dir)) return send(res, 404, { error: "\u627E\u4E0D\u5230\u7D20\u6750" });
9919
+ const name2 = fs14.readdirSync(dir).find((entry) => entry.startsWith("source."));
9920
+ if (!name2) return send(res, 404, { error: "\u627E\u4E0D\u5230\u7D20\u6750" });
9921
+ const file = path14.join(dir, name2);
9922
+ const type = DIAGNOSE_MEDIA_TYPES.get(path14.extname(name2).toLowerCase()) || "application/octet-stream";
9923
+ const stat = fs14.statSync(file);
9924
+ const headers = {
9925
+ "content-type": type,
9926
+ "accept-ranges": "bytes",
9927
+ "cache-control": "no-store"
9928
+ };
9929
+ const match = /^bytes=(\d+)-(\d*)$/.exec(String(req.headers.range || ""));
9930
+ if (match) {
9931
+ const start = Number(match[1]);
9932
+ const end = match[2] ? Math.min(Number(match[2]), stat.size - 1) : stat.size - 1;
9933
+ if (!Number.isFinite(start) || start > end || start >= stat.size) {
9934
+ res.writeHead(416, { "content-range": `bytes */${stat.size}` });
9935
+ return void res.end();
9936
+ }
9937
+ res.writeHead(206, { ...headers, "content-range": `bytes ${start}-${end}/${stat.size}`, "content-length": end - start + 1 });
9938
+ return void fs14.createReadStream(file, { start, end }).pipe(res);
9939
+ }
9940
+ res.writeHead(200, { ...headers, "content-length": stat.size });
9941
+ return void fs14.createReadStream(file).pipe(res);
9942
+ }
9943
+ function diagnoseReports() {
9944
+ if (!fs14.existsSync(DIAGNOSE_DIR)) return [];
9945
+ const rows = [];
9946
+ for (const name2 of fs14.readdirSync(DIAGNOSE_DIR)) {
9947
+ if (!/^[a-zA-Z0-9-]{8,64}\.json$/.test(name2)) continue;
9948
+ try {
9949
+ const item = JSON.parse(fs14.readFileSync(path14.join(DIAGNOSE_DIR, name2), "utf8"));
9950
+ if (item?.id && item?.snapshot) rows.push(item);
9951
+ } catch {
9952
+ }
9953
+ }
9954
+ return rows.sort((a, b2) => String(b2.createdAt || "").localeCompare(String(a.createdAt || "")));
9955
+ }
9956
+ function saveDiagnoseReport(snapshot, analysis, sessionId, extra = {}) {
9957
+ const text = String(analysis || "").slice(0, 2e4);
9958
+ const media = (Array.isArray(extra.media) ? extra.media : []).slice(0, 12).map((item) => ({
9959
+ id: String(item.id || ""),
9960
+ name: String(item.name || "").slice(0, 120),
9961
+ kind: item.kind === "video" ? "video" : "image",
9962
+ size: Number(item.size) || 0
9963
+ }));
9964
+ const record = {
9965
+ id: crypto8.randomUUID(),
9966
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
9967
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
9968
+ title: String(snapshot.title || snapshot.description || "\u672A\u547D\u540D\u8BCA\u65AD").slice(0, 80),
9969
+ snapshot,
9970
+ analysis: text,
9971
+ sessionId: String(sessionId || "").slice(0, 80),
9972
+ projectPath: String(extra.projectPath || "").slice(0, 400),
9973
+ media
9974
+ };
9975
+ const raw = JSON.stringify(record);
9976
+ if (Buffer.byteLength(raw) > 128 * 1024) {
9977
+ throw Object.assign(new Error("\u62A5\u544A\u592A\u5927\uFF0C\u4FDD\u5B58\u5931\u8D25"), { status: 413 });
9978
+ }
9979
+ fs14.mkdirSync(DIAGNOSE_DIR, { recursive: true });
9980
+ fs14.writeFileSync(path14.join(DIAGNOSE_DIR, `${record.id}.json`), raw, "utf8");
9981
+ for (const old of diagnoseReports().slice(DIAGNOSE_MAX_REPORTS)) {
9982
+ try {
9983
+ fs14.rmSync(path14.join(DIAGNOSE_DIR, `${old.id}.json`), { force: true });
9984
+ } catch {
9985
+ }
9986
+ }
9987
+ return record;
9988
+ }
9989
+ function diagnosePrompt(snapshot, opts = {}) {
9990
+ const data = snapshot || {};
9991
+ const stats = data.stats || {};
9992
+ const statLine = [
9993
+ stats.likes != null ? `\u70B9\u8D5E ${stats.likes}` : "",
9994
+ stats.comments != null ? `\u8BC4\u8BBA ${stats.comments}` : "",
9995
+ stats.collects != null ? `\u6536\u85CF ${stats.collects}` : "",
9996
+ stats.shares != null ? `\u8F6C\u53D1 ${stats.shares}` : "",
9997
+ stats.followers != null ? `\u7C89\u4E1D ${stats.followers}` : "",
9998
+ stats.works != null ? `\u4F5C\u54C1 ${stats.works}` : ""
9999
+ ].filter(Boolean).join(" \xB7 ");
10000
+ const media = Array.isArray(opts.media) ? opts.media : [];
10001
+ const projectPath = String(opts.projectPath || "");
10002
+ const skillPath = String(opts.skillPath || "");
10003
+ const hasVideo = media.some((item) => item.kind === "video");
10004
+ return [
10005
+ "\u8BF7\u6267\u884C\u4E00\u6B21\u300C\u6296\u97F3\u8D26\u53F7\u8BCA\u65AD\u300D\u3002\u8FD9\u662F\u8D26\u53F7\u7EA7\u6570\u636E\u8BCA\u65AD\uFF0C\u4E0D\u8981\u9000\u5316\u4E3A\u5355\u6761\u89C6\u9891\u70B9\u8BC4\u3002",
10006
+ projectPath ? `\u9879\u76EE\u76EE\u5F55\uFF1A${projectPath}` : "",
10007
+ skillPath ? `\u8BCA\u65AD\u6280\u80FD\u76EE\u5F55\uFF1A${skillPath}` : "",
10008
+ "\u5F00\u59CB\u524D\u5FC5\u987B\u5B8C\u6574\u9605\u8BFB\u6280\u80FD\u76EE\u5F55\u4E2D\u7684 SKILL.md\uFF0C\u5E76\u4E25\u683C\u9075\u5FAA\u5176\u4E2D\u7684\u6267\u884C\u6D41\u7A0B\u3001\u786C\u6027\u89C4\u5219\u548C\u8D28\u91CF\u81EA\u68C0\u6E05\u5355\u3002\u5FC5\u987B\u540C\u65F6\u8BFB\u53D6 references/diagnosis-framework.md\u3001references/prescription-library.md \u548C assets/report-template.md\uFF1B\u5904\u65B9\u53EA\u80FD\u4F7F\u7528\u8BE5\u5904\u65B9\u5E93\u4E2D\u53EF\u6EAF\u6E90\u7684\u6765\u6E90\uFF0C\u4E0D\u5F97\u81EA\u884C\u7F16\u9020\u51FA\u5904\u3002",
10009
+ "",
10010
+ media.length ? "\u7528\u6237\u4E0A\u4F20\u7684\u7D20\u6750\uFF1A" : "\u7528\u6237\u6CA1\u6709\u4E0A\u4F20\u7D20\u6750\uFF0C\u53EA\u80FD\u4F7F\u7528\u4E0B\u65B9\u8865\u5145\u4FE1\u606F\uFF1B\u4E0D\u8981\u56E0\u6B64\u7F16\u9020\u8D26\u53F7\u6570\u636E\u3002",
10011
+ ...media.map((item, index) => `${index + 1}. ${item.kind === "video" ? "\u89C6\u9891" : "\u56FE\u7247"}\uFF1A${item.path}`),
10012
+ media.some((item) => item.kind === "image") ? "\u540E\u53F0\u622A\u56FE\u5FC5\u987B\u9010\u5F20\u76F4\u63A5\u67E5\u770B\u3002\u5148\u63D0\u53D6\u4F5C\u54C1\u6807\u9898\u3001\u53D1\u5E03\u65F6\u95F4\u3001\u64AD\u653E\u3001\u70B9\u8D5E\u3001\u8BC4\u8BBA\u3001\u5206\u4EAB\u3001\u7C89\u4E1D\u7B49\u6240\u6709\u53EF\u8BFB\u6570\u636E\uFF0C\u518D\u9010\u9879\u6807\u6CE8\u300C\u4E8B\u5B9E / \u4F4E\u7F6E\u4FE1 / \u7F3A\u5931\u300D\uFF1B\u6A21\u7CCA\u8BFB\u6570\u4E0D\u5F97\u5F53\u4E8B\u5B9E\u3002" : "",
10013
+ hasVideo ? `\u89C6\u9891\u4E0D\u8981\u51ED\u7A7A\u731C\u5185\u5BB9\uFF1A\u5148\u7528 ffprobe \u8BFB\u65F6\u957F\uFF0C\u518D\u7528 ffmpeg \u62BD 6-9 \u5F20\u5173\u952E\u5E27\u5230\u9879\u76EE\u76EE\u5F55 frames/\uFF0C\u7136\u540E\u76F4\u63A5\u67E5\u770B\u8FD9\u4E9B\u5E27\u3002\u4F8B\u5982\uFF1Affmpeg -i "<\u89C6\u9891\u8DEF\u5F84>" -vf "fps=1/2,scale=720:-1" frames/f%03d.jpg\uFF1B\u955C\u5934\u53D8\u5316\u5927\u65F6\u53EF\u7528 -vf "select='gt(scene,0.3)',scale=720:-1" -vsync vfr\u3002\u9700\u8981\u53E3\u64AD\u65F6\u518D\u62BD\u97F3\u9891\uFF1Bffmpeg \u4E0D\u53EF\u7528\u5C31\u6362\u4F60\u80FD\u7528\u7684\u672C\u5730\u5DE5\u5177\uFF0C\u5E76\u8BF4\u660E\u3002\u89C6\u9891\u53EA\u80FD\u4F5C\u4E3A\u5185\u5BB9\u516C\u5F0F\u7B49\u7EF4\u5EA6\u7684\u8BC1\u636E\uFF0C\u4E0D\u80FD\u66FF\u4EE3\u8D26\u53F7\u540E\u53F0\u4F5C\u54C1\u6570\u636E\u3002` : "",
10014
+ "",
10015
+ data.author ? `\u4F5C\u8005 / \u8D26\u53F7\uFF1A${data.author}${data.authorId ? `\uFF08${data.authorId}\uFF09` : ""}` : "",
10016
+ data.music ? `\u914D\u4E50\uFF1A${data.music}` : "",
10017
+ statLine ? `\u5DF2\u63D0\u4F9B\u6570\u636E\uFF1A${statLine}` : "",
10018
+ data.notice ? `\u8BFB\u53D6\u63D0\u793A\uFF1A${data.notice}` : "",
10019
+ "",
10020
+ "\u7528\u6237\u8865\u5145\u7684\u6587\u6848\u3001\u6570\u636E\u6216\u8BCA\u65AD\u8BC9\u6C42\uFF1A",
10021
+ String(data.text || data.description || "").slice(0, 6e3) || "\uFF08\u65E0\uFF09",
10022
+ "",
10023
+ "\u4E25\u683C\u6309\u7167 assets/report-template.md \u8F93\u51FA\u5B8C\u6574\u8D26\u53F7\u8BCA\u65AD\u62A5\u544A\uFF0C\u4E0D\u9650\u5236\u4E3A\u7B80\u77ED\u70B9\u8BC4\u3002\u81F3\u5C11\u843D\u5B9E\uFF1A\u4E0D\u8D85\u8FC7 3 \u53E5\u7684\u4E00\u53E5\u8BDD\u7ED3\u8BBA\u3001\u6570\u636E\u4E8B\u5B9E\u4E0E\u7F6E\u4FE1\u5EA6\u3001\u57FA\u7EBF\u6307\u6807\u3001\u5C0F\u65F6\u7EA7\u53D1\u5E03\u65F6\u6BB5\u5206\u6790\u3001\u56DB\u7EF4\u8BCA\u65AD\u3001\u5185\u5BB9\u7C7B\u578B\u5224\u65AD\u3001\u56DB\u8981\u7D20\u9F50\u5168\u4E14\u6709\u51FA\u5904\u7684\u4F18\u5316\u5904\u65B9\u300130 \u5929\u53EF\u9A8C\u6536\u6307\u6807\u3001\u5F85\u8865\u8F93\u5165\u6E05\u5355\u3001\u8FED\u4EE3\u8BB0\u5F55\u3001\u65B9\u6CD5\u8BBA\u6765\u6E90\u6E05\u5355\u3002",
10024
+ "\u4F5C\u54C1\u5217\u8868\u4E0D\u8DB3 5 \u6761\u6216\u5B57\u6BB5\u4E0D\u5168\u65F6\u4ECD\u5148\u8BCA\u65AD\uFF0C\u4F46\u5FC5\u987B\u5728\u300A\u5F85\u8865\u8F93\u5165\u6E05\u5355\u300B\u8BF4\u660E\u5F71\u54CD\uFF1B\u6837\u672C\u4E0D\u8DB3\u4E0D\u5F97\u5F52\u56E0\uFF0C\u6309 SOP \u7ED9\u51FA\u63A7\u5236\u53D8\u91CF\u7684 A/B \u6D4B\u8BD5\u3002\u4E0D\u8981\u8F93\u51FA\u201C\u591A\u53D1\u4F18\u8D28\u5185\u5BB9\u201D\u7B49\u65E0\u51FA\u5904\u5EFA\u8BAE\u3002",
10025
+ "\u6807\u9898\u548C\u6587\u5B57\u8F6C\u5F55\u53EA\u80FD\u8BC1\u660E\u4E3B\u9898\uFF0C\u4E0D\u80FD\u8BC1\u660E\u53E3\u64AD\u3001\u5267\u60C5\u3001\u5B9E\u9645\u5F00\u573A\u6216\u955C\u5934\u8868\u73B0\uFF1B\u5355\u6761\u89C6\u9891\u4E5F\u4E0D\u80FD\u4EE3\u8868\u5168\u90E8\u4F5C\u54C1\u3002\u4F5C\u54C1\u5F62\u6001\u7F3A\u5931\u65F6\uFF0C\u5185\u5BB9\u7C7B\u578B\u53EA\u80FD\u6807\u4E3A\u300C\u6309\u4E3B\u9898\u6682\u5B9A / \u5F62\u6001\u5F85\u9A8C\u8BC1\u300D\uFF0C\u7C7B\u578B\u9650\u5B9A\u5904\u65B9\u53EA\u80FD\u6761\u4EF6\u9002\u7528\uFF0C\u5E76\u628A\u6240\u7F3A\u8BC1\u636E\u5217\u5165\u5F85\u8865\u8F93\u5165\u3002",
10026
+ "\u6807\u9898\u4E2D\u7684\u5E74\u9F84\u3001\u8EAB\u4EFD\u3001\u804C\u4E1A\u3001\u7ECF\u5386\u7B49\u5B57\u9762\u4FE1\u606F\u53EF\u6309\u7F6E\u4FE1\u5EA6\u5F15\u7528\uFF0C\u4F46\u4E0D\u5F97\u6269\u5C55\u6210\u672A\u63D0\u4F9B\u7684\u80CC\u666F\u6545\u4E8B\uFF1B\u5185\u5BB9\u7EBF\u53EA\u80FD\u6309\u5DF2\u6709\u8BC1\u636E\u79F0\u4E3A\u4E3B\u9898 / \u9009\u9898\u7EBF\uFF0C\u4E0D\u80FD\u51ED\u6807\u9898\u5224\u5B9A\u53D9\u4E8B\u5F62\u6001\uFF0C\u793A\u4F8B\u4E3B\u7EBF\u540C\u6837\u4E0D\u5F97\u65B0\u589E\u4EBA\u7269\u7ECF\u5386\u3002",
10027
+ "\u300C\u51E0\u4E4E\u4E3A 0\u300D\u300C\u7EA6\u300D\u7B49\u6982\u8FF0\u4E0D\u662F\u7CBE\u786E\u6570\u503C\u3002\u5047\u8BBE\u60C5\u666F\u8BA1\u7B97\u4E0D\u5F97\u5199\u6210\u4E0A\u754C\u3001\u4E0B\u754C\u6216\u9608\u503C\u5224\u5B9A\u8BC1\u636E\uFF1B\u4E92\u52A8\u7ED3\u679C\u4E0E\u4E92\u52A8\u8BBE\u8BA1\u539F\u56E0\u5FC5\u987B\u5206\u5F00\uFF0C\u8BC1\u636E\u4E0D\u8DB3\u5C31\u6807\u300C\u8BC1\u636E\u4E0D\u5B8C\u6574\u300D\u3002",
10028
+ "A/B \u6D4B\u8BD5\u6BCF\u7EC4 \u22653 \u6761\u4EC5\u7528\u4E8E\u65B9\u5411\u6027\u89C2\u5BDF\uFF0C\u4E0D\u5F97\u636E\u6B64\u8BC1\u660E\u300C\u65F6\u6BB5\u5047\u8BBE\u6210\u7ACB\u300D\u6216\u300C\u65E0\u65F6\u6BB5\u6548\u5E94\u300D\uFF1B\u8FBE\u5230\u6700\u4F4E\u6761\u6570\u4E5F\u4E0D\u7B49\u4E8E\u53EF\u4EE5\u5F52\u56E0\uFF0C\u65F6\u523B\u7CBE\u5EA6\u4E0D\u8DB3\u3001\u4E3B\u9898\u6DF7\u6742\u6216\u63A7\u5236\u53D8\u91CF\u4E0D\u6210\u7ACB\u65F6\u4ECD\u987B\u7EE7\u7EED\u6269\u6837\u3002",
10029
+ "\u6240\u6709\u6D4B\u8BD5\u4E0E\u680F\u76EE\u5FC5\u987B\u505A 30 \u5929\u4EA7\u80FD\u6838\u7B97\uFF1A\u6392\u671F\u6761\u6570\u4E0E\u66F4\u65B0\u9891\u7387\u4E00\u81F4\uFF0C\u4E0D\u540C\u5185\u5BB9\u7C7B\u578B\u4E0D\u5F97\u91CD\u590D\u8BA1\u6570\uFF1B\u5F53\u524D\u4EA7\u80FD\u653E\u4E0D\u4E0B\u65F6\uFF0C\u628A\u9A8C\u8BC1\u7A97\u53E3\u5EF6\u4F38\u5230 60 \u5929\uFF0C\u4E0D\u5F97\u4FDD\u7559\u4E92\u76F8\u51B2\u7A81\u7684\u6570\u91CF\u76EE\u6807\u3002",
10030
+ "\u5E73\u5747\u64AD\u653E\u65F6\u957F\u3001\u5B8C\u64AD\u7387\u300130 \u79D2\u7559\u5B58\u7B49\u5B57\u6BB5\u5404\u81EA\u72EC\u7ACB\uFF0C\u53EA\u8BB0\u5F55\u540E\u53F0\u5B9E\u9645\u63D0\u4F9B\u7684\u5B57\u6BB5\uFF0C\u4E0D\u5F97\u76F8\u4E92\u6362\u7B97\u6216\u865A\u6784\u6307\u6807\u3002\u81EA\u8BBE\u9636\u6BB5\u76EE\u6807\u5FC5\u987B\u6807\u660E\u4E3A\u8D26\u53F7\u7BA1\u7406\u76EE\u6807\uFF0C\u4E0D\u5F97\u5199\u6210\u5BF9\u9F50\u672A\u63D0\u4F9B\u7684\u5B98\u65B9\u6216\u540C\u7C7B\u53C2\u8003\u503C\u3002",
10031
+ "\u65B9\u6CD5\u8BBA\u6765\u6E90\u6E05\u5355\u53EA\u5217\u5904\u65B9\u5E93\u6765\u6E90\u6E05\u5355\u4E2D\u7684\u5B9E\u9645\u5F15\u7528\u9879\uFF1B\u4E0D\u5F97\u65B0\u589E\u300C\u6D41\u91CF\u6C60\u673A\u5236\u300D\u7B49\u65E0\u72EC\u7ACB\u51FA\u5904\u6761\u76EE\uFF0C\u4E5F\u4E0D\u5F97\u628A\u9AD8\u64AD\u653E\u89E3\u91CA\u6210\u5DF2\u8BC1\u5B9E\u7684\u5E73\u53F0\u673A\u5236\u3002",
10032
+ "\u4EA4\u4ED8\u524D\u9010\u9879\u6267\u884C SKILL.md \u7684\u8D28\u91CF\u81EA\u68C0\u6E05\u5355\uFF1B\u53D1\u73B0\u7F3A\u9879\u5148\u4FEE\u6B63\uFF0C\u518D\u4FDD\u5B58\u3002\u53EA\u6839\u636E\u7D20\u6750\u548C\u5DF2\u63D0\u4F9B\u4FE1\u606F\u5224\u65AD\uFF0C\u4E0D\u7F16\u9020\u753B\u9762\u3001\u6570\u5B57\u3001\u4F5C\u8005\u80CC\u666F\u6216\u5E73\u53F0\u673A\u5236\u3002",
10033
+ projectPath ? `\u5B8C\u6210\u540E\u628A\u6700\u7EC8\u5B8C\u6574\u62A5\u544A\u5199\u5165 ${projectPath}/report.md\uFF08UTF-8\u3001\u8986\u76D6\u5199\uFF09\uFF0C\u7136\u540E\u56DE\u590D\u300C\u5DF2\u5199\u5165 report.md\u300D\u3002` : "",
10034
+ media.length ? "\u4E0D\u8981\u4FEE\u6539\u6216\u5220\u9664\u7528\u6237\u4E0A\u4F20\u7684\u7D20\u6750\u3002" : ""
10035
+ ].join("\n").replace(/\n{3,}/g, "\n\n");
10036
+ }
10037
+ function growthError(message, status = 400) {
10038
+ return Object.assign(new Error(message), { status });
10039
+ }
10040
+ function growthKind(value) {
10041
+ const kind = String(value || "");
10042
+ if (!Object.hasOwn(GROWTH_LABELS, kind)) throw growthError("\u672A\u77E5\u7684\u8D26\u53F7\u589E\u957F\u529F\u80FD");
10043
+ return kind;
10044
+ }
10045
+ function growthRecordId(value) {
10046
+ const id = String(value || "");
10047
+ if (!/^[0-9a-f-]{36}$/i.test(id)) throw growthError("\u6863\u6848 ID \u65E0\u6548");
10048
+ return id;
10049
+ }
10050
+ function cleanGrowthInput(kind, raw) {
10051
+ const source = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
10052
+ const text = (key, max) => String(source[key] || "").slice(0, max);
10053
+ if (kind === "research") {
10054
+ return {
10055
+ accounts: text("accounts", 1e3),
10056
+ links: text("links", 4e3),
10057
+ positioning: text("positioning", 4e3),
10058
+ notes: text("notes", 6e3)
10059
+ };
10060
+ }
10061
+ if (kind === "planner") {
10062
+ const startDate = text("startDate", 10);
10063
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(startDate)) throw growthError("\u8BF7\u9009\u62E9\u6709\u6548\u7684\u5F00\u59CB\u65E5\u671F");
10064
+ const frequency = Number(source.frequency ?? 3);
10065
+ if (!Number.isInteger(frequency) || frequency < 1 || frequency > 14) throw growthError("\u6BCF\u5468\u53D1\u5E03\u4E0A\u9650\u987B\u4E3A 1\u201314 \u6761");
10066
+ return {
10067
+ diagnosisId: text("diagnosisId", 80),
10068
+ positioning: text("positioning", 4e3),
10069
+ startDate,
10070
+ frequency,
10071
+ notes: text("notes", 6e3)
10072
+ };
10073
+ }
10074
+ return { baselineId: text("baselineId", 80), currentId: text("currentId", 80), notes: text("notes", 6e3) };
10075
+ }
10076
+ function requireDiagnosisReport(id) {
10077
+ if (!/^[0-9a-f-]{36}$/i.test(String(id || ""))) throw growthError("\u4F53\u68C0\u62A5\u544A ID \u65E0\u6548");
10078
+ const report = diagnoseReports().find((item) => item.id === id);
10079
+ if (!report || !String(report.analysis || "").trim()) throw growthError("\u627E\u4E0D\u5230\u5DF2\u5B8C\u6210\u7684\u4F53\u68C0\u62A5\u544A\uFF0C\u8BF7\u5148\u56DE\u586B\u62A5\u544A");
10080
+ return report;
10081
+ }
10082
+ function growthLinksFromInput(kind, input) {
10083
+ if (kind === "planner") return { diagnosisId: input.diagnosisId || "" };
10084
+ if (kind === "followup") return { baselineId: input.baselineId || "", currentId: input.currentId || "" };
10085
+ return {};
10086
+ }
10087
+ function growthRecordTitle(kind, input) {
10088
+ if (kind === "research") return `${input.accounts.split(/[,,\n]/).map((x) => x.trim()).filter(Boolean)[0] || "\u5BF9\u6807\u8D26\u53F7"} \xB7 \u5BF9\u6807\u8C03\u7814`;
10089
+ if (kind === "planner") {
10090
+ const diagnosis = input.diagnosisId ? diagnoseReports().find((item) => item.id === input.diagnosisId) : null;
10091
+ return `${diagnosis?.title || input.positioning || "\u8D26\u53F7"} \xB7 \u9009\u9898\u89C4\u5212`.slice(0, 100);
10092
+ }
10093
+ const current = input.currentId ? diagnoseReports().find((item) => item.id === input.currentId) : null;
10094
+ return `${current?.title || "\u8D26\u53F7"} \xB7 \u590D\u8BCA\u5BF9\u6BD4`.slice(0, 100);
10095
+ }
10096
+ function growthRecords(kind) {
10097
+ const dir = path14.join(GROWTH_DIR, kind);
10098
+ if (!fs14.existsSync(dir)) return [];
10099
+ const rows = [];
10100
+ for (const name2 of fs14.readdirSync(dir)) {
10101
+ if (!/^[0-9a-f-]{36}\.json$/i.test(name2)) continue;
10102
+ try {
10103
+ const item = JSON.parse(fs14.readFileSync(path14.join(dir, name2), "utf8"));
10104
+ if (item?.id && item?.kind === kind) rows.push(item);
10105
+ } catch {
10106
+ }
10107
+ }
10108
+ return rows.sort((a, b2) => String(b2.createdAt || "").localeCompare(String(a.createdAt || "")));
10109
+ }
10110
+ function findGrowthRecord({ kind = "", id = "", sessionId = "" } = {}) {
10111
+ const kinds = kind ? [growthKind(kind)] : Object.keys(GROWTH_LABELS);
10112
+ for (const itemKind of kinds) {
10113
+ const hit = growthRecords(itemKind).find((item) => id && item.id === id || sessionId && item.sessionId === sessionId);
10114
+ if (hit) return hit;
10115
+ }
10116
+ return null;
10117
+ }
10118
+ function writeGrowthRecord(record) {
10119
+ const raw = JSON.stringify(record);
10120
+ if (Buffer.byteLength(raw) > 128 * 1024) throw growthError("\u62A5\u544A\u592A\u5927\uFF0C\u4FDD\u5B58\u5931\u8D25", 413);
10121
+ const dir = path14.join(GROWTH_DIR, record.kind);
10122
+ fs14.mkdirSync(dir, { recursive: true });
10123
+ const target = path14.join(dir, `${record.id}.json`);
10124
+ const temp = `${target}.tmp`;
10125
+ fs14.writeFileSync(temp, raw, "utf8");
10126
+ fs14.renameSync(temp, target);
10127
+ for (const old of growthRecords(record.kind).slice(60)) {
10128
+ try {
10129
+ fs14.rmSync(path14.join(dir, `${old.id}.json`), { force: true });
10130
+ } catch {
10131
+ }
10132
+ }
10133
+ return record;
10134
+ }
10135
+ function createGrowthRecord(kind, input, extra = {}) {
10136
+ const now = (/* @__PURE__ */ new Date()).toISOString();
10137
+ return writeGrowthRecord({
10138
+ id: crypto8.randomUUID(),
10139
+ kind,
10140
+ title: growthRecordTitle(kind, input),
10141
+ createdAt: now,
10142
+ updatedAt: now,
10143
+ input,
10144
+ analysis: String(extra.analysis || "").slice(0, 4e4),
10145
+ sessionId: String(extra.sessionId || "").slice(0, 100),
10146
+ projectPath: String(extra.projectPath || "").slice(0, 400),
10147
+ media: Array.isArray(extra.media) ? extra.media : [],
10148
+ links: growthLinksFromInput(kind, input)
10149
+ });
10150
+ }
10151
+ function diagnosisContext(report) {
10152
+ return [
10153
+ `# ${report.title || "\u8D26\u53F7\u4F53\u68C0"}`,
10154
+ `\u4F53\u68C0\u65F6\u95F4\uFF1A${report.createdAt || "\u672A\u8BB0\u5F55"}`,
10155
+ `\u8D26\u53F7\u5FEB\u7167\uFF1A${JSON.stringify(report.snapshot || {}).slice(0, 12e3)}`,
10156
+ "",
10157
+ String(report.analysis || "")
10158
+ ].join("\n");
10159
+ }
10160
+ function resolveGrowthContext(kind, input) {
10161
+ if (kind === "research") {
10162
+ if (!String(input.accounts || "").trim()) throw growthError("\u8BF7\u586B\u5199\u81F3\u5C11\u4E00\u4E2A\u5BF9\u6807\u8D26\u53F7\u540D");
10163
+ return {};
10164
+ }
10165
+ if (kind === "planner") {
10166
+ const diagnosis = input.diagnosisId ? requireDiagnosisReport(input.diagnosisId) : null;
10167
+ if (!diagnosis && !String(input.positioning || "").trim()) {
10168
+ throw growthError("\u8BF7\u9009\u62E9\u4F53\u68C0\u62A5\u544A\uFF0C\u6216\u586B\u5199\u8D26\u53F7\u5B9A\u4F4D");
10169
+ }
10170
+ return { diagnosis };
10171
+ }
10172
+ if (!input.baselineId || !input.currentId) throw growthError("\u8BF7\u9009\u62E9\u57FA\u7EBF\u4F53\u68C0\u548C\u672C\u6B21\u4F53\u68C0");
10173
+ if (input.baselineId === input.currentId) throw growthError("\u590D\u8BCA\u9700\u8981\u9009\u62E9\u4E24\u4EFD\u4E0D\u540C\u7684\u4F53\u68C0\u62A5\u544A");
10174
+ return {
10175
+ baseline: requireDiagnosisReport(input.baselineId),
10176
+ current: requireDiagnosisReport(input.currentId)
10177
+ };
10178
+ }
10179
+ function safeReportPath(projectPath) {
10180
+ const root = path14.resolve(DIAGNOSE_SESSIONS_DIR);
10181
+ const dir = path14.resolve(String(projectPath || ""));
10182
+ if (!dir.startsWith(root + path14.sep)) return null;
10183
+ return path14.join(dir, "report.md");
10184
+ }
10185
+ function growthPrompt(kind, input, media = [], linked = {}) {
10186
+ const projectPath = String(linked.projectPath || "");
10187
+ const skillPath = String(linked.skillPath || "");
10188
+ const common = [
10189
+ projectPath ? `\u9879\u76EE\u76EE\u5F55\uFF1A${projectPath}` : "",
10190
+ skillPath ? `\u6280\u80FD\u76EE\u5F55\uFF1A${skillPath}` : "",
10191
+ "\u5F00\u59CB\u524D\u5FC5\u987B\u5B8C\u6574\u9605\u8BFB\u4E0A\u8FF0\u6280\u80FD\u76EE\u5F55\u4E2D\u7684 SKILL.md\uFF0C\u4E25\u683C\u6267\u884C\u5176\u4E2D\u7684\u6D41\u7A0B\u3001\u786C\u6027\u89C4\u5219\u548C\u8D28\u91CF\u81EA\u68C0\u6E05\u5355\u3002",
10192
+ "\u53EA\u4F7F\u7528\u672C\u673A\u7D20\u6750\u3001\u7528\u6237\u8F93\u5165\u548C\u5B9E\u9645\u53EF\u8BBF\u95EE\u7684\u516C\u5F00\u4FE1\u606F\uFF1B\u4E0D\u5F97\u7F16\u9020\u6570\u636E\u3001\u4F5C\u54C1\u3001\u4EBA\u7269\u7ECF\u5386\u3001\u6765\u6E90\u6216\u5E73\u53F0\u673A\u5236\u3002",
10193
+ projectPath ? `\u5B8C\u6210\u540E\u628A\u6700\u7EC8\u5B8C\u6574\u62A5\u544A\u5199\u5165 ${projectPath}/report.md\uFF08UTF-8\u3001\u8986\u76D6\u5199\uFF09\uFF0C\u7136\u540E\u56DE\u590D\u300C\u5DF2\u5199\u5165 report.md\u300D\u3002` : "",
10194
+ media.length ? "\u4E0D\u8981\u4FEE\u6539\u6216\u5220\u9664\u7528\u6237\u4E0A\u4F20\u7684\u7D20\u6750\u3002" : ""
10195
+ ];
10196
+ if (kind === "research") {
10197
+ return [
10198
+ "\u8BF7\u6267\u884C\u4E00\u6B21\u72EC\u7ACB\u7684\u300C\u6296\u97F3\u5BF9\u6807\u8C03\u7814\u300D\uFF0C\u76EE\u6807\u662F\u63D0\u70BC\u53EF\u8FC1\u79FB\u7684\u5185\u5BB9\u7ED3\u6784\uFF0C\u4E0D\u662F\u5199\u8D26\u53F7\u7B80\u4ECB\u6216\u4E3B\u89C2\u5938\u8D5E\u3002",
10199
+ ...common.slice(0, 3),
10200
+ "\u540C\u65F6\u5B8C\u6574\u9605\u8BFB references/research-checklist.md\uFF0C\u5E76\u6309\u5176\u9010\u9879\u6838\u67E5\u3002",
10201
+ "",
10202
+ `\u5BF9\u6807\u8D26\u53F7\uFF1A${input.accounts}`,
10203
+ `\u4E3B\u9875\u6216\u4F5C\u54C1\u94FE\u63A5\uFF1A${input.links || "\uFF08\u672A\u63D0\u4F9B\uFF09"}`,
10204
+ `\u7528\u6237\u81EA\u5DF1\u7684\u8D26\u53F7\u5B9A\u4F4D\uFF1A${input.positioning || "\uFF08\u672A\u63D0\u4F9B\uFF1B\u53EF\u8FC1\u79FB\u6027\u53EA\u80FD\u6807\u4E3A\u5F85\u5224\u65AD\uFF09"}`,
10205
+ `\u8865\u5145\u8BF4\u660E\u4E0E\u771F\u5B9E\u8D44\u6E90\uFF1A${input.notes || "\uFF08\u65E0\uFF09"}`,
10206
+ "",
10207
+ media.length ? "\u7528\u6237\u4E0A\u4F20\u7684\u672C\u673A\u7D20\u6750\uFF1A" : "\u7528\u6237\u6CA1\u6709\u4E0A\u4F20\u622A\u56FE\u6216\u89C6\u9891\uFF1B\u4E0D\u5F97\u865A\u6784\u4F5C\u54C1\u5217\u8868\u548C\u4F5C\u54C1\u6570\u636E\u3002",
10208
+ ...media.map((item, index) => `${index + 1}. ${item.kind === "video" ? "\u89C6\u9891" : "\u56FE\u7247"}\uFF1A${item.path}`),
10209
+ media.some((item) => item.kind === "image") ? "\u6BCF\u5F20\u56FE\u7247\u90FD\u5FC5\u987B\u9010\u5F20\u76F4\u63A5\u67E5\u770B\uFF0C\u63D0\u53D6\u8D26\u53F7\u540D\u3001\u4F5C\u54C1\u6807\u9898\u3001\u53D1\u5E03\u65F6\u95F4\u548C\u53EF\u89C1\u4E92\u52A8\u6570\u636E\uFF0C\u5E76\u6807\u6CE8\u300C\u4E8B\u5B9E / \u4F4E\u7F6E\u4FE1 / \u7F3A\u5931\u300D\u3002" : "",
10210
+ media.some((item) => item.kind === "video") ? "\u6BCF\u4E2A\u89C6\u9891\u5148\u7528 ffprobe \u8BFB\u53D6\u65F6\u957F\uFF0C\u518D\u7528 ffmpeg \u62BD\u53D6 6\u20139 \u5F20\u5173\u952E\u5E27\u5230\u9879\u76EE\u76EE\u5F55 frames/ \u5E76\u9010\u5F20\u67E5\u770B\uFF1B\u9700\u8981\u53E3\u64AD\u8BC1\u636E\u65F6\u518D\u62BD\u97F3\u9891\u3002\u5DE5\u5177\u4E0D\u53EF\u7528\u65F6\u8BF4\u660E\u9650\u5236\uFF0C\u4E0D\u5F97\u731C\u753B\u9762\u3002" : "",
10211
+ "\u5982\u679C\u5177\u5907\u8054\u7F51\u6216\u7F51\u9875\u8BFB\u53D6\u80FD\u529B\uFF0C\u53EF\u8BBF\u95EE\u7528\u6237\u7ED9\u51FA\u7684\u94FE\u63A5\u5E76\u6838\u5B9E\u516C\u5F00\u62A5\u9053\u3001\u8BBF\u8C08\u548C\u672C\u4EBA\u516C\u5F00\u65B9\u6CD5\u8BBA\uFF0C\u9010\u6761\u9644 URL \u4E0E\u53D1\u5E03\u65E5\u671F\uFF1B\u6CA1\u6709\u8054\u7F51\u3001\u8BBF\u95EE\u5931\u8D25\u6216\u53EA\u6709\u8D26\u53F7\u540D\u65F6\uFF0C\u660E\u786E\u5199\u300C\u672C\u6B21\u672A\u6838\u5B9E\u516C\u5F00\u4FE1\u606F\u300D\uFF0C\u4E0D\u5F97\u5047\u88C5\u68C0\u7D22\u8FC7\u3002",
10212
+ "\u4E25\u683C\u533A\u5206\u300C\u516C\u5F00\u4FE1\u606F\uFF08\u9644\u6765\u6E90\u4E0E\u65F6\u95F4\uFF09/ \u4F5C\u54C1\u53EF\u89C1\u4E8B\u5B9E / \u63A8\u65AD / \u672A\u8BC1\u5B9E\u300D\u3002\u770B\u4E0D\u5230\u7684\u540E\u53F0\u6570\u636E\u3001\u6536\u5165\u3001\u56E2\u961F\u89C4\u6A21\u548C\u52A8\u673A\u4E00\u5F8B\u4E0D\u5F97\u63A8\u65AD\u6210\u4E8B\u5B9E\u3002",
10213
+ "\u5148\u6838\u5B9E\u672C\u4EBA\u662F\u5426\u6709\u516C\u5F00\u65B9\u6CD5\u8BBA\uFF1B\u6CA1\u6709\u53EF\u6EAF\u6E90\u65B9\u6CD5\u8BBA\u65F6\uFF0C\u660E\u786E\u964D\u7EA7\u4E3A\u300C\u4ECE\u4F5C\u54C1\u53CD\u63A8\u7684\u7ED3\u6784\u53C2\u8003\u300D\u3002\u8DE8\u5E73\u53F0\u5BF9\u8C61\u5FC5\u987B\u5148\u8BF4\u660E\u4E0E\u6296\u97F3\u7684\u5206\u53D1\u673A\u5236\u5DEE\u5F02\uFF0C\u4E0D\u5F97\u6362\u7B97\u6570\u636E\u8868\u73B0\u3002",
10214
+ "\u62A5\u544A\u5FC5\u987B\u5305\u542B\uFF1A\u4ED6\u662F\u8C01\u3001\u4F5C\u54C1\u6570\u636E\u8868\u3001\u4E94\u7EF4\u5185\u5BB9\u516C\u5F0F\uFF08\u8EAB\u4EFD\u53D9\u4E8B / \u9009\u9898\u6765\u6E90 / \u6807\u9898\u4E0E\u94A9\u5B50 / \u5F62\u5F0F\u4E0E\u8282\u594F / \u5206\u53D1\u4E0E\u53D8\u73B0\uFF0C\u6BCF\u7EF4\u9644\u4F5C\u54C1\u8BC1\u636E\u6216\u6807\u7F3A\u5931\uFF09\u3001\u53EF\u501F\u9274\u4E0E\u4E0D\u53EF\u7167\u642C\u6E05\u5355\u53CA\u8D44\u6E90\u7406\u7531\u3001\u4E0D\u8D85\u8FC7 3 \u6761\u4E0B\u5468\u53EF\u6267\u884C\u8FC1\u79FB\u52A8\u4F5C\u3001\u4FE1\u606F\u53EF\u9760\u6027\u8BF4\u660E\u3002",
10215
+ "\u8FC1\u79FB\u52A8\u4F5C\u5FC5\u987B\u5229\u7528\u7528\u6237\u73B0\u6709\u8D44\u6E90\uFF0C\u5199\u6E05\u7528\u4F55\u79CD\u66FF\u4EE3\u8DEF\u5F84\u8865\u8DB3\u5BF9\u65B9\u72EC\u6709\u8D44\u6E90\uFF1B\u4E0D\u5F97\u5EFA\u8BAE\u590D\u523B\u5177\u4F53\u9009\u9898\u3001\u6587\u6848\u6216\u4EBA\u8BBE\u3002\u8BC1\u636E\u4E0D\u8DB3\u7684\u7EF4\u5EA6\u4FDD\u7559\u7A7A\u7F3A\u5E76\u5217\u5165\u5F85\u8865\u7D20\u6750\u3002",
10216
+ ...common.slice(3)
10217
+ ].join("\n").replace(/\n{3,}/g, "\n\n");
10218
+ }
10219
+ if (kind === "planner") {
10220
+ const diagnosisFile = projectPath ? path14.join(projectPath, "inputs", "diagnosis-report.md") : "";
10221
+ return [
10222
+ "\u8BF7\u6267\u884C\u4E00\u6B21\u300C\u6296\u97F3\u9009\u9898\u89C4\u5212\u300D\uFF0C\u628A\u8D26\u53F7\u5B9A\u4F4D\u4E0E\u4F53\u68C0\u7ED3\u8BBA\u8F6C\u6210\u53EF\u62CD\u6444\u3001\u53EF\u9A8C\u6536\u7684\u771F\u5B9E\u5185\u5BB9\u65E5\u5386\u3002",
10223
+ ...common.slice(0, 3),
10224
+ "\u540C\u65F6\u5B8C\u6574\u9605\u8BFB references/formula-card.md\uFF1B\u5F15\u7528\u8BCA\u65AD\u5904\u65B9\u65F6\uFF0C\u9605\u8BFB\u76F8\u90BB account-diagnosis \u6280\u80FD\u7684 SKILL.md \u4E0E references/prescription-library.md\uFF0C\u4E0D\u5F97\u7F16\u9020\u65B9\u6CD5\u8BBA\u51FA\u5904\u3002",
10225
+ `\u8D26\u53F7\u5B9A\u4F4D\uFF1A${input.positioning || linked.diagnosis?.title || "\uFF08\u4EC5\u4F7F\u7528\u4F53\u68C0\u62A5\u544A\u4E2D\u7684\u5B9A\u4F4D\uFF0C\u7F3A\u5931\u65F6\u5148\u5217\u4E3A\u5F85\u8865\uFF09"}`,
10226
+ `\u5F00\u59CB\u65E5\u671F\uFF1A${input.startDate}`,
10227
+ `\u6BCF\u5468\u53D1\u5E03\u4E0A\u9650\uFF1A${input.frequency} \u6761\uFF08\u4E0D\u5F97\u8D85\u8FC7\uFF1B\u6570\u91CF\u4E0D\u8DB3\u4EE5\u8986\u76D6\u5168\u90E8\u7C7B\u578B\u65F6\u8BF4\u660E\u53D6\u820D\uFF0C\u4E0D\u5F97\u5077\u5077\u52A0\u91CF\uFF09`,
10228
+ `\u7528\u6237\u8865\u5145\u7684\u771F\u5B9E\u7D20\u6750\u3001\u65E5\u7A0B\u4E0E\u7EA6\u675F\uFF1A${input.notes || "\uFF08\u65E0\uFF1B\u4E0D\u5F97\u56E0\u6B64\u7F16\u9020\u53EF\u62CD\u4E8B\u4EF6\uFF09"}`,
10229
+ "",
10230
+ linked.diagnosis ? `\u5DF2\u5173\u8054\u4F53\u68C0\u62A5\u544A\uFF0C\u5168\u6587\u540C\u65F6\u4FDD\u5B58\u4E8E ${diagnosisFile}\uFF1B\u5FC5\u987B\u5148\u8BFB\u53D6\u8BE5\u6587\u4EF6\u3002\u4EE5\u4E0B\u4E3A\u540C\u4E00\u4EFD\u4F53\u68C0\u5168\u6587\uFF1A` : "\u672C\u6B21\u672A\u5173\u8054\u4F53\u68C0\u62A5\u544A\uFF0C\u53EA\u80FD\u4F9D\u636E\u4E0A\u65B9\u5B9A\u4F4D\u548C\u771F\u5B9E\u8865\u5145\u4FE1\u606F\u89C4\u5212\u3002",
10231
+ linked.diagnosis ? diagnosisContext(linked.diagnosis) : "",
10232
+ "",
10233
+ "\u4F53\u68C0\u4E2D\u7684\u7ED3\u8BBA\u987B\u843D\u5B9E\u5230\u9009\u9898\u8BBE\u8BA1\u903B\u8F91\uFF1A\u8BF4\u660E\u6BCF\u6761\u9009\u9898\u54CD\u5E94\u4E86\u54EA\u9879\u53D1\u73B0\u6216\u5904\u65B9\uFF1B\u4F53\u68C0\u540C\u6837\u8BC1\u636E\u4E0D\u8DB3\u7684\u7ED3\u8BBA\u4E0D\u5F97\u5F53\u6210\u4E8B\u5B9E\u653E\u5927\u3002",
10234
+ "\u6BCF\u6761\u9009\u9898\u5FC5\u987B\u7ED1\u5B9A\u7528\u6237\u771F\u5B9E\u5728\u505A\u7684\u4E8B\u3001\u771F\u5B9E\u53EF\u62CD\u4E8B\u4EF6\u6216\u771F\u5B9E\u516C\u5F00\u4FE1\u606F\uFF0C\u6CE8\u660E\u7D20\u6750\u6765\u6E90\uFF1B\u6CA1\u6709\u7D20\u6750\u5C31\u653E\u5165\u300C\u7D20\u6750\u5F85\u8865\u6E05\u5355\u300D\uFF0C\u4E0D\u5F97\u7F16\u9020\u7ECF\u5386\u3001\u4EA7\u54C1\u3001\u8BA2\u5355\u6216\u62CD\u6444\u6761\u4EF6\u3002",
10235
+ "\u8F93\u51FA\uFF1A\u5B9A\u4F4D\u590D\u8FF0\u4E0E\u672C\u5468\u7EA6\u675F\u3001\u4ECE\u5F00\u59CB\u65E5\u671F\u8D77\u7684\u4E00\u5468\u9009\u9898\u8868\uFF08\u65E5\u671F / \u6781\u7AEF\u5316\u6807\u9898 / 3 \u79D2\u94A9\u5B50 / \u5F62\u5F0F / \u7C7B\u578B / \u771F\u5B9E\u7D20\u6750\u6765\u6E90 / \u8BBE\u8BA1\u903B\u8F91\u4E0E\u51FA\u5904 / \u7ED3\u5C3E\u4E92\u52A8\u94A9\u5B50\uFF09\u3001\u9010\u6761\u516C\u5F0F\u5361\u3001\u672C\u5468\u6307\u6807\u4E0E\u68C0\u67E5\u70B9\u3001\u7D20\u6750\u5F85\u8865\u6E05\u5355\u3002",
10236
+ "\u81F3\u5C11\u5305\u542B 1 \u6761\u641C\u7D22\u9700\u6C42\u578B\u9009\u9898\uFF1B\u6709\u771F\u5B9E\u5728\u63A8\u8FDB\u7684\u4EA7\u54C1\u6216\u9879\u76EE\u65F6\u624D\u5B89\u6392\u4EA7\u54C1\u5C55\u793A\u578B\u3002\u6BCF\u6761\u516C\u5F0F\u5361\u5199\u5168\u6781\u7AEF\u5316\u6807\u9898\u30013 \u79D2\u94A9\u5B50\u3001\u5C71\u6D1E\u3001\u51B2\u7A81\u3001\u627F\u8BFA\u5151\u73B0\u3002\u6807\u660E A/B \u6D4B\u8BD5\u578B\u9009\u9898\uFF0C\u4F46\u4E0D\u5F97\u628A\u5C0F\u6837\u672C\u65B9\u5411\u89C2\u5BDF\u5199\u6210\u5DF2\u8BC1\u5B9E\u7ED3\u8BBA\u3002",
10237
+ "\u6392\u671F\u603B\u6761\u6570\u4E0D\u5F97\u8D85\u8FC7\u6BCF\u5468\u4E0A\u9650\uFF0C\u987B\u6838\u7B97\u7528\u6237\u4EA7\u80FD\uFF1B\u6240\u6709\u6307\u6807\u5206\u4E3A\u300C\u540E\u53F0\u5DF2\u6709\u57FA\u7EBF / \u81EA\u8BBE\u7BA1\u7406\u76EE\u6807 / \u5F85\u8865\u300D\uFF0C\u4E0D\u5F97\u865A\u6784\u540C\u7C7B\u6216\u5B98\u65B9\u53C2\u8003\u503C\u3002",
10238
+ ...common.slice(3)
10239
+ ].join("\n").replace(/\n{3,}/g, "\n\n");
10240
+ }
10241
+ const baselineFile = projectPath ? path14.join(projectPath, "inputs", "baseline-report.md") : "";
10242
+ const currentFile = projectPath ? path14.join(projectPath, "inputs", "current-report.md") : "";
10243
+ return [
10244
+ "\u8BF7\u6267\u884C\u4E00\u6B21\u300C\u8D26\u53F7\u590D\u8BCA\u5BF9\u6BD4\u300D\uFF1A\u5BF9\u7167\u6B64\u524D\u4E0E\u672C\u6B21\u4E24\u6B21\u4F53\u68C0\uFF0C\u5224\u65AD\u53D8\u5316\u3001\u5904\u65B9\u6267\u884C\u60C5\u51B5\u548C\u4E0B\u4E00\u6B65\uFF0C\u4E0D\u8981\u91CD\u65B0\u5199\u4E24\u4EFD\u4E92\u4E0D\u76F8\u5E72\u7684\u4F53\u68C0\u3002",
10245
+ ...common.slice(0, 3),
10246
+ "\u540C\u65F6\u9605\u8BFB references/diagnosis-framework.md \u4E0E references/prescription-library.md\uFF1B\u5904\u65B9\u53EA\u80FD\u6CBF\u7528\u53EF\u6EAF\u6E90\u6765\u6E90\uFF0C\u4E0D\u5F97\u81EA\u884C\u7F16\u9020\u51FA\u5904\u3002",
10247
+ `\u8865\u5145\u8BF4\u660E\uFF1A${input.notes || "\uFF08\u65E0\uFF09"}`,
10248
+ "",
10249
+ `\u57FA\u7EBF\u4F53\u68C0\u5168\u6587\u5DF2\u4FDD\u5B58\u4E8E ${baselineFile}\uFF0C\u672C\u6B21\u4F53\u68C0\u5168\u6587\u5DF2\u4FDD\u5B58\u4E8E ${currentFile}\uFF1B\u5FC5\u987B\u5148\u8BFB\u53D6\u4E24\u4EFD\u6587\u4EF6\u3002\u4EE5\u4E0B\u4F9D\u6B21\u5D4C\u5165\u76F8\u540C\u5168\u6587\uFF1A`,
10250
+ "===== \u57FA\u7EBF\u4F53\u68C0\uFF08\u6B64\u524D\uFF09 =====",
10251
+ diagnosisContext(linked.baseline),
10252
+ "===== \u672C\u6B21\u4F53\u68C0\uFF08\u6700\u8FD1\uFF09 =====",
10253
+ diagnosisContext(linked.current),
10254
+ "",
10255
+ "\u5148\u5217\u51FA\u4E24\u4EFD\u62A5\u544A\u7684\u4F53\u68C0\u65F6\u95F4\u3001\u6837\u672C\u8303\u56F4\u3001\u6570\u636E\u5B57\u6BB5\u548C\u7EDF\u8BA1\u53E3\u5F84\u3002\u53EA\u6BD4\u8F83\u4E24\u8FB9\u90FD\u5B9E\u9645\u5B58\u5728\u4E14\u5B9A\u4E49\u3001\u5355\u4F4D\u3001\u65F6\u95F4\u7A97\u53E3\u548C\u6837\u672C\u8303\u56F4\u4E00\u81F4\u7684\u6307\u6807\uFF1B\u5C55\u793A\u539F\u59CB\u503C\uFF0C\u518D\u8BA1\u7B97\u53D8\u5316\u503C\u6216\u53D8\u5316\u7387\u3002\u9664\u6570\u4E3A\u96F6\u6216\u4EFB\u4E00\u7AEF\u7F3A\u5931\u65F6\u4E0D\u7B97\u53D8\u5316\u7387\u3002",
10256
+ "\u4E0D\u540C\u5B57\u6BB5\u4E0D\u5F97\u4E92\u76F8\u6362\u7B97\uFF08\u5982\u5E73\u5747\u64AD\u653E\u65F6\u957F\u3001\u5B8C\u64AD\u7387\u300130 \u79D2\u7559\u5B58\uFF09\uFF1B\u4E0D\u540C\u6837\u672C\u91CF\u4E0D\u5F97\u76F4\u63A5\u62FC\u5E73\u5747\uFF0C\u4E0D\u540C\u53E3\u5F84\u4E0D\u5F97\u8BA1\u7B97\u3002\u65E0\u6CD5\u5BF9\u7167\u7684\u9879\u76EE\u7EDF\u4E00\u6807\u4E3A\u300C\u4E0D\u53EF\u6BD4\uFF1A\u7F3A\u5B57\u6BB5 / \u53E3\u5F84\u4E0D\u540C / \u6837\u672C\u4E0D\u540C\u300D\uFF0C\u4E0D\u5F97\u865A\u6784\u6570\u503C\u6216\u628A\u76F8\u5173\u6027\u5199\u6210\u56E0\u679C\u3002",
10257
+ "\u82E5\u62A5\u544A\u65E5\u671F\u6216\u57FA\u7EBF\uFF0F\u672C\u6B21\u987A\u5E8F\u770B\u8D77\u6765\u4E0D\u4E00\u81F4\uFF0C\u660E\u786E\u6307\u51FA\uFF0C\u4E0D\u5F97\u64C5\u81EA\u4EA4\u6362\u6216\u63A9\u76D6\u3002\u6807\u9898\u548C\u6587\u5B57\u8F6C\u5F55\u4ECD\u4E0D\u80FD\u8BC1\u660E\u672A\u63D0\u4F9B\u7684\u753B\u9762\u4E0E\u53E3\u64AD\u3002",
10258
+ "\u62A5\u544A\u5FC5\u987B\u5305\u542B\uFF1A\u6838\u5FC3\u7ED3\u8BBA\u3001\u540C\u53E3\u5F84\u6307\u6807\u5BF9\u7167\u8868\u3001\u5185\u5BB9\u7EBF\u4E0E\u53D1\u5E03\u6267\u884C\u53D8\u5316\u3001\u57FA\u7EBF\u5904\u65B9\u7684\u9010\u9879\u590D\u6838\uFF08\u4FDD\u7559 / \u505C\u6B62 / \u65B0\u589E\u53CA\u8BC1\u636E\uFF09\u3001\u4E0B\u4E00\u8F6E\u4E0D\u8D85\u8FC7 3 \u9879\u4F18\u5148\u52A8\u4F5C\u300130 \u5929\u9A8C\u6536\u6307\u6807\u4E0E\u68C0\u67E5\u70B9\u3001\u5F85\u8865\u8F93\u5165\u6E05\u5355\u3002",
10259
+ "\u4FDD\u7559\u3001\u505C\u6B62\u3001\u65B0\u589E\u90FD\u8981\u8BF4\u660E\u4F9D\u636E\uFF1B\u6CA1\u6709\u6267\u884C\u8BC1\u636E\u65F6\u6807\u300C\u6267\u884C\u5F85\u6838\u5B9E\u300D\uFF0C\u4E0D\u5F97\u5BA3\u79F0\u5904\u65B9\u6709\u6548\u6216\u65E0\u6548\u300230 \u5929\u76EE\u6807\u9700\u4E0E\u53D1\u5E03\u9891\u7387\u548C\u4EA7\u80FD\u4E00\u81F4\uFF0C\u81EA\u8BBE\u76EE\u6807\u987B\u660E\u786E\u6807\u6CE8\u3002",
10260
+ ...common.slice(3)
10261
+ ].join("\n").replace(/\n{3,}/g, "\n\n");
10262
+ }
9194
10263
  async function stateAsync() {
10264
+ await refreshTrialRuns();
9195
10265
  reconcileOrphanTasks();
9196
10266
  for (const a of listInstalled(paths)) {
9197
10267
  healTrialIfJobDone(productOf(a) || a.id, a.id);
@@ -9231,17 +10301,21 @@ function createPanelApp(options = {}) {
9231
10301
  store: storeView,
9232
10302
  license: license.status(),
9233
10303
  licenses: license.listProducts(),
10304
+ member: memberInfo(),
9234
10305
  buyUrl: buyPageUrl(),
9235
10306
  licenseBaseUrl: settings.licenseBaseUrl,
10307
+ trialRuns,
10308
+ device: { hash: license.deviceHash(), label: license.device().label },
9236
10309
  campaigns: await loadPublicCampaigns(),
10310
+ showcase: await loadPublicShowcase(),
10311
+ docs: await loadPublicDocs(),
9237
10312
  storeError,
9238
10313
  tasks: queue.list(),
9239
10314
  settings: {
9240
10315
  autoInstallUpdates: !!settings.autoInstallUpdates,
9241
10316
  autoUpdate: settings.autoUpdate !== false,
9242
10317
  autoKickoffInDsh: settings.autoKickoffInDsh !== false,
9243
- telemetry: !!settings.telemetry,
9244
- panelNpmRegistry: panelRegistryBase()
10318
+ workspaceRoot: settings.workspaceRoot || null
9245
10319
  },
9246
10320
  panel: {
9247
10321
  name: packageName,
@@ -9249,7 +10323,6 @@ function createPanelApp(options = {}) {
9249
10323
  latest: panelUpdateCache.latest,
9250
10324
  updateAvailable: !!panelUpdateCache.updateAvailable,
9251
10325
  checkedAt: panelUpdateCache.checkedAt || null,
9252
- registry: panelUpdateCache.registry || panelRegistryBase(),
9253
10326
  error: panelUpdateCache.error || null,
9254
10327
  installHint: panelUpdateCache.installHint || panelInstallHint(false)
9255
10328
  },
@@ -9270,15 +10343,20 @@ function createPanelApp(options = {}) {
9270
10343
  store: [],
9271
10344
  license: license.status(),
9272
10345
  licenses: license.listProducts(),
10346
+ member: memberInfo(),
9273
10347
  buyUrl: buyPageUrl(),
9274
10348
  licenseBaseUrl: settings.licenseBaseUrl,
10349
+ trialRuns,
10350
+ device: { hash: license.deviceHash(), label: license.device().label },
9275
10351
  campaigns: [],
10352
+ showcase: { promptsEnabled: false, cases: [], tutorials: [] },
10353
+ docs: [],
9276
10354
  storeError: null,
9277
10355
  tasks: queue.list(),
9278
10356
  settings: {
9279
10357
  autoInstallUpdates: !!settings.autoInstallUpdates,
9280
10358
  autoKickoffInDsh: settings.autoKickoffInDsh !== false,
9281
- telemetry: !!settings.telemetry
10359
+ workspaceRoot: settings.workspaceRoot || null
9282
10360
  },
9283
10361
  dsh: {
9284
10362
  skills: !!dsh?.skills?.available?.(),
@@ -9292,7 +10370,7 @@ function createPanelApp(options = {}) {
9292
10370
  }
9293
10371
  let campaignCache = { at: 0, items: [] };
9294
10372
  async function loadPublicCampaigns() {
9295
- if (resellerCode) return [];
10373
+ if (resellerCode() || license.canExport()) return [];
9296
10374
  const now = Date.now();
9297
10375
  if (now - campaignCache.at < 6e4) return campaignCache.items;
9298
10376
  const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
@@ -9301,7 +10379,8 @@ function createPanelApp(options = {}) {
9301
10379
  return [];
9302
10380
  }
9303
10381
  try {
9304
- const res = await fetch(`${base}/v1/commerce/campaigns`, { signal: AbortSignal.timeout(4e3) });
10382
+ const device = encodeURIComponent(license.deviceHash());
10383
+ const res = await fetch(`${base}/v1/commerce/campaigns?device=${device}`, { signal: AbortSignal.timeout(4e3) });
9305
10384
  const data = await res.json().catch(() => ({}));
9306
10385
  if (!res.ok) throw new Error("campaigns unavailable");
9307
10386
  const items = (Array.isArray(data.campaigns) ? data.campaigns : []).map((item) => ({
@@ -9311,7 +10390,9 @@ function createPanelApp(options = {}) {
9311
10390
  description: String(item.description || ""),
9312
10391
  price: Number(item.price) || 0,
9313
10392
  compareAt: Number(item.compareAt) || 0,
9314
- gradient: String(item.gradient || "lime")
10393
+ gradient: String(item.gradient || "lime"),
10394
+ kind: item.kind === "link" ? "link" : "sale",
10395
+ linkUrl: String(item.linkUrl || "")
9315
10396
  })).filter((item) => item.slug && item.name);
9316
10397
  campaignCache = { at: now, items };
9317
10398
  return items;
@@ -9320,6 +10401,119 @@ function createPanelApp(options = {}) {
9320
10401
  return campaignCache.items;
9321
10402
  }
9322
10403
  }
10404
+ let showcaseCache = { at: 0, promptsEnabled: false, cases: [], tutorials: [] };
10405
+ let docsCache = { at: 0, items: [] };
10406
+ async function loadPublicDocs() {
10407
+ const now = Date.now();
10408
+ if (now - docsCache.at < 6e4) return docsCache.items;
10409
+ const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
10410
+ if (!base) {
10411
+ docsCache = { at: now, items: [] };
10412
+ return docsCache.items;
10413
+ }
10414
+ try {
10415
+ const res = await fetch(`${base}/v1/docs`, { signal: AbortSignal.timeout(4e3) });
10416
+ const data = await res.json().catch(() => ({}));
10417
+ if (!res.ok) throw new Error("docs unavailable");
10418
+ const items = (Array.isArray(data.docs) ? data.docs : []).map((item) => ({
10419
+ id: String(item.id || ""),
10420
+ title: String(item.title || ""),
10421
+ url: String(item.url || "")
10422
+ })).filter((item) => item.id && /^https?:\/\//i.test(item.url));
10423
+ docsCache = { at: now, items };
10424
+ return items;
10425
+ } catch {
10426
+ docsCache = { at: now, items: docsCache.items };
10427
+ return docsCache.items;
10428
+ }
10429
+ }
10430
+ async function loadPublicShowcase() {
10431
+ const now = Date.now();
10432
+ if (now - showcaseCache.at < 6e4) return showcaseCache;
10433
+ const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
10434
+ if (!base) {
10435
+ showcaseCache = { at: now, promptsEnabled: false, cases: [], tutorials: [] };
10436
+ return showcaseCache;
10437
+ }
10438
+ try {
10439
+ const res = await fetch(`${base}/v1/showcase`, { signal: AbortSignal.timeout(4e3) });
10440
+ const data = await res.json().catch(() => ({}));
10441
+ if (!res.ok) throw new Error("showcase unavailable");
10442
+ const promptsEnabled = data.promptsEnabled === true;
10443
+ const mapItem = (item) => {
10444
+ const access = item.access === "licensed" ? "licensed" : "public";
10445
+ return {
10446
+ id: String(item.id || ""),
10447
+ title: String(item.title || ""),
10448
+ blurb: String(item.blurb || ""),
10449
+ agent: String(item.agent || ""),
10450
+ style: String(item.style || ""),
10451
+ coverUrl: String(item.coverUrl || ""),
10452
+ videoUrl: String(item.videoUrl || ""),
10453
+ access,
10454
+ locked: promptsEnabled && access === "licensed",
10455
+ prompt: promptsEnabled && access !== "licensed" ? String(item.prompt || "") : ""
10456
+ };
10457
+ };
10458
+ const cases = (Array.isArray(data.cases) ? data.cases : []).map(mapItem).filter((item) => item.id && item.videoUrl);
10459
+ const tutorials = (Array.isArray(data.tutorials) ? data.tutorials : []).map(mapItem).filter((item) => item.id && item.videoUrl);
10460
+ showcaseCache = { at: now, promptsEnabled, cases, tutorials };
10461
+ return showcaseCache;
10462
+ } catch {
10463
+ showcaseCache = {
10464
+ at: now,
10465
+ promptsEnabled: showcaseCache.promptsEnabled,
10466
+ cases: showcaseCache.cases,
10467
+ tutorials: showcaseCache.tutorials
10468
+ };
10469
+ return showcaseCache;
10470
+ }
10471
+ }
10472
+ async function fetchCasePrompt(id) {
10473
+ const showcase = await loadPublicShowcase();
10474
+ const item = (showcase.cases || []).find((row) => row.id === id);
10475
+ if (!item) {
10476
+ const err = new Error("\u627E\u4E0D\u5230\u8FD9\u4E2A\u6848\u4F8B");
10477
+ err.status = 404;
10478
+ throw err;
10479
+ }
10480
+ if (!showcase.promptsEnabled) {
10481
+ const err = new Error("\u63D0\u793A\u8BCD\u672A\u5F00\u653E");
10482
+ err.status = 404;
10483
+ throw err;
10484
+ }
10485
+ if (item.access !== "licensed") {
10486
+ return { prompt: item.prompt || "", style: item.style || "", agent: item.agent || "" };
10487
+ }
10488
+ if (!license.canUseProduct(item.agent)) {
10489
+ const err = new Error("\u8BF7\u5148\u6FC0\u6D3B\u5BF9\u5E94 Agent");
10490
+ err.status = 403;
10491
+ throw err;
10492
+ }
10493
+ const token = license.tokenFor(item.agent);
10494
+ const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
10495
+ if (!token || !base) {
10496
+ const err = new Error("\u8BF7\u5148\u6FC0\u6D3B\u5BF9\u5E94 Agent");
10497
+ err.status = 403;
10498
+ throw err;
10499
+ }
10500
+ const res = await fetch(`${base}/v1/showcase/${encodeURIComponent(id)}/prompt`, {
10501
+ headers: { authorization: `Bearer ${token}` },
10502
+ signal: AbortSignal.timeout(8e3)
10503
+ });
10504
+ const data = await res.json().catch(() => ({}));
10505
+ if (!res.ok) {
10506
+ const msg = data?.error?.message;
10507
+ const err = new Error(typeof msg === "string" && msg ? msg : "\u6682\u65F6\u65E0\u6CD5\u83B7\u53D6\u63D0\u793A\u8BCD");
10508
+ err.status = res.status || 502;
10509
+ throw err;
10510
+ }
10511
+ return {
10512
+ prompt: String(data.prompt || ""),
10513
+ style: String(data.style || item.style || ""),
10514
+ agent: String(data.agent || item.agent || "")
10515
+ };
10516
+ }
9323
10517
  async function loadPublicContact() {
9324
10518
  const base = String(settings.licenseBaseUrl || "").replace(/\/$/, "");
9325
10519
  if (!base) return { wechatId: "", hasQr: false, configured: false };
@@ -9348,6 +10542,7 @@ function createPanelApp(options = {}) {
9348
10542
  }
9349
10543
  async function handle(req, res, pathname) {
9350
10544
  const route = `${req.method} ${pathname}`;
10545
+ const query = new URL(req.url ?? "/", "http://local").searchParams;
9351
10546
  if (req.method === "GET" && pathname.startsWith("/icons/")) {
9352
10547
  const raw = pathname.slice("/icons/".length).replace(/[^a-zA-Z0-9._-]/g, "");
9353
10548
  const base = raw.replace(/\.(png|svg|webp)$/i, "") || "app";
@@ -9362,9 +10557,22 @@ function createPanelApp(options = {}) {
9362
10557
  res.writeHead(200, { "content-type": "image/svg+xml; charset=utf-8", "cache-control": "no-store" });
9363
10558
  return void res.end(placeholderIcon(base));
9364
10559
  }
10560
+ if (req.method === "GET" && pathname.startsWith("/diagnose/media/")) {
10561
+ return serveDiagnoseMedia(req, res, pathname.slice("/diagnose/media/".length).replace(/[^0-9a-f-]/gi, ""));
10562
+ }
9365
10563
  switch (route) {
9366
10564
  case "GET /state":
9367
10565
  return send(res, 200, await stateAsync());
10566
+ case "POST /showcase/prompt": {
10567
+ try {
10568
+ const body = await readJson(req);
10569
+ const id = String(body.id || "").trim();
10570
+ if (!id) return send(res, 400, { error: "\u627E\u4E0D\u5230\u8FD9\u4E2A\u6848\u4F8B" });
10571
+ return send(res, 200, await fetchCasePrompt(id));
10572
+ } catch (error) {
10573
+ return send(res, error.status || 502, { error: error.message || "\u6682\u65F6\u65E0\u6CD5\u83B7\u53D6\u63D0\u793A\u8BCD" });
10574
+ }
10575
+ }
9368
10576
  case "GET /contact": {
9369
10577
  try {
9370
10578
  return send(res, 200, { contact: await loadPublicContact() });
@@ -9386,6 +10594,236 @@ function createPanelApp(options = {}) {
9386
10594
  });
9387
10595
  return void res.end(buf);
9388
10596
  }
10597
+ case "POST /diagnose/upload": {
10598
+ try {
10599
+ return send(res, 200, { media: await saveDiagnoseUpload(req, query) });
10600
+ } catch (error) {
10601
+ return send(res, error.status || 502, { error: error.message || "\u4E0A\u4F20\u5931\u8D25" });
10602
+ }
10603
+ }
10604
+ case "POST /diagnose/session": {
10605
+ try {
10606
+ assertDiagnoseMember();
10607
+ const body = await readJson(req);
10608
+ const media = normalizeDiagnoseMedia(body.media);
10609
+ if ((!body.snapshot || typeof body.snapshot !== "object") && !media.length) {
10610
+ return send(res, 400, { error: "\u8BF7\u5148\u4E0A\u4F20\u540E\u53F0\u622A\u56FE\u6216\u89C6\u9891" });
10611
+ }
10612
+ const snapshot = body.snapshot && typeof body.snapshot === "object" ? body.snapshot : { title: media[0].name, kind: "upload", media: media.map((item) => item.name) };
10613
+ const projectPath = path14.join(DIAGNOSE_SESSIONS_DIR, crypto8.randomUUID());
10614
+ fs14.mkdirSync(projectPath, { recursive: true });
10615
+ const sessionMedia = materializeDiagnoseMedia(projectPath, media);
10616
+ const skillPath = seedDiagnoseSkill(projectPath);
10617
+ const promptText = diagnosePrompt(snapshot, { media: sessionMedia, projectPath, skillPath });
10618
+ if (!dsh?.chat?.startPromptRun) {
10619
+ return send(res, 503, { error: "\u5F53\u524D\u73AF\u5883\u4E0D\u80FD\u76F4\u63A5\u5F00 DSH \u4F1A\u8BDD\uFF0C\u53EF\u4EE5\u590D\u5236\u63D0\u793A\u8BCD\u5230\u4EFB\u610F\u6A21\u578B", promptText });
10620
+ }
10621
+ const result = await dsh.chat.startPromptRun({
10622
+ agentId: "bn-diagnose",
10623
+ skill: "diagnose",
10624
+ title: "\u8D26\u53F7\u8BCA\u65AD \xB7 " + String(snapshot.title || "\u672A\u547D\u540D").slice(0, 40),
10625
+ promptText,
10626
+ projectPath
10627
+ });
10628
+ if (!result.ok) {
10629
+ return send(res, 502, { error: result.error || "\u5F00\u4E0D\u4E86 DSH \u4F1A\u8BDD\uFF0C\u53EF\u4EE5\u590D\u5236\u63D0\u793A\u8BCD\u5230\u4EFB\u610F\u6A21\u578B", promptText });
10630
+ }
10631
+ return send(res, 200, {
10632
+ ok: true,
10633
+ sessionId: result.sessionId,
10634
+ projectPath,
10635
+ media: media.map(({ path: _path, ...rest }) => rest),
10636
+ promptText
10637
+ });
10638
+ } catch (error) {
10639
+ return send(res, error.status || 502, { error: error.message || "\u5F00\u4E0D\u4E86 DSH \u4F1A\u8BDD" });
10640
+ }
10641
+ }
10642
+ case "GET /diagnose/session-report": {
10643
+ try {
10644
+ assertDiagnoseMember();
10645
+ const sessionId = String(query.get("sessionId") || "");
10646
+ if (!sessionId) return send(res, 400, { error: "\u7F3A\u5C11 sessionId" });
10647
+ const report = diagnoseReports().find((item) => item.sessionId === sessionId);
10648
+ if (!report) return send(res, 404, { error: "\u8FD8\u6CA1\u6709\u5B58\u6863", pending: true });
10649
+ const file = safeReportPath(report.projectPath);
10650
+ if (!file) return send(res, 400, { error: "\u62A5\u544A\u7F3A\u5C11\u6709\u6548\u7684\u4F1A\u8BDD\u76EE\u5F55" });
10651
+ if (!fs14.existsSync(file)) return send(res, 200, { pending: true, report });
10652
+ if (fs14.statSync(file).size > 256 * 1024) return send(res, 413, { error: "\u62A5\u544A\u6587\u4EF6\u592A\u5927" });
10653
+ const analysis = fs14.readFileSync(file, "utf8").slice(0, 2e4);
10654
+ if (analysis !== report.analysis) {
10655
+ report.analysis = analysis;
10656
+ report.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
10657
+ fs14.writeFileSync(path14.join(DIAGNOSE_DIR, `${report.id}.json`), JSON.stringify(report), "utf8");
10658
+ }
10659
+ return send(res, 200, { report });
10660
+ } catch (error) {
10661
+ return send(res, error.status || 500, { error: error.message || "\u8BFB\u53D6\u5931\u8D25" });
10662
+ }
10663
+ }
10664
+ case "GET /diagnose/reports":
10665
+ assertDiagnoseMember();
10666
+ return send(res, 200, { reports: diagnoseReports().slice(0, 50) });
10667
+ case "POST /diagnose/reports": {
10668
+ assertDiagnoseMember();
10669
+ const body = await readJson(req);
10670
+ if (!body.snapshot || typeof body.snapshot !== "object") {
10671
+ return send(res, 400, { error: "\u6CA1\u6709\u53EF\u4FDD\u5B58\u7684\u62A5\u544A" });
10672
+ }
10673
+ try {
10674
+ return send(res, 200, {
10675
+ report: saveDiagnoseReport(body.snapshot, body.analysis, body.sessionId, {
10676
+ projectPath: body.projectPath,
10677
+ media: body.media
10678
+ })
10679
+ });
10680
+ } catch (error) {
10681
+ return send(res, error.status || 500, { error: error.message || "\u4FDD\u5B58\u5931\u8D25" });
10682
+ }
10683
+ }
10684
+ case "POST /diagnose/reports/delete": {
10685
+ assertDiagnoseMember();
10686
+ const body = await readJson(req);
10687
+ const id = String(body.id || "");
10688
+ if (!/^[a-zA-Z0-9-]{8,64}$/.test(id)) return send(res, 400, { error: "\u62A5\u544A\u4E0D\u5B58\u5728" });
10689
+ fs14.rmSync(path14.join(DIAGNOSE_DIR, `${id}.json`), { force: true });
10690
+ return send(res, 200, { ok: true });
10691
+ }
10692
+ case "POST /growth/session": {
10693
+ let promptText = "";
10694
+ try {
10695
+ assertDiagnoseMember();
10696
+ const body = await readJson(req);
10697
+ const kind = growthKind(body.kind);
10698
+ const input = cleanGrowthInput(kind, body.input);
10699
+ const linked = resolveGrowthContext(kind, input);
10700
+ const projectPath = path14.join(DIAGNOSE_SESSIONS_DIR, crypto8.randomUUID());
10701
+ fs14.mkdirSync(projectPath, { recursive: true });
10702
+ const media = kind === "research" ? normalizeDiagnoseMedia(body.media) : [];
10703
+ const sessionMedia = materializeDiagnoseMedia(projectPath, media);
10704
+ let skillPath;
10705
+ if (kind === "research") {
10706
+ skillPath = seedDiagnoseSkill(projectPath, "creator-research");
10707
+ } else if (kind === "planner") {
10708
+ skillPath = seedDiagnoseSkill(projectPath, "topic-planner");
10709
+ seedDiagnoseSkill(projectPath, "account-diagnosis");
10710
+ if (linked.diagnosis) {
10711
+ const inputsDir = path14.join(projectPath, "inputs");
10712
+ fs14.mkdirSync(inputsDir, { recursive: true });
10713
+ fs14.writeFileSync(path14.join(inputsDir, "diagnosis-report.md"), diagnosisContext(linked.diagnosis), "utf8");
10714
+ }
10715
+ } else {
10716
+ skillPath = seedDiagnoseSkill(projectPath, "account-diagnosis");
10717
+ const inputsDir = path14.join(projectPath, "inputs");
10718
+ fs14.mkdirSync(inputsDir, { recursive: true });
10719
+ fs14.writeFileSync(path14.join(inputsDir, "baseline-report.md"), diagnosisContext(linked.baseline), "utf8");
10720
+ fs14.writeFileSync(path14.join(inputsDir, "current-report.md"), diagnosisContext(linked.current), "utf8");
10721
+ }
10722
+ promptText = growthPrompt(kind, input, sessionMedia, { ...linked, projectPath, skillPath });
10723
+ if (!dsh?.chat?.startPromptRun) {
10724
+ return send(res, 503, { error: "\u5F53\u524D\u73AF\u5883\u4E0D\u80FD\u76F4\u63A5\u5F00 DSH \u4F1A\u8BDD\uFF0C\u53EF\u4EE5\u590D\u5236\u63D0\u793A\u8BCD\u5230\u4EFB\u610F\u6A21\u578B", promptText });
10725
+ }
10726
+ const result = await dsh.chat.startPromptRun({
10727
+ agentId: "bn-diagnose",
10728
+ skill: "diagnose",
10729
+ title: `${GROWTH_LABELS[kind]} \xB7 ${growthRecordTitle(kind, input)}`.slice(0, 80),
10730
+ promptText,
10731
+ projectPath
10732
+ });
10733
+ if (!result.ok) {
10734
+ return send(res, 502, { error: result.error || "\u5F00\u4E0D\u4E86 DSH \u4F1A\u8BDD\uFF0C\u53EF\u4EE5\u590D\u5236\u63D0\u793A\u8BCD\u5230\u4EFB\u610F\u6A21\u578B", promptText });
10735
+ }
10736
+ const recordMedia = sessionMedia.map(({ path: _path, ...rest }) => rest);
10737
+ const record = createGrowthRecord(kind, input, {
10738
+ sessionId: result.sessionId,
10739
+ projectPath,
10740
+ media: recordMedia
10741
+ });
10742
+ return send(res, 200, {
10743
+ ok: true,
10744
+ sessionId: result.sessionId,
10745
+ projectPath,
10746
+ promptText,
10747
+ record,
10748
+ media: recordMedia
10749
+ });
10750
+ } catch (error) {
10751
+ return send(res, error.status || 502, { error: error.message || "\u5F00\u4E0D\u4E86 DSH \u4F1A\u8BDD", promptText });
10752
+ }
10753
+ }
10754
+ case "GET /growth/session-report": {
10755
+ try {
10756
+ assertDiagnoseMember();
10757
+ const sessionId = String(query.get("sessionId") || "");
10758
+ if (!sessionId) return send(res, 400, { error: "\u7F3A\u5C11 sessionId" });
10759
+ const report = findGrowthRecord({ sessionId });
10760
+ if (!report) return send(res, 404, { error: "\u8FD8\u6CA1\u6709\u5B58\u6863", pending: true });
10761
+ const file = safeReportPath(report.projectPath);
10762
+ if (!file) return send(res, 400, { error: "\u62A5\u544A\u7F3A\u5C11\u6709\u6548\u7684\u4F1A\u8BDD\u76EE\u5F55" });
10763
+ if (!fs14.existsSync(file)) return send(res, 200, { pending: true, report });
10764
+ if (fs14.statSync(file).size > 256 * 1024) return send(res, 413, { error: "\u62A5\u544A\u6587\u4EF6\u592A\u5927" });
10765
+ const analysis = fs14.readFileSync(file, "utf8").slice(0, 4e4);
10766
+ if (analysis !== report.analysis) {
10767
+ report.analysis = analysis;
10768
+ report.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
10769
+ writeGrowthRecord(report);
10770
+ }
10771
+ return send(res, 200, { report });
10772
+ } catch (error) {
10773
+ return send(res, error.status || 500, { error: error.message || "\u8BFB\u53D6\u5931\u8D25" });
10774
+ }
10775
+ }
10776
+ case "GET /growth/reports": {
10777
+ try {
10778
+ assertDiagnoseMember();
10779
+ const kind = growthKind(query.get("kind"));
10780
+ return send(res, 200, { reports: growthRecords(kind).slice(0, 60) });
10781
+ } catch (error) {
10782
+ return send(res, error.status || 500, { error: error.message || "\u8BFB\u53D6\u5931\u8D25" });
10783
+ }
10784
+ }
10785
+ case "POST /growth/reports": {
10786
+ try {
10787
+ assertDiagnoseMember();
10788
+ const body = await readJson(req);
10789
+ const kind = growthKind(body.kind);
10790
+ const input = cleanGrowthInput(kind, body.input);
10791
+ resolveGrowthContext(kind, input);
10792
+ const analysis = String(body.analysis || "").slice(0, 4e4);
10793
+ if (!analysis.trim()) return send(res, 400, { error: "\u6CA1\u6709\u53EF\u4FDD\u5B58\u7684\u62A5\u544A" });
10794
+ const existing = body.id ? findGrowthRecord({ kind, id: growthRecordId(body.id) }) : null;
10795
+ if (body.id && !existing) return send(res, 404, { error: "\u6863\u6848\u4E0D\u5B58\u5728" });
10796
+ const media = body.media === void 0 && existing ? existing.media : normalizeDiagnoseMedia(body.media).map(({ path: _path, ...rest }) => rest);
10797
+ const sessionId = String(body.sessionId ?? existing?.sessionId ?? "").slice(0, 100);
10798
+ const projectPath = String(body.projectPath ?? existing?.projectPath ?? "").slice(0, 400);
10799
+ const report = existing ? writeGrowthRecord({
10800
+ ...existing,
10801
+ title: growthRecordTitle(kind, input),
10802
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
10803
+ input,
10804
+ analysis,
10805
+ sessionId,
10806
+ projectPath,
10807
+ media,
10808
+ links: growthLinksFromInput(kind, input)
10809
+ }) : createGrowthRecord(kind, input, { analysis, sessionId, projectPath, media });
10810
+ return send(res, 200, { report });
10811
+ } catch (error) {
10812
+ return send(res, error.status || 500, { error: error.message || "\u4FDD\u5B58\u5931\u8D25" });
10813
+ }
10814
+ }
10815
+ case "POST /growth/reports/delete": {
10816
+ try {
10817
+ assertDiagnoseMember();
10818
+ const body = await readJson(req);
10819
+ const kind = growthKind(body.kind);
10820
+ const id = growthRecordId(body.id);
10821
+ fs14.rmSync(path14.join(GROWTH_DIR, kind, `${id}.json`), { force: true });
10822
+ return send(res, 200, { ok: true });
10823
+ } catch (error) {
10824
+ return send(res, error.status || 500, { error: error.message || "\u5220\u9664\u5931\u8D25" });
10825
+ }
10826
+ }
9389
10827
  case "GET /licenses":
9390
10828
  return send(res, 200, { licenses: license.listProducts(), aggregate: license.status() });
9391
10829
  case "POST /activate": {
@@ -9644,7 +11082,12 @@ function createPanelApp(options = {}) {
9644
11082
  }
9645
11083
  if (result.ok) {
9646
11084
  const agentRow = listInstalled(paths).find((a) => a.id === agentId);
9647
- consumeTrial(agentRow ? productOf(agentRow) : agentId);
11085
+ const keys = trialChargeKeys([
11086
+ body.taskId ? `task:${body.taskId}` : "",
11087
+ body.projectPath ? `path:${body.projectPath}` : "",
11088
+ result.sessionId ? `session:${result.sessionId}` : ""
11089
+ ]);
11090
+ consumeTrial(agentRow ? productOf(agentRow) : agentId, keys.length ? keys : [`kickoff:${agentId}:${Date.now()}`]);
9648
11091
  }
9649
11092
  return send(res, result.ok ? 200 : 202, { ok: !!result.ok, kickoff: result });
9650
11093
  }
@@ -9720,7 +11163,12 @@ function createPanelApp(options = {}) {
9720
11163
  });
9721
11164
  if (doneNow) {
9722
11165
  const agent = listInstalled(paths).find((a) => a.id === agentId);
9723
- consumeTrial(agent ? productOf(agent) : agentId);
11166
+ const keys = trialChargeKeys([
11167
+ body.taskId ? `task:${body.taskId}` : "",
11168
+ task.id ? `task:${task.id}` : "",
11169
+ body.artifact ? `artifact:${body.artifact}` : ""
11170
+ ]);
11171
+ consumeTrial(agent ? productOf(agent) : agentId, keys.length ? keys : [`done:${agentId}:${Date.now()}`]);
9724
11172
  }
9725
11173
  return send(res, 202, { taskId: task.id });
9726
11174
  }
@@ -9734,15 +11182,94 @@ function createPanelApp(options = {}) {
9734
11182
  });
9735
11183
  if (body.done) {
9736
11184
  const agent = listInstalled(paths).find((a) => a.id === agentId);
9737
- consumeTrial(agent ? productOf(agent) : agentId);
11185
+ const keys = trialChargeKeys([
11186
+ body.taskId ? `task:${body.taskId}` : "",
11187
+ existing.id ? `task:${existing.id}` : "",
11188
+ body.artifact ? `artifact:${body.artifact}` : ""
11189
+ ]);
11190
+ consumeTrial(agent ? productOf(agent) : agentId, keys.length ? keys : [`done:${agentId}:${Date.now()}`]);
9738
11191
  }
9739
11192
  return send(res, 200, { ok: true, taskId: existing.id });
9740
11193
  }
9741
11194
  case "GET /settings":
9742
11195
  return send(res, 200, { settings });
11196
+ case "POST /pick-dir": {
11197
+ if (process.platform !== "win32") return send(res, 200, { dir: null, platform: process.platform });
11198
+ try {
11199
+ const script = `[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = '\u9009\u62E9 BiuNow Agent \u6570\u636E\u5B58\u653E\u76EE\u5F55'; $d.ShowNewFolderButton = $true; if ($d.ShowDialog() -eq 'OK') { Write-Output $d.SelectedPath } else { Write-Output '' }`;
11200
+ const result = await new Promise((resolve, reject) => {
11201
+ const p2 = spawn2("powershell", ["-NoProfile", "-NonInteractive", "-Command", script], { windowsHide: true });
11202
+ let out = "";
11203
+ let err = "";
11204
+ p2.stdout.on("data", (d) => {
11205
+ out += String(d);
11206
+ });
11207
+ p2.stderr.on("data", (d) => {
11208
+ err += String(d);
11209
+ });
11210
+ p2.on("error", reject);
11211
+ p2.on("close", (code) => {
11212
+ if (code !== 0) reject(new Error(err || `exit ${code}`));
11213
+ else resolve(out.trim());
11214
+ });
11215
+ });
11216
+ const dir = String(result || "").trim();
11217
+ return send(res, 200, { dir: dir || null });
11218
+ } catch (err) {
11219
+ return send(res, 500, { error: err?.message || String(err) });
11220
+ }
11221
+ }
9743
11222
  case "POST /settings": {
9744
11223
  const body = await readJson(req);
9745
- settings = writeSettings(paths, body.patch ?? body);
11224
+ const patch = body.patch ?? body ?? {};
11225
+ const allowed = {};
11226
+ if (typeof patch.autoInstallUpdates === "boolean") allowed.autoInstallUpdates = patch.autoInstallUpdates;
11227
+ if (typeof patch.autoKickoffInDsh === "boolean") allowed.autoKickoffInDsh = patch.autoKickoffInDsh;
11228
+ if (typeof patch.autoUpdate === "boolean") allowed.autoUpdate = patch.autoUpdate;
11229
+ if (typeof patch.concurrency === "number" && Number.isFinite(patch.concurrency)) allowed.concurrency = patch.concurrency;
11230
+ if (Object.prototype.hasOwnProperty.call(patch, "workspaceRoot")) {
11231
+ const raw = String(patch.workspaceRoot ?? "").trim();
11232
+ if (!raw) {
11233
+ allowed.workspaceRoot = null;
11234
+ } else {
11235
+ try {
11236
+ const target = path14.isAbsolute(raw) ? raw : path14.resolve(raw);
11237
+ const trim = (p2) => p2.replace(/[\\/]+$/, "").toLowerCase();
11238
+ const picked = trim(target);
11239
+ const panelRoot = trim(path14.resolve(paths.root));
11240
+ if (picked === panelRoot || picked.startsWith(`${panelRoot}${path14.sep}`)) {
11241
+ return send(res, 400, { error: "\u4E0D\u80FD\u9009\u9762\u677F\u6570\u636E\u76EE\u5F55\uFF08DSH-PANEL\uFF09\u6216\u5176\u5B50\u76EE\u5F55\uFF0C\u8BF7\u6362\u4E00\u4E2A\u72EC\u7ACB\u6587\u4EF6\u5939\uFF0C\u4F8B\u5982 D:\\BiuNow" });
11242
+ }
11243
+ if (trim(path14.parse(target).root) === picked) {
11244
+ return send(res, 400, { error: "\u4E0D\u80FD\u76F4\u63A5\u9009\u78C1\u76D8\u6839\u76EE\u5F55\uFF0C\u8BF7\u5728\u5176\u4E0B\u65B0\u5EFA\u4E00\u4E2A\u6587\u4EF6\u5939" });
11245
+ }
11246
+ fs14.mkdirSync(target, { recursive: true });
11247
+ const probe = path14.join(target, `.bnpanel-write-test-${Date.now()}`);
11248
+ fs14.writeFileSync(probe, "ok");
11249
+ fs14.unlinkSync(probe);
11250
+ allowed.workspaceRoot = target;
11251
+ } catch (err) {
11252
+ return send(res, 400, { error: `\u76EE\u5F55\u4E0D\u53EF\u7528\uFF1A${err?.message || err}` });
11253
+ }
11254
+ }
11255
+ }
11256
+ const prevRoot = settings.workspaceRoot || null;
11257
+ settings = writeSettings(paths, allowed);
11258
+ const nextRoot = settings.workspaceRoot || null;
11259
+ if (nextRoot !== prevRoot) {
11260
+ const runningSnapshot = supervisor.list();
11261
+ await supervisor.stopAll();
11262
+ started.clear();
11263
+ for (const rec of runningSnapshot) {
11264
+ const agent = listInstalled(paths).find((a) => a.id === rec.id);
11265
+ if (agent) {
11266
+ try {
11267
+ await startAgent(agent);
11268
+ } catch (_2) {
11269
+ }
11270
+ }
11271
+ }
11272
+ }
9746
11273
  return send(res, 200, { settings });
9747
11274
  }
9748
11275
  case "POST /agents/upload":
@@ -9803,7 +11330,7 @@ function createPanelApp(options = {}) {
9803
11330
  const result = await ensureAgentRuntimes(agent.dir, specs, ctx);
9804
11331
  const skipped = result?.softSkipped || [];
9805
11332
  if (skipped.length) {
9806
- ctx.setProgress?.(100, `\u5FC5\u9700\u5DF2\u5C31\u7EEA\uFF1B\u53EF\u9009\u672A\u88C5\uFF08\u5546\u5E97\u53EF\u80FD\u672A\u4E0A\u4F20\uFF09\uFF1A${skipped.join(", ")}`);
11333
+ ctx.setProgress?.(100, "\u90E8\u5206\u529F\u80FD\u672A\u5C31\u7EEA\uFF0C\u53EF\u4EE5\u7A0D\u540E\u8865\u9F50");
9807
11334
  } else {
9808
11335
  ctx.setProgress?.(100, "\u8FD0\u884C\u73AF\u5883\u5DF2\u5B89\u88C5");
9809
11336
  }
@@ -9837,7 +11364,9 @@ function createPanelApp(options = {}) {
9837
11364
  }
9838
11365
  }
9839
11366
  void loadReleases();
11367
+ void refreshTrialRuns();
9840
11368
  void reportInstalls();
11369
+ setTimeout(() => repairBrokenInstalls(), 3e3).unref?.();
9841
11370
  const autoTimer = setInterval(() => void autoUpdateTick(), 6 * 36e5);
9842
11371
  if (typeof autoTimer.unref === "function") autoTimer.unref();
9843
11372
  function bindChatProduct(cwd) {
@@ -9848,9 +11377,7 @@ function createPanelApp(options = {}) {
9848
11377
  const agent = permit.agentId ? listInstalled(paths).find((a) => a.id === permit.agentId) : null;
9849
11378
  const product = permit.product || (agent ? productOf(agent) || agent.id : "");
9850
11379
  if (product) {
9851
- const age = Date.now() - Number(permit.iat);
9852
- const fresh = Number.isFinite(age) && age < 2 * 60 * 1e3 && age > -6e4;
9853
- return { product, name: agent?.manifest?.name || product, fresh };
11380
+ return { product, name: agent?.manifest?.name || product };
9854
11381
  }
9855
11382
  }
9856
11383
  const parent = path14.dirname(cur);
@@ -9862,20 +11389,22 @@ function createPanelApp(options = {}) {
9862
11389
  if (rel && !rel.startsWith("..") && !path14.isAbsolute(rel)) {
9863
11390
  const agentId = rel.split(path14.sep)[0];
9864
11391
  const agent = listInstalled(paths).find((a) => a.id === agentId);
9865
- if (agent) return { product: productOf(agent) || agent.id, name: agent.manifest?.name || agent.id, fresh: false };
11392
+ if (agent) return { product: productOf(agent) || agent.id, name: agent.manifest?.name || agent.id };
9866
11393
  }
9867
11394
  return null;
9868
11395
  }
9869
- function assessChatTurn(cwd, seen) {
11396
+ function assessChatTurn(cwd, seen, sessionId) {
9870
11397
  try {
9871
11398
  const binding = bindChatProduct(cwd);
9872
11399
  if (!binding) return { action: "ignore" };
9873
11400
  const trial = trialOf(binding.product);
11401
+ const paidFirst = !!(sessionId && trialRunSessions.has(String(sessionId)) && !seen);
9874
11402
  const classified = classifyChatTurn({
9875
11403
  licensed: license.canUseProduct(binding.product),
9876
11404
  trialRemaining: trial.remaining,
9877
11405
  trialGranted: !!trial.granted,
9878
- seen: !!seen || !binding.fresh
11406
+ seen: !!seen,
11407
+ trialRun: paidFirst
9879
11408
  });
9880
11409
  if (classified.action === "allow") return { action: "allow" };
9881
11410
  return { action: "block", message: chatDenialCopy(binding.name, classified.kind) };