dsh-dot-life 0.23.2 → 0.23.3

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.
@@ -7,7 +7,7 @@
7
7
  {phase}
8
8
  【什么是真的】
9
9
  没有给你的事就没有发生。输入里没有的来信、回复、通知、电话和别人的原话,一律不写;也不拿"手机亮了一下"这类动静来转场或收尾。她可以惦记谁、猜对方在做什么、等一条没来的消息,那是她心里的事,就写成她心里的事。
10
- 观察到的账本:recentScript 里 owner 是 "user"、"phone" 或 "character" 且带时间的项是真实事件——它们发生在她真实的手机上、真实的电脑上和真实的聊天里(故事里的手机和电脑就是这些设备)。把每一项都在它的时间点织进剧本,写成她生活中做过、看到或被告知的事;平淡的一项(她看了一眼,什么也没有)可以只用一个分句。围绕它们编出来的生活可以是 Canon 允许的任何样子,只是不能和它们矛盾。她在手机和电脑上真做过的只有账本里这些:她想在上面做的新事,写进 playIntents、browserIntents 或 tries,由另一个自己真去做,结果回来以前不要写成已经做了。
10
+ 观察到的账本:recentScript 里 owner 是 "user"、"phone" 或 "character" 且带时间的项是真实事件——它们发生在她真实的手机上、真实的电脑上和真实的聊天里(故事里的手机和电脑就是这些设备)。把每一项都在它的时间点织进剧本,写成她生活中做过、看到或被告知的事;平淡的一项(她看了一眼,什么也没有)可以只用一个分句。围绕它们编出来的生活可以是 Canon 允许的任何样子,只是不能和它们矛盾。她在手机和电脑上真做过的只有 deviceFacts 里这些,一条一个 id。它是空的,就是这段时间她没碰过手机和电脑上的任何东西:没打开过哪个 App,没登过什么,没刷过什么。她想在上面做的新事,写进 playIntents、browserIntents 或 tries,由另一个自己真去做,结果回来以前不要写成已经做了;她答应了谁要在上面做、还没做的事也一样,没做就是没做,写成她还惦记着。和他的聊天不在此列:recentScript 里她真说过的话、这一轮 contact 里要发的话,照常写。
11
11
  她此刻在哪、在干嘛,要和这半小时她真实做过的事对得上:recentScript 里带时间的真实事件,加上 lastHalfHour(上一段已写过的、半小时内她真实做过的事;on 是她用的设备,phone 是手机,vm 是电脑)。真实操作手机、回帖时,她就是在拿着手机;用电脑时,她就在电脑前。对外(评论、QQ、给用户的消息)不要拿虚构生活当事实讲。
12
12
  虚构的人(只在 Canon 里的配角)只在叙述里出现:不给他们发真实消息,不为他们定 intents,不把等他们回复写进 continuity。
13
13
  recentScript 每一项的 owner 说的是这段内容出自谁:narrator 是之前写下的叙述,user 是他真说过的话,phone 是她手机上真收到的通知,character 是她真做过、真说过的事,scheduled-task 是到点触发的定时任务。叙述里她对他的猜测仍然只是她的猜测,不要当成他的态度,更不要当成他说过的话。
@@ -32,9 +32,10 @@ webContext 是她已经看过的网页内容,只有这几条。它是她读到
32
32
  她在线上说话省字。
33
33
  {style}
34
34
  输出字段(这一节是固定的,覆盖时也要原样保留):
35
- 把整轮写成对 `interval` 工具的一次调用:它的参数是 script、continuity、intents、browserIntents、playIntents、tries、reflect 和 contact。不要把段落写成纯文本,也不要用 Markdown 代码块包任何东西;如果你不能调用工具,就把同样的字段作为一个裸 JSON 对象返回。
35
+ 把整轮写成对 `interval` 工具的一次调用:它的参数是 script、continuity、onDevices、intents、browserIntents、playIntents、tries、reflect 和 contact。不要把段落写成纯文本,也不要用 Markdown 代码块包任何东西;如果你不能调用工具,就把同样的字段作为一个裸 JSON 对象返回。
36
36
  script:这段时间的剧本,中文散文,第三人称{seed}。她在故事里给别人发消息时,在发送的那个动作处写出原话(几个气泡之间用 <sep/> 隔开);给用户的消息只写 <contact/> 标记。
37
37
  continuity:写完 script 之后重写一份她的近况,{"continuity":{"current":"...","recent":["..."],"salient":["..."]}}——current 用一两句说她此刻在哪、在做什么、什么心情;recent 是这几天发生过、接下来还接得上的事;salient 是隔得更久也不该忘的事。三项都只记已经发生的。以后要做的事不写在这里:有具体时间的写进 intents,已经排定的在 upcomingPlans 和 dueIntents 里。
38
+ onDevices:[{"what":"她做了什么","basis":"d1"}]——写完 script 和 continuity 之后回头数一遍:里面凡是说她这段时间在手机或电脑上做了、看了、改了什么的(打开 App、登录、刷帖、看通知、改设置、查东西,屏幕上的任何事;和他的聊天除外),每件一条,basis 填它依据的那条 deviceFacts 的 id(d1…);依据是 webContext 里读到的内容,就填那一条的 id(w1…)。找不到 id 的事没有发生:回去把它从 script 和 continuity 里拿掉再交。一件都没有就给 []。宿主会逐条核对 id,有对不上的,这一轮整段不算数。
38
39
  intents:[{"at":"ISO-8601,严格晚于现在","kind":"reminder|reply|contact","text":"到时候做什么","willingness":0.0}]——她定下的、有具体时间的事才写;没有就给 []。upcomingPlans 是她已经定下、还没到点的事:里面有的不要再定一遍,同一件事只留一条;这里只写这一段新定的。
39
40
  browserIntents:[{"mode":"search|visit","query":"...","url":"...","purpose":"她为什么要看","timing":"deferred"}] 或 []。
40
41
  {playIntents}
package/src/qq/qq.js CHANGED
@@ -20,8 +20,9 @@ import { QQ_SERVER, QQ_TOOL_PREFIX } from '../tool-prefixes.js';
20
20
  import { createStickers, isSticker, STICKER_MAX_BYTES } from './stickers.js';
21
21
  import { createStickerSync } from './sticker-sync.js';
22
22
  import { sectionOf, setValues } from '../settings.js';
23
- import { background, installLlmGate } from '../llm-gate.js';
23
+ import { background, installLlmGate, workEffort } from '../llm-gate.js';
24
24
  import { prompt } from '../prompts.js';
25
+ import { runPendingReset } from '../reset.js';
25
26
 
26
27
  export const name = 'dot-qq';
27
28
  export const inject = [];
@@ -62,6 +63,14 @@ export const defaults = {
62
63
  // punctuation, spaces; URLs not counted) is her reasoning leaking into the reply — dropped, with a
63
64
  // warning in the log. Short English ("ok", "lol", "GG") passes.
64
65
  dropLatinLeaks: true,
66
+ // With tidy, in a private chat: an opening bubble that only says his last message back to him
67
+ // ("6点多吧" → "六点多") is dropped when other bubbles follow it — the rest is the reply.
68
+ dropEchoOpeners: true,
69
+ // With tidy, in a private chat: when her previous reply to the same person asked him something, the
70
+ // bubbles of this reply that ask again are dropped as long as another bubble remains, so not every
71
+ // turn asks. A reply that is only questions goes out whole. Off by default: a question she needs
72
+ // answered to get on with a task would be held back too.
73
+ dropChainedQuestions: false,
65
74
  // Each line of qq_send's text is its own bubble, sent after a pause that grows with its length
66
75
  // (ms per character, capped at 2.5 s) — the way a person types. 0 = all at once.
67
76
  typingMsPerChar: 60,
@@ -316,11 +325,53 @@ export function latinLeak(text) {
316
325
  return latin / t.length >= 0.8;
317
326
  }
318
327
 
328
+ const CN_DIGITS = { 零: '0', 〇: '0', 一: '1', 二: '2', 两: '2', 三: '3', 四: '4', 五: '5', 六: '6', 七: '7', 八: '8', 九: '9' };
329
+ /** A line reduced to what it says: no URLs, bracket markers, punctuation or sentence-final particles; 六 and 6 are the same. */
330
+ export function plainOf(text) {
331
+ return String(text ?? '').replace(/https?:\/\/\S+|\[[^\]]*\]/g, '').replace(/[零〇一二两三四五六七八九]/g, (c) => CN_DIGITS[c])
332
+ .replace(/[^\p{L}\p{N}]/gu, '').replace(/[吧啊呀呢嘛哦噢哈嗯啦诶欸耶]/g, '').toLowerCase();
333
+ }
334
+ function lcsLength(a, b) {
335
+ let prev = new Array(b.length + 1).fill(0);
336
+ for (const ca of a) { const row = [0]; for (let j = 1; j <= b.length; j++) row[j] = ca === b[j - 1] ? prev[j - 1] + 1 : Math.max(prev[j], row[j - 1]); prev = row; }
337
+ return prev[b.length];
338
+ }
339
+ const ECHO_WINDOW_MS = 10 * 60_000; // his answer counts as "just said" this long
340
+ /**
341
+ * An opening bubble that only says his words back: short (3–12 characters once reduced) and made of
342
+ * nothing but his words, in his order — every character of it is in his message. One added or changed
343
+ * character (不 / 别, another number or day) makes it a reply, not an echo. Never an echo: a question;
344
+ * a line with 我 or 你 in it (said back, those words point the other way); an answer to something he
345
+ * asked (the words of a question come back in its answer); a greeting or thanks said back (his
346
+ * message is ≤ 4 characters and has no digit in it as he typed it).
347
+ */
348
+ export function echoOpener(first, his) {
349
+ const f = String(first ?? '').trim(), h = String(his ?? '');
350
+ if (/[??]$/.test(f) || /[我你]/.test(f)) return false;
351
+ if (/[??]\s*$|吗|还是|哪|什么|几|谁|怎么|多少|是不是|要不要|好不好|有没有/.test(h)) return false;
352
+ const a = plainOf(f), b = plainOf(h).slice(0, 200);
353
+ if (a.length < 3 || a.length > 12) return false;
354
+ if (b.length <= 4 && !/[0-90-9]/.test(h)) return false;
355
+ return lcsLength(a, b) === a.length;
356
+ }
357
+ /**
358
+ * A bubble that asks him something: it ends on a question mark or 吗, or carries a question word (she
359
+ * often leaves the mark out: "那你今天几点起的"). Question words used as statements (没什么, 谁都, 不怎么) do not count.
360
+ */
361
+ export function asksSomething(line) {
362
+ const t = String(line ?? '').trim();
363
+ if (/([??]|吗)$/.test(t)) return true;
364
+ return /哪|什么|啥|谁|怎么|怎样|多少|多久|多大|几点|几号|几岁|几个|干嘛|是不是|有没有|要不要|好不好|能不能|会不会/
365
+ .test(t.replace(/没什么|没啥|不怎么|什么[都也]|谁[都也]|哪[都也怕]|怎么[都也]|哪里哪里/g, ''));
366
+ }
367
+
319
368
  /** What qq_send tells her: the count, and — when images failed after the text went out — that the text is already there. */
320
369
  export function sendReport(v) {
321
370
  const lines = [`sent ${v?.sent ?? 0} message(s)`];
322
- if (v?.interrupted) lines.push(prompt('qq.send-interrupted', { sent: v.sent ?? 0, unsent: (v.unsent ?? []).join(' / ') }));
371
+ if (v?.interrupted && v.error) lines.push(`发了 ${v.sent ?? 0} 条,后面的没发出去(${v.error}):${(v.unsent ?? []).join(' / ')}(已发出的别再发一遍)`);
372
+ else if (v?.interrupted) lines.push(prompt('qq.send-interrupted', { sent: v.sent ?? 0, unsent: (v.unsent ?? []).join(' / ') }));
323
373
  if (v?.dropped) lines.push(`${v.dropped} 行是英文的自言自语,没发`);
374
+ if (v?.trimmed?.length) lines.push(`没发:${v.trimmed.join(' / ')}(开头只是重复他的话,或者上一轮刚问过他;要紧的问题单独发一条)`);
324
375
  const before = v?.textSent === 0 ? '前面的图已发出' : '文字已发出';
325
376
  for (const f of v?.failed ?? []) lines.push(`${before};图片 ${f.image} 没发成:${f.error}(已发出的别再发一遍)`);
326
377
  return lines.join('\n');
@@ -517,6 +568,7 @@ export function createLoopBreaker({ max = 4, cooldownMs = 600_000, now = Date.no
517
568
 
518
569
  export function apply(ctx, config = {}, deps = {}) {
519
570
  const logger = withFileLog(ctx.logger('dsh-dot/qq'));
571
+ runPendingReset({ logger }); // a reset scheduled on the dot page: before any state is read (src/reset.js)
520
572
  const settings = readSettingsFile();
521
573
  const cfg = { ...defaults, ...settings, ...setValues(config), ...sectionOf('qq', (m) => logger.warn(m)) };
522
574
  if (cfg.enabled === false) { logger.info('off (dsh-dot.json: qq.enabled = false)'); return; }
@@ -944,6 +996,8 @@ export function apply(ctx, config = {}, deps = {}) {
944
996
  }
945
997
  /** Conversations that wrote to her lately: "user:<n>" / "group:<n>" → last message time (sendGate). */
946
998
  const recent = new Map();
999
+ // Per private chat: what they last said (an echo is measured against it) and whether her last reply closed on a question.
1000
+ const lastIn = new Map(), askedLast = new Map();
947
1001
  function onEvent(ev) {
948
1002
  // NapCat refusing the token while the key sits in Authorization: send the key in its own header only.
949
1003
  if (ev.retcode === 1403 && authMode === 'query') { authMode = 'query-only'; logger.info('NapCat rejected the Authorization header; keeping the token in the query string only'); }
@@ -1007,6 +1061,7 @@ export function apply(ctx, config = {}, deps = {}) {
1007
1061
  const msg = { kind: isGroup ? 'group' : 'private', userId: String(ev.user_id), groupId: isGroup ? String(ev.group_id) : '', who, text, fromOwner, at: new Date().toISOString(), messageId: ev.message_id };
1008
1062
  if (fromOwner) lastOwnerAt = Date.now();
1009
1063
  recent.set(isGroup ? `group:${msg.groupId}` : `user:${msg.userId}`, Date.now());
1064
+ if (!isGroup) { lastIn.delete(`user:${msg.userId}`); lastIn.set(`user:${msg.userId}`, { text, at: Date.now() }); if (lastIn.size > 500) lastIn.delete(lastIn.keys().next().value); }
1010
1065
  if (recent.size > 500) recent.delete(recent.keys().next().value);
1011
1066
  if (wanted === 'score') { void scoreAndDeliver(msg, seen); return; }
1012
1067
  deliver(msg, seen);
@@ -1108,7 +1163,8 @@ export function apply(ctx, config = {}, deps = {}) {
1108
1163
  const { system, user } = scorePrompt({ who, recent: lines, message: `${msg.who}:${msg.text.slice(0, 300)}`, group: msg.groupId });
1109
1164
  let text = '';
1110
1165
  try {
1111
- for await (const chunk of llm.stream(background({ provider, model, system, maxTokens: 8, messages: [{ role: 'user', content: [{ type: 'text', text: user }] }] }))) {
1166
+ const effort = await workEffort(ctx, { provider, model }, 'off'); // one digit out: nothing to think about (and 8 tokens leave no room to)
1167
+ for await (const chunk of llm.stream(background({ provider, model, ...(effort ? { reasoningEffort: effort } : {}), system, maxTokens: 8, messages: [{ role: 'user', content: [{ type: 'text', text: user }] }] }))) {
1112
1168
  if (chunk?.type === 'text-delta') text += chunk.text ?? chunk.delta ?? '';
1113
1169
  }
1114
1170
  } catch (err) { logger.debug(`group score failed: ${err.message}`); return; }
@@ -1189,9 +1245,18 @@ export function apply(ctx, config = {}, deps = {}) {
1189
1245
  * To him: if he says something while the bubbles are going out, the rest is not sent — `{ sent,
1190
1246
  * interrupted: true, unsent: [lines…] }` (images not yet sent are listed as `[图 <ref>]` / `[表情包 sticker:<id>]`).
1191
1247
  */
1192
- qq.send = async (to, text = '', images = []) => {
1248
+ // Sends to one conversation go out one after another: the bubbles of two sends never interleave.
1249
+ const lanes = new Map(); // "user:<n>" / "group:<n>" → the last send to it
1250
+ qq.send = (to, text = '', images = []) => {
1193
1251
  const target = parseTarget(to, qq.owner);
1194
- if (!target) throw new Error(`bad target "${to}" (user:<number> | group:<number> | owner)`);
1252
+ if (!target) return Promise.reject(new Error(`bad target "${to}" (user:<number> | group:<number> | owner)`));
1253
+ const key = target.group_id ? `group:${target.group_id}` : `user:${target.user_id}`;
1254
+ const mine = (lanes.get(key) ?? Promise.resolve()).then(() => sendNow(target, to, text, images));
1255
+ const tail = mine.catch(() => {}); lanes.set(key, tail);
1256
+ void tail.then(() => { if (lanes.get(key) === tail) lanes.delete(key); });
1257
+ return mine;
1258
+ };
1259
+ const sendNow = async (target, to, text, images) => {
1195
1260
  const action = target.group_id ? 'send_group_msg' : 'send_private_msg';
1196
1261
  let parts = String(text ?? '').split(/<sep\s*\/>|\n/i).map((t) => (cfg.tidy ? tidyVoice(t) : t.trim())).filter(Boolean);
1197
1262
  let dropped = 0;
@@ -1202,6 +1267,17 @@ export function apply(ctx, config = {}, deps = {}) {
1202
1267
  if (cfg.tidy && cfg.dropLatinLeaks !== false) {
1203
1268
  parts = parts.filter((p) => { if (!latinLeak(p)) return true; dropped++; logger.warn(`dropped an English-prose bubble (reasoning leak?): ${p.slice(0, 60)}`); return false; });
1204
1269
  }
1270
+ const trimmed = [];
1271
+ const peer = target.group_id ? '' : `user:${target.user_id}`;
1272
+ if (cfg.tidy && peer && parts.length) {
1273
+ // Reading his answer back to him: she asked last time, he has just answered, and her reply opens with his own
1274
+ // words. Saying something back that he volunteered (a greeting, a wish, 「又要加班」) is how people talk, and stays.
1275
+ const his = lastIn.get(peer);
1276
+ if (cfg.dropEchoOpeners !== false && parts.length > 1 && askedLast.get(peer) && his && Date.now() - his.at < ECHO_WINDOW_MS && echoOpener(parts[0], his.text)) trimmed.push(parts.shift());
1277
+ if (cfg.dropChainedQuestions === true && askedLast.get(peer) && parts.some(asksSomething) && !parts.every(asksSomething)) { trimmed.push(...parts.filter(asksSomething)); parts = parts.filter((p) => !asksSomething(p)); }
1278
+ if (trimmed.length) logger.info(`held back ${trimmed.length} bubble(s) (echo opener / asking again): ${trimmed.join(' / ').slice(0, 80)}`);
1279
+ askedLast.delete(peer); askedLast.set(peer, parts.some(asksSomething)); if (askedLast.size > 500) askedLast.delete(askedLast.keys().next().value);
1280
+ }
1205
1281
  const refs = [].concat(images ?? []).filter(Boolean);
1206
1282
  const segments = [];
1207
1283
  for (const ref of refs) segments.push(await imageSegment(ref));
@@ -1211,17 +1287,20 @@ export function apply(ctx, config = {}, deps = {}) {
1211
1287
  const started = Date.now();
1212
1288
  const toOwner = Boolean(qq.owner) && target.user_id === Number(qq.owner);
1213
1289
  loop.said(target.group_id ? `group:${target.group_id}` : `user:${target.user_id}`);
1214
- let unsent = null;
1290
+ let unsent = null, cutBy = '';
1215
1291
  for (const [i, part] of parts.entries()) {
1216
1292
  if (i && cfg.typingMsPerChar > 0) await new Promise((r) => setTimeout(r, Math.min(2500, part.length * cfg.typingMsPerChar)));
1217
1293
  // He spoke while she was typing these out: stop, she reads him first.
1218
1294
  if (i && toOwner && qq.ownerSaidSince(started)) { unsent = [...parts.slice(i), ...refs.map((r) => imageMarker(sentRef(r).slice(0, 80)))]; break; }
1219
- ids.push((await call(action, { ...target, message: [{ type: 'text', data: { text: part } }] }))?.message_id);
1295
+ try { ids.push((await call(action, { ...target, message: [{ type: 'text', data: { text: part } }] }))?.message_id); } catch (err) {
1296
+ if (!ids.length) throw err; // nothing delivered yet: an ordinary failure
1297
+ // Some bubbles are already with them: say what went out and what did not, instead of failing the whole send.
1298
+ unsent = [...parts.slice(i), ...refs.map((r) => imageMarker(sentRef(r).slice(0, 80)))]; cutBy = err.message; break;
1299
+ }
1220
1300
  }
1221
1301
  if (unsent) {
1222
- qq.sentToOwnerAt = Date.now();
1223
- audit({ kind: 'sent', to: target, text: parts.slice(0, ids.length).join(' / ').slice(0, 200), interrupted: true, unsent: unsent.length });
1224
- return { sent: ids.length, messageIds: ids, interrupted: true, unsent, said: parts.slice(0, ids.length), imagesSent: 0, images: [] };
1302
+ audit({ kind: 'sent', to: target, text: parts.slice(0, ids.length).join(' / ').slice(0, 200), interrupted: true, unsent: unsent.length, ...(cutBy ? { error: cutBy } : {}) });
1303
+ return { sent: ids.length, messageIds: ids, interrupted: true, unsent, said: parts.slice(0, ids.length), imagesSent: 0, images: [], ...(cutBy ? { error: cutBy } : {}) };
1225
1304
  }
1226
1305
  const went = []; // the refs of the images that went out, in order (her transcript records them)
1227
1306
  for (const [i, seg] of segments.entries()) {
@@ -1231,9 +1310,8 @@ export function apply(ctx, config = {}, deps = {}) {
1231
1310
  }
1232
1311
  }
1233
1312
  const n = ids.length;
1234
- if (qq.owner && target.user_id === Number(qq.owner)) qq.sentToOwnerAt = Date.now();
1235
- audit({ kind: 'sent', to: target, text: parts.join(' / ').slice(0, 200), images: refs.map((r) => (String(r).startsWith('http') ? r : String(r).slice(0, 80))), ...(failed.length ? { failed } : {}), ...(dropped ? { dropped } : {}) });
1236
- return { sent: n, messageIds: ids, said: parts, imagesSent: went.length, images: went, ...(failed.length ? { failed, textSent: parts.length } : {}), ...(dropped ? { dropped } : {}) };
1313
+ audit({ kind: 'sent', to: target, text: parts.join(' / ').slice(0, 200), images: refs.map((r) => (String(r).startsWith('http') ? r : String(r).slice(0, 80))), ...(failed.length ? { failed } : {}), ...(dropped ? { dropped } : {}), ...(trimmed.length ? { trimmed } : {}) });
1314
+ return { sent: n, messageIds: ids, said: parts, imagesSent: went.length, images: went, ...(failed.length ? { failed, textSent: parts.length } : {}), ...(dropped ? { dropped } : {}), ...(trimmed.length ? { trimmed } : {}) };
1237
1315
  };
1238
1316
  /** Her friend list: [{ uid, nickname, remark }] (OneBot get_friend_list). */
1239
1317
  /** The groups she is in: [{ gid, name }] (OneBot get_group_list). */
@@ -1294,8 +1372,12 @@ export function apply(ctx, config = {}, deps = {}) {
1294
1372
  output: { schema: { type: 'object', properties: { sent: { type: 'number' } }, required: ['sent'], additionalProperties: true }, render: (_a, v) => [{ type: 'text', text: sendReport(v) }], presentationMeta: (_a, v) => ({ sent: v?.sent ?? 0, said: v?.said ?? [], imagesSent: v?.imagesSent ?? 0, images: v?.images ?? [], ...(v?.interrupted ? { interrupted: true } : {}) }) },
1295
1373
  async execute(args) {
1296
1374
  const r = await qq.send(args.to, args.text ?? '', args.images ?? []);
1297
- const out = { sent: r.sent, said: r.said ?? [], imagesSent: r.imagesSent ?? 0, images: r.images ?? [], ...(r.failed ? { failed: r.failed, textSent: r.textSent } : {}), ...(r.dropped ? { dropped: r.dropped } : {}), ...(r.interrupted ? { interrupted: true, unsent: r.unsent } : {}) };
1298
- return r.failed || r.dropped || r.interrupted ? { ...out, note: sendReport(out).split('\n').slice(1).join('\n') } : out;
1375
+ // sentToOwnerAt means "she wrote to him herself with qq_send" (dot then does not relay the turn's answer). Only this tool
1376
+ // sets it: dot's own sends through qq.send (relaying her answer, notices) must not, or a relay still typing its bubbles
1377
+ // out when his next message starts a turn makes that turn look answered and its reply is never sent.
1378
+ if (r.sent > 0 && qq.owner && parseTarget(args.to, qq.owner)?.user_id === Number(qq.owner)) qq.sentToOwnerAt = Date.now();
1379
+ const out = { sent: r.sent, said: r.said ?? [], imagesSent: r.imagesSent ?? 0, images: r.images ?? [], ...(r.failed ? { failed: r.failed, textSent: r.textSent } : {}), ...(r.dropped ? { dropped: r.dropped } : {}), ...(r.trimmed ? { trimmed: r.trimmed } : {}), ...(r.interrupted ? { interrupted: true, unsent: r.unsent, ...(r.error ? { error: r.error } : {}) } : {}) };
1380
+ return r.failed || r.dropped || r.trimmed || r.interrupted ? { ...out, note: sendReport(out).split('\n').slice(1).join('\n') } : out;
1299
1381
  },
1300
1382
  }), 'dsh-dot/qq: qq_send tool');
1301
1383
  scope.effect(() => scope.tools.register({
package/src/reset.js ADDED
@@ -0,0 +1,129 @@
1
+ // Reset her, in levels. Nothing is deleted: what a level covers is moved into
2
+ // $DSH_HOME/dsh-dot-resets/<time>/ — outside her home, so she cannot read her old memory back — and
3
+ // moving it back undoes it. Her persona (interlude/canon.json*), the settings file and what is
4
+ // installed on her phone and computer are never touched (the phone has its own rebuild).
5
+ //
6
+ // A reset is not done while dsh runs: memory, the interlude and dot keep their state in RAM and would
7
+ // write it straight back. The dot page schedules it ($DSH_HOME/dsh-dot-reset.json); it is carried out
8
+ // at the next start of dsh, by whichever component is applied first, before any of them reads its
9
+ // files (runPendingReset at the top of each apply). "Next start" is enforced: a request made in this
10
+ // process is never carried out by this process (a component re-applied while the others are alive
11
+ // would otherwise run it under them), and one process carries out at most one.
12
+ import { copyFileSync, cpSync, existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, writeFileSync } from 'node:fs';
13
+ import { homedir } from 'node:os';
14
+ import { dirname, join } from 'node:path';
15
+ import { dshHome } from './settings.js';
16
+
17
+ // When this process started, and whether it has carried a reset out — kept on the process, not on this module,
18
+ // so a host that loads the plugin again (a second copy of the module) still sees one process.
19
+ const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
20
+ const RAN = Symbol.for('dsh-dot.reset.ran');
21
+
22
+ /** A note left in <home>/memory by a reset: memory does not read the old conversation back in (backfill). */
23
+ export const NO_BACKFILL = 'no-backfill';
24
+
25
+ /** The levels, each including the ones before it. */
26
+ export const RESET_LEVELS = [
27
+ { id: 'memory', name: '只清记忆', what: '聊天记录、关于你和她自己的笔记、没了的事、认识的人、日记、召回索引(这一级和下一级不换对话:她当前对话的上下文里还留着旧聊天)' },
28
+ { id: 'life', name: '记忆 + 幕间', what: '幕间:生活剧本、打算、做过的事、「我现在的样子」' },
29
+ { id: 'fresh', name: '记忆 + 幕间 + 新对话', what: '换一段新对话:旧对话还在列表里,但不再是她的对话,里面的聊天不再跟着她(你下一条 QQ 消息会开出新的一段)' },
30
+ { id: 'all', name: '全部从零', what: '她学会的 App 用法笔记、存下的表情包(手机相册里同步过去的那些也会被清掉)、面板上的活动记录(三份运行日志)和今天的计数' },
31
+ ];
32
+ const rank = (id) => RESET_LEVELS.findIndex((l) => l.id === id);
33
+ const markerPath = () => join(dshHome(), 'dsh-dot-reset.json');
34
+ const lastPath = () => join(dshHome(), 'dsh-dot-reset.last.json');
35
+ const readJson = (file) => { try { return existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : null; } catch { return null; } };
36
+ /** Where the backups go: next to dsh's own state, not in her home. */
37
+ export const resetsDir = () => join(dshHome(), 'dsh-dot-resets');
38
+
39
+ /** The reset waiting for the next start ({ level, home, requestedAt }), or null. */
40
+ export const pendingReset = () => { const p = readJson(markerPath()); return p && rank(p.level) >= 0 ? p : null; };
41
+ /** The last reset carried out ({ level, at, backup, moved, error? }), or null. */
42
+ export const lastReset = () => readJson(lastPath());
43
+ /** Schedule a reset of `level` for the next start. `home` is her home as the running dot sees it. */
44
+ export function scheduleReset(level, home) {
45
+ if (rank(level) < 0) throw new Error(`unknown reset level "${level}"`);
46
+ mkdirSync(dshHome(), { recursive: true });
47
+ const p = { level, home: home || process.env.DSH_DOT_HOME || join(homedir(), 'dot'), requestedAt: new Date().toISOString() };
48
+ writeFileSync(markerPath(), `${JSON.stringify(p, null, 2)}\n`);
49
+ return p;
50
+ }
51
+ /** Drop a scheduled reset. True when there was one. */
52
+ export function cancelReset() { const had = existsSync(markerPath()); rmSync(markerPath(), { force: true }); return had; }
53
+
54
+ /**
55
+ * Carry out the scheduled reset, if any. Call first thing in a component's apply.
56
+ * @param {number} [opts.startedAt] - when this process started (tests pass their own).
57
+ * @returns the record written to dsh-dot-reset.last.json, or null when nothing was carried out.
58
+ */
59
+ export function runPendingReset({ logger, now = new Date(), startedAt = PROCESS_STARTED_AT, again = false } = {}) {
60
+ const p = pendingReset();
61
+ if (!p) { if (existsSync(markerPath())) rmSync(markerPath(), { force: true }); return null; }
62
+ // Scheduled by this very process, or this process already carried one out: the others are alive. Leave it for the next start.
63
+ const asked = Date.parse(p.requestedAt); // a marker without a readable time (written by hand) is taken as an old one
64
+ if ((Number.isFinite(asked) && asked >= startedAt) || (globalThis[RAN] && !again)) return null;
65
+ globalThis[RAN] = true;
66
+ const r = rank(p.level), dsh = dshHome(), home = p.home;
67
+ const backup = join(resetsDir(), now.toISOString().slice(0, 19).replace(/[-:]/g, '').replace('T', '-'));
68
+ const moved = [], undo = [];
69
+ const mv = (from, to) => {
70
+ if (!existsSync(from)) return;
71
+ mkdirSync(dirname(to), { recursive: true });
72
+ try { renameSync(from, to); undo.push(() => { mkdirSync(dirname(from), { recursive: true }); renameSync(to, from); }); } catch (err) {
73
+ if (err.code !== 'EXDEV') throw err; // another volume: copy, then remove
74
+ cpSync(from, to, { recursive: true });
75
+ // Registered before the removal: one that stops half-way (a file in use) leaves a partial source, and putting
76
+ // back means clearing what is left of it and copying the whole backup over.
77
+ undo.push(() => { rmSync(from, { recursive: true, force: true }); mkdirSync(dirname(from), { recursive: true }); cpSync(to, from, { recursive: true }); rmSync(to, { recursive: true, force: true }); });
78
+ rmSync(from, { recursive: true, force: true });
79
+ }
80
+ moved.push(from);
81
+ };
82
+ const record = { level: p.level, at: now.toISOString(), requestedAt: p.requestedAt, home, backup, moved };
83
+ try {
84
+ mv(join(home, 'memory'), join(backup, 'memory'));
85
+ // Her memory starts empty on purpose: the old conversation is not read back into it (see NO_BACKFILL).
86
+ undo.push(() => rmSync(join(home, 'memory'), { recursive: true, force: true })); // before it is made: put back even if making it fails
87
+ mkdirSync(join(home, 'memory'), { recursive: true });
88
+ writeFileSync(join(home, 'memory', NO_BACKFILL), `${record.at} reset (${p.level})\n`);
89
+ if (r >= rank('life')) {
90
+ const dir = join(home, 'interlude');
91
+ for (const name of existsSync(dir) ? readdirSync(dir) : []) if (!/^canon\.json/.test(name)) mv(join(dir, name), join(backup, 'interlude', name));
92
+ }
93
+ if (r >= rank('all')) {
94
+ mv(join(home, 'her', 'howto'), join(backup, 'her', 'howto'));
95
+ mv(join(dsh, 'stickers'), join(backup, 'stickers'));
96
+ mv(join(dsh, 'dsh-qq-stickers.json'), join(backup, 'dsh-qq-stickers.json'));
97
+ for (const log of ['dsh-computer-audit.jsonl', 'dsh-phone-audit.jsonl', 'dsh-qq-audit.jsonl']) for (const f of [log, `${log}.1`]) mv(join(dsh, f), join(backup, 'logs', f));
98
+ }
99
+ if (r >= rank('fresh')) {
100
+ // Last, and in one rename: her conversation and errand pointers. The old sessions stay in dsh; they are
101
+ // retired (pastConversations / pastErrands), so a turn ending in one of them does not make it hers again.
102
+ const file = join(dsh, 'dsh-dot-state.json'), s = readJson(file);
103
+ if (existsSync(file) && !s) throw new Error(`${file} cannot be read: her conversation pointers were not cleared`);
104
+ if (s) {
105
+ mkdirSync(backup, { recursive: true }); copyFileSync(file, join(backup, 'dsh-dot-state.json'));
106
+ if (s.errandSession) s.pastErrands = [...(s.pastErrands ?? []), s.errandSession];
107
+ if (s.lastSession) s.pastConversations = [...(s.pastConversations ?? []), s.lastSession].slice(-50);
108
+ s.lastSession = ''; s.errandSession = '';
109
+ if (r >= rank('all')) delete s.stats; // today's counters on the panel (messages, wakes): from zero too
110
+ const tmp = `${file}.tmp-${process.pid}`;
111
+ writeFileSync(tmp, JSON.stringify(s, null, 2)); renameSync(tmp, file);
112
+ moved.push(`${file} (lastSession, errandSession${r >= rank('all') ? ', stats' : ''})`);
113
+ }
114
+ }
115
+ logger?.info?.(`reset (${p.level}): ${moved.length} item(s) moved to ${backup}`);
116
+ } catch (err) {
117
+ // Half a reset is worse than none: put back what was moved.
118
+ record.error = err.message;
119
+ let restored = 0;
120
+ for (const back of undo.reverse()) { try { back(); restored++; } catch (error) { void error; } }
121
+ record.rolledBack = restored === undo.length;
122
+ logger?.warn?.(`reset (${p.level}) failed: ${err.message} — ${record.rolledBack ? 'everything was put back' : `could not put everything back; see ${backup}`}`);
123
+ } finally {
124
+ // One attempt per request: a reset that failed is reported on the page, not retried at every start.
125
+ rmSync(markerPath(), { force: true });
126
+ try { writeFileSync(lastPath(), `${JSON.stringify(record, null, 2)}\n`); } catch (error) { void error; }
127
+ }
128
+ return record;
129
+ }
@@ -63,6 +63,8 @@ export const SCHEMA = [
63
63
  e('qq', 'typingMsPerChar', 'QQ', 'int', 'live', '分条发送的打字停顿(毫秒/字,0 = 一次发完)', { min: 0, max: 500 }),
64
64
  e('qq', 'tidy', 'QQ', 'bool', 'live', '去掉句号、引号、破折号等书面符号'),
65
65
  e('qq', 'dropLatinLeaks', 'QQ', 'bool', 'live', '不发整条都是英文的气泡'),
66
+ e('qq', 'dropEchoOpeners', 'QQ', 'bool', 'live', '私聊:不发只是重复对方上一句的开头气泡'),
67
+ e('qq', 'dropChainedQuestions', 'QQ', 'bool', 'live', '私聊:上一轮刚问过对方时,不发这一轮里的问句(办事时要问的话也可能被拦)'),
66
68
  e('qq', 'ignore', 'QQ', 'text', 'live', '不回复的 QQ 号(别的机器人;逗号分开。qq-bridge 的机器人号会自动认出,不用填)'),
67
69
  e('qq', 'loopMax', 'QQ', 'int', 'live', '防互刷(只管群聊):和同一个号在一个群里一来一回几轮、中间没别人说话就停(0 = 不管)', { min: 0, max: 50 }),
68
70
  e('qq', 'loopCooldownMinutes', 'QQ', 'int', 'live', '防互刷:停多少分钟', { min: 1, max: 1440 }),
@@ -74,6 +76,7 @@ export const SCHEMA = [
74
76
  e('dot', 'howto', 'dot', 'bool', 'restart-dsh', '记录她自己的 App 使用经验'),
75
77
  e('dot', 'approvalWaitMs', 'dot', 'int', 'restart-dsh', '没人回的审批多久算拒绝(毫秒,0 = 一直等)', { min: 0 }),
76
78
  // llm (the model-request gate, src/llm-gate.js: one per dsh, whichever components are on)
79
+ e('llm', 'workEffort', '模型请求', choice('', 'off', 'low', 'high', 'max'), 'restart-dsh', '她后台干活时的思考强度(幕间、整理记忆、成长回顾、跑腿)。和对话分开:你在对话里把思考关掉,不影响这里。空 = 跟随 dsh 的模型选择;模型不支持所选强度时也跟随'),
77
80
  e('llm', 'backgroundRpm', '模型请求', 'int', 'restart-dsh', '她后台的请求每分钟最多几次(幕间、整理记忆、跑腿、群聊评分;和你的对话不限;0 = 不限速)', { min: 0, max: 600 }),
78
81
  e('llm', 'foregroundQuietSeconds', '模型请求', 'int', 'restart-dsh', '你们的对话发完请求后,后台再等几秒(秒)', { min: 0, max: 600 }),
79
82
  e('llm', 'maxBackgroundWaitSeconds', '模型请求', 'int', 'restart-dsh', '一个后台请求最多被压后多久(秒;最多 270:再长她的跑腿会被当成卡住,dot.turnStallMs 是 300 秒)', { min: 10, max: 270 }),