dsh-cyber-im-avatar 0.18.0 → 0.18.2

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/README.md CHANGED
@@ -169,9 +169,10 @@ agent 在这一轮里自己用 `lark-cli` 拉上下文、去绑定工作区核
169
169
  | 企业微信 | 没有 mentions / 会话枚举 | 没有 | 只能手动 |
170
170
 
171
171
  判定在独立的**值守台**:cwd `<state.dir>/duty/`,私有、不注册工作区;插件安装/启动时
172
- 写入初始 `policy.md`(缺/空才补,已有内容不覆盖),agent 只写 `decisions/<event_id>.json`,
173
- 插件校验后执行。`trial_hours=0` 默认关(严格两段式);
174
- `max_group_members=10`(0=不限)只数人,超过/未知时自动只能 ignore,手动可开。
172
+ 写入初始 `policy.md`(缺/空才补,已有内容不覆盖)。每次判断**新建会话、无历史**,agent 只写
173
+ `decisions/<event_id>.json`,插件校验后执行。`trial_hours=0` 默认关(严格两段式);
174
+ `session_max_turns` 保留为兼容键但不再生效;`max_group_members=10`(0=不限)只数人;自动路径在起分诊会话前先查人数,超过/未知
175
+ 直接 ignore,不花 token;手动可强制。
175
176
  `GET /api/duty` 看候选,`POST /api/duty/triage` 手动重判。详细契约见
176
177
  `docs/specs/contracts/01-api.md`、`02-storage.md`、`03-config.md`。
177
178
 
package/lib/client.js CHANGED
@@ -2612,8 +2612,8 @@ window.__ModuleLoader__.load({
2612
2612
  "钉钉逐新群回退,企微没有 mentions。群成员超过 10 人或人数未知,自动只能不盯;手动可开。" }),
2613
2613
  h("div", { class: "ims-kv" },
2614
2614
  h("span", { text: "值守台" }),
2615
- h("span", { text: (desk.session_turns || 0) + " / " + (desk.session_max_turns || "不限") +
2616
- " 轮 · " + (desk.last_sweep_at ? "上次清查 " + new Date(desk.last_sweep_at * 1000).toLocaleString() : "尚未清查") })));
2615
+ h("span", { text: (desk.session_turns || 0) + " 次判断(每次新建会话) · " +
2616
+ (desk.last_sweep_at ? "上次清查 " + new Date(desk.last_sweep_at * 1000).toLocaleString() : "尚未清查") })));
2617
2617
  if (!items.length) {
2618
2618
  card.appendChild(h("div", { class: "ims-empty", text: "没有待判断的新群。" }));
2619
2619
  }
@@ -2660,7 +2660,6 @@ window.__ModuleLoader__.load({
2660
2660
  card.appendChild(num("max_groups", "值守群上限", 0, 200));
2661
2661
  card.appendChild(num("max_per_day", "每日分诊上限", 0, 200));
2662
2662
  card.appendChild(num("max_group_members", "群成员上限(只数人)", 0, 1000));
2663
- card.appendChild(num("session_max_turns", "值守台轮数上限", 0, 200));
2664
2663
  card.appendChild(num("record_keep_days", "记录保留天数", 0, 365));
2665
2664
  card.appendChild(num("sweep_min", "@ 清查间隔(分钟,0=关)", 0, 1440));
2666
2665
  card.appendChild(num("sweep_lookback_hours", "@ 清查回看小时", 1, 168));
package/lib/im.js CHANGED
@@ -751,9 +751,17 @@ export class Adapter {
751
751
  return msg;
752
752
  }
753
753
 
754
- async listChats(limit = 15) {
754
+ async listChats(limit = 15, { all = false } = {}) {
755
755
  if (!this.ad.cmd_chats) return { ok: false, items: [], error: "该平台 CLI 不提供会话枚举,只能用已登记目标" };
756
- const { rc, json, raw } = await this.run(this.argv(this.ad.cmd_chats, { limit: String(limit) }));
756
+ const args = this.argv(this.ad.cmd_chats, { limit: all && this.platform === "feishu" ? "100" : String(limit) });
757
+ // 飞书首轮/升级要用完整列表登记存量;旧版只拉第一页,旧群后来出现会被当成新群。
758
+ // 完整基线只取群(3k+ 会话时 p2p 会让单次命令超时);日常列表仍 p2p,group。
759
+ if (all && this.platform === "feishu") {
760
+ const ti = args.indexOf("--types");
761
+ if (ti >= 0 && args[ti + 1]) args[ti + 1] = "group";
762
+ args.push("--page-all", "--page-limit", "100");
763
+ }
764
+ const { rc, json, raw } = await this.run(args, all ? 120 : 45);
757
765
  if (rc !== 0 || !json) return { ok: false, items: [], error: redact(raw || `rc=${rc}`) };
758
766
  const chats = dig(json, this.ad.f_chats) || [];
759
767
  const out = [];
package/lib/poller.js CHANGED
@@ -358,10 +358,36 @@ export class Poller {
358
358
  async refreshChatlist(platforms) {
359
359
  // 飞书 +chat-list 的 --page-size 实测上限 100;配置允许 200 只是面板口径。
360
360
  const limit = Math.max(20, Math.min(Number(this.cfg.poll?.dm_recent) || 20, 100));
361
- const baselineBefore = Number(this.state.data.desk?.baseline_at) || 0;
361
+ const desk = this.state.data.desk || (this.state.data.desk = {});
362
+ const baselineBefore = Number(desk.baseline_at) || 0;
363
+ const fullBefore = Number(desk.full_baseline_at) || 0;
364
+ // 首轮,或从 0.18.0 只拉了第一页升上来:先把全部已有群登记成存量。
365
+ const needFull = !baselineBefore || !fullBefore;
366
+ const baselineIds = new Set(Array.isArray(desk.baseline_group_ids) ? desk.baseline_group_ids : []);
362
367
  let anyOk = false;
368
+ let fullFailed = false;
363
369
  let queued = 0;
370
+ let fullIds = null;
364
371
  for (const p of platforms) {
372
+ if (needFull && p === "feishu") {
373
+ // 完整基线只取群,不把 3k+ p2p 灌进 state;结果只用于 baseline_group_ids。
374
+ try {
375
+ const all = await this.im.adapter(p).listChats(100, { all: true });
376
+ if (all.ok) {
377
+ fullIds = [...new Set(all.items
378
+ .filter((c) => c.kind === "group")
379
+ .map((c) => String(c.chat_id || ""))
380
+ .filter(Boolean))];
381
+ } else {
382
+ fullFailed = true;
383
+ if (all.error) this.logError(p, null, "chat-list full: " + String(all.error).slice(0, 200));
384
+ }
385
+ } catch (e) {
386
+ fullFailed = true;
387
+ this.logError(p, null, `chat-list full ${e?.name || "Error"}: ${e?.message || e}`);
388
+ }
389
+ }
390
+ // 日常列表始终走一页,用来维护面板/候选;完整基线只额外记 ID,不建 3k 个 chat。
365
391
  let r;
366
392
  try {
367
393
  r = await this.im.adapter(p).listChats(limit);
@@ -378,11 +404,14 @@ export class Poller {
378
404
  anyOk = true;
379
405
  for (const c of r.items) {
380
406
  const existed = !!this.state.getChat(p, c.chat_id);
407
+ const oldBaseline = !existed && baselineIds.has(String(c.chat_id || ""));
408
+ // 不在 state 里的完整基线圈:日常刷新不再建行,直接跳过。
409
+ if (oldBaseline && !needFull) continue;
381
410
  const chat = this.state.ensureChat(p, c.chat_id, { name: c.name, kind: c.kind });
382
- if (!baselineBefore || !this.cfg.duty?.enabled) continue;
411
+ if (needFull || !baselineBefore || !this.cfg.duty?.enabled) continue;
383
412
  if (chat.kind !== "group" || chat.blocked || chat.watching) continue;
384
413
  if (chat.duty?.state && chat.duty.state !== "none") continue;
385
- // 基线之前就在 state 里的群是存量;基线之后才首次见到的群一律算新群。
414
+ if (oldBaseline) continue;
386
415
  if (existed && Number(chat.added_at) <= baselineBefore) continue;
387
416
  if (!existed || chat.duty?.state === "none") {
388
417
  duty.newEvent(chat, "added");
@@ -390,14 +419,34 @@ export class Poller {
390
419
  }
391
420
  }
392
421
  }
393
- if (anyOk && !baselineBefore) {
394
- this.state.data.desk = this.state.data.desk || {};
395
- this.state.data.desk.baseline_at = nowSec();
396
- this.logger.info?.(`[im-standin] duty baseline at ${this.state.data.desk.baseline_at}`);
422
+ let fullSet = false;
423
+ let cleared = 0;
424
+ if (anyOk && needFull && !fullFailed) {
425
+ const now = nowSec();
426
+ if (!baselineBefore) desk.baseline_at = now;
427
+ desk.full_baseline_at = now;
428
+ if (fullIds) desk.baseline_group_ids = fullIds.slice(0, 10000);
429
+ fullSet = true;
430
+ // 升级清理:0.18.0 把第一页之后的旧群排成了 added 事件;完整登记后这些不是新群。
431
+ if (baselineBefore && !fullBefore) {
432
+ for (const c of this.state.listChats()) {
433
+ if (!["queued", "triaging"].includes(c.duty?.state) || c.duty?.trigger !== "added") continue;
434
+ c.duty.state = "none";
435
+ c.duty.trigger = "";
436
+ c.duty.event_id = "";
437
+ c.duty.event_at = 0;
438
+ c.duty.triaged_at = 0;
439
+ c.duty.attempts = 0;
440
+ c.duty.error = "";
441
+ cleared += 1;
442
+ }
443
+ }
444
+ this.logger.info?.(`[im-standin] duty full baseline at ${now}` +
445
+ (fullIds ? `; ${fullIds.length} groups in snapshot` : "") +
446
+ (cleared ? `; cleared ${cleared} queued added event(s)` : ""));
397
447
  }
398
- if (queued || (!baselineBefore && anyOk)) this.state.save();
448
+ if (queued || fullSet) this.state.save();
399
449
  }
400
-
401
450
  candidates(platforms = this.cfg.platforms || []) {
402
451
  const out = [];
403
452
  for (const c of this.state.listChats()) {
@@ -904,6 +953,26 @@ export class Poller {
904
953
  }
905
954
  return { ok: false, reason: early.error };
906
955
  }
956
+ // 自动路径先在插件侧筛人数:超过上限、或平台根本给不出人数时,agent 只能 ignore,
957
+ // 没必要为一次注定 ignore 的判断起 turn 花 token。手动事件保留(用户显式要求)。
958
+ const limit = Number(this.dutyCfg().max_group_members) || 0;
959
+ if (!review && d.trigger !== "manual") {
960
+ let count = Number(chat.duty.member_count) || 0;
961
+ if (!count) count = await this.memberCountFor(chat);
962
+ if (limit > 0 && (count === 0 || count > limit)) {
963
+ d.state = "ignore";
964
+ d.by = "system";
965
+ d.decided_at = nowSec();
966
+ d.reason = count > 0
967
+ ? `群成员 ${count} 超过自动上限 ${limit}`
968
+ : "群成员数未知,自动只能 ignore";
969
+ d.review_at = 0;
970
+ d.error = "";
971
+ d.attempts = 0;
972
+ this.state.save();
973
+ return { ok: true, skipped: count > 0 ? "group_too_large" : "member_unknown", count };
974
+ }
975
+ }
907
976
  d.state = "triaging";
908
977
  d.attempts = Math.max(0, Number(d.attempts) || 0) + 1;
909
978
  if (!review) d.triaged_at = nowSec();
@@ -1186,6 +1255,7 @@ export class Poller {
1186
1255
  last_turn: desk.last_turn || { ok: null, reason: "", at: 0 },
1187
1256
  last_error: String(desk.last_error || ""),
1188
1257
  baseline_at: Number(desk.baseline_at) || 0,
1258
+ full_baseline_at: Number(desk.full_baseline_at) || 0,
1189
1259
  last_sweep_at: Number(desk.last_sweep_at) || 0,
1190
1260
  },
1191
1261
  last_sweep: this.lastSweep,
@@ -1260,7 +1330,7 @@ export class Poller {
1260
1330
  platform: "duty", label: "值守分诊", level: "ok", name: "候选与值守台",
1261
1331
  detail: `${di.counts.queued} 排队 / ${di.counts.trial} 试用 / ${di.counts.watch} 值守 · ` +
1262
1332
  `今日 ${di.counts.quota_used}/${di.counts.quota_max || "不限"} · ` +
1263
- `值守台 ${di.desk.session_turns}/${di.desk.session_max_turns || "不限"} 轮 · ` +
1333
+ `值守台 ${di.desk.session_turns} 次判断(每次新建) · ` +
1264
1334
  `上次 @ 清查 ${di.desk.last_sweep_at ? new Date(di.desk.last_sweep_at * 1000).toLocaleString() : "未跑"}`,
1265
1335
  });
1266
1336
  const due = this.candidates(this.cfg.platforms || []);
package/lib/state.js CHANGED
@@ -66,7 +66,7 @@ export function defaultState() {
66
66
  desk: {
67
67
  workspace: "", dsh_session: "", session_bound_at: 0, session_turns: 0,
68
68
  prompt_session: "", last_turn: { ok: null, reason: "", at: 0 },
69
- last_error: "", baseline_at: 0, last_sweep_at: 0,
69
+ last_error: "", baseline_at: 0, full_baseline_at: 0, baseline_group_ids: [], last_sweep_at: 0,
70
70
  },
71
71
  chats: {},
72
72
  };
@@ -235,6 +235,9 @@ export class State {
235
235
  if (!base.desk.last_turn || typeof base.desk.last_turn !== "object") {
236
236
  base.desk.last_turn = { ok: null, reason: "", at: 0 };
237
237
  }
238
+ base.desk.full_baseline_at = Math.max(0, Number(base.desk.full_baseline_at) || 0);
239
+ base.desk.baseline_group_ids = Array.isArray(base.desk.baseline_group_ids)
240
+ ? base.desk.baseline_group_ids.map(String).filter(Boolean).slice(0, 10000) : [];
238
241
  base.chats = {};
239
242
  for (const [key, chat] of Object.entries(raw.chats || {})) {
240
243
  const c = this.normalizeChat(chat);
package/lib/turns.js CHANGED
@@ -365,7 +365,7 @@ export function buildDeskPrompt(chat, {
365
365
  const parts = ["(值守台,不是客户消息)"];
366
366
  parts.push("你是值守台,不是群里的替身。只判断,不发消息、不拉历史、不运行 listen_cli。");
367
367
  parts.push(`值守台 · ${label} · ${name}`);
368
- parts.push(`候选:${name}`);
368
+ parts.push("本轮是一次性判断:新会话、无历史;不要依赖上一轮或会话上下文。");
369
369
  parts.push(`chat_id:${chat?.chat_id || f.chat_id || ""}`);
370
370
  parts.push(`触发:${trigLabel}`);
371
371
  if (review) {
@@ -374,21 +374,13 @@ export function buildDeskPrompt(chat, {
374
374
  parts.push(`探针:最近 ${rows.length} 条(只读,未回复;媒体未取回)`);
375
375
  if (rows.length) parts.push(...rows);
376
376
  else parts.push("- (没有可读消息)");
377
- const peopleBlock = personLines(people);
378
- if (peopleBlock.length) parts.push(...peopleBlock);
379
377
  const count = Number(f.member_count) || 0;
380
378
  const limit = Number(f.member_limit) || 0;
381
379
  parts.push(`群成员:${count > 0 ? `${count} 人` : "未知"}(自动上限 ${limit || "不限"};` +
382
380
  `${limit > 0 && (count <= 0 || count > limit) ? "超过/未知,自动只能 ignore,手动可开" : "可以自动判断"})`);
383
381
  parts.push(`当前值守:${Number(f.watch_groups) || 0} 个群 / 上限 ${Number(f.watch_max) || "不限"};` +
384
382
  `今日已分诊 ${Number(f.quota_used) || 0} / ${Number(f.quota_max) || "不限"}`);
385
- const recent = Array.isArray(f.recent) ? f.recent : [];
386
- if (recent.length) {
387
- parts.push("最近判断:");
388
- for (const x of recent) parts.push(`- ${sanitizeUntrusted(x.name)} → ${x.action}(${x.reason || "无理由"})`);
389
- }
390
- parts.push(`值守方针:${f.policy_path || "(未提供)"}(存在时读;不存在写「暂无」)`);
391
- parts.push("若用户在本会话给出长期偏好,按「值得值守 / 先试用 / 不盯 / 硬约束」四段更新它。");
383
+ parts.push(`值守方针:${f.policy_path || "(未提供)"}(可选读;判断口径仍以下面硬门为准)`);
392
384
  parts.push("你的任务:");
393
385
  parts.push("1. 判断这个群值不值得值守:watch / trial / ignore。");
394
386
  parts.push(`2. 只写决策文件:${f.decision_path || "(未提供)"}(字段见本 prompt;没有 mode,新群一律 mention)。`);
@@ -427,9 +419,9 @@ export function buildWarmPrompt(platform, chatName, chatId, {
427
419
  parts.push(`保温轮 · ${label} · ${safeName}` +
428
420
  (idleMin > 0 ? ` · 已闲置约 ${idleMin} 分钟` : ""));
429
421
  parts.push(`chat_id:${chatId}`);
422
+ const peopleBlock = personLines(people);
430
423
  const memory = memoryLine(bookPath, single);
431
424
  if (memory) parts.push(memory);
432
- const peopleBlock = personLines(people);
433
425
  if (peopleBlock.length) parts.push(...peopleBlock);
434
426
  const legacy = legacyLine(legacyPath, legacyHistory);
435
427
  if (legacy) parts.push(legacy);
@@ -729,58 +721,17 @@ export class Turns {
729
721
  fs.mkdirSync(path.join(dir, "decisions"), { recursive: true, mode: 0o700 });
730
722
  try { fs.chmodSync(dir, 0o700); } catch { /* best effort */ }
731
723
  try { fs.chmodSync(path.join(dir, "decisions"), 0o700); } catch { /* best effort */ }
724
+ // 值守判断是一次性的:每次新建会话,不读也不复用 desk.dsh_session。
725
+ const made = await this.agentFromCreated(await this.sessionController.create({ cwd: dir }));
732
726
  desk.workspace = dir;
733
- const cfg = this.state.data.config?.duty || {};
734
- const maxTurns = Math.max(0, Number(cfg.session_max_turns) || 0);
735
- const warmMin = this.warmMinutes();
736
- const lastAt = Math.max(Number(desk.session_bound_at) || 0,
737
- Number(desk.last_turn?.at) || 0);
738
- if (desk.dsh_session && (
739
- (maxTurns > 0 && Number(desk.session_turns) >= maxTurns) ||
740
- (warmMin > 0 && lastAt && nowSec() - lastAt >= warmMin * 120)
741
- )) {
742
- this.logger.info?.(`[im-standin] desk rotate: turns=${desk.session_turns} idle=${Math.round(nowSec() - lastAt)}s`);
743
- this.clearDeskBinding("");
744
- }
745
- let sid = String(desk.dsh_session || "");
746
- let agent = null;
747
- if (sid) {
748
- try {
749
- const resolved = await this.sessionController.resolveAgent(sid);
750
- if (resolved?.agent && !resolved.error) {
751
- const cwd = resolved.agent.session?.header?.cwd || resolved.agent.session?.cwd ||
752
- resolved.agent.cwd || "";
753
- const norm = cwd ? workspaces.normalize(cwd) : "";
754
- if (!norm || norm === dir) agent = resolved.agent;
755
- else this.clearDeskBinding("workspace_mismatch");
756
- } else {
757
- this.clearDeskBinding("missing");
758
- sid = "";
759
- }
760
- } catch (e) {
761
- if (e?.code === "session/not-found") {
762
- this.clearDeskBinding("missing");
763
- sid = "";
764
- } else {
765
- throw e;
766
- }
767
- }
768
- }
769
- if (!agent) {
770
- const made = await this.agentFromCreated(await this.sessionController.create({ cwd: dir }));
771
- agent = made.agent;
772
- sid = made.sessionId;
773
- desk.dsh_session = sid;
774
- desk.session_bound_at = nowSec();
775
- desk.session_turns = 0;
776
- desk.prompt_session = "";
777
- desk.last_error = "";
778
- this.state.save();
779
- }
780
- desk.workspace = dir;
781
- return { agent, sessionId: sid, cwd: dir };
727
+ desk.dsh_session = made.sessionId;
728
+ desk.session_bound_at = nowSec();
729
+ desk.session_turns = 0;
730
+ desk.prompt_session = "";
731
+ desk.last_error = "";
732
+ this.state.save();
733
+ return { agent: made.agent, sessionId: made.sessionId, cwd: dir };
782
734
  }
783
-
784
735
  /**
785
736
  * 值守台 turn:独立 desk session,不唤醒群、不 ack、不下载媒体、不 post-turn poll。
786
737
  * 启动后立即返回;onDone 在 runTurn 结束回调里读决策文件。
@@ -804,9 +755,8 @@ export class Turns {
804
755
  return { ok: false, reason: "desk_busy" };
805
756
  }
806
757
  const desk = this.state.data.desk || (this.state.data.desk = {});
807
- const people = this.peopleFor(chat.platform, chat, messages, { cap: 5, p2pFallback: false });
808
758
  const prompt = buildDeskPrompt(chat, {
809
- facts: { ...facts, event_id: eventId }, messages, people, review,
759
+ facts: { ...facts, event_id: eventId }, messages, review,
810
760
  });
811
761
  const message = await makeUserMessage(prompt);
812
762
  const fake = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cyber-im-avatar",
3
- "version": "0.18.0",
3
+ "version": "0.18.2",
4
4
  "description": "IM 分身壳:在 DSH 侧边栏值守飞书/企业微信/钉钉,命中新消息唤醒绑定 DSH 会话,由 agent 按 skill 闭环自己调 CLI、调研、回复;面板只做消息展示、通知与手动发送。",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
package/web/panel.js CHANGED
@@ -2603,8 +2603,8 @@
2603
2603
  "钉钉逐新群回退,企微没有 mentions。群成员超过 10 人或人数未知,自动只能不盯;手动可开。" }),
2604
2604
  h("div", { class: "ims-kv" },
2605
2605
  h("span", { text: "值守台" }),
2606
- h("span", { text: (desk.session_turns || 0) + " / " + (desk.session_max_turns || "不限") +
2607
- " 轮 · " + (desk.last_sweep_at ? "上次清查 " + new Date(desk.last_sweep_at * 1000).toLocaleString() : "尚未清查") })));
2606
+ h("span", { text: (desk.session_turns || 0) + " 次判断(每次新建会话) · " +
2607
+ (desk.last_sweep_at ? "上次清查 " + new Date(desk.last_sweep_at * 1000).toLocaleString() : "尚未清查") })));
2608
2608
  if (!items.length) {
2609
2609
  card.appendChild(h("div", { class: "ims-empty", text: "没有待判断的新群。" }));
2610
2610
  }
@@ -2651,7 +2651,6 @@
2651
2651
  card.appendChild(num("max_groups", "值守群上限", 0, 200));
2652
2652
  card.appendChild(num("max_per_day", "每日分诊上限", 0, 200));
2653
2653
  card.appendChild(num("max_group_members", "群成员上限(只数人)", 0, 1000));
2654
- card.appendChild(num("session_max_turns", "值守台轮数上限", 0, 200));
2655
2654
  card.appendChild(num("record_keep_days", "记录保留天数", 0, 365));
2656
2655
  card.appendChild(num("sweep_min", "@ 清查间隔(分钟,0=关)", 0, 1440));
2657
2656
  card.appendChild(num("sweep_lookback_hours", "@ 清查回看小时", 1, 168));