koishi-plugin-satori-ai 1.3.8 → 1.3.10

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/lib/api.d.ts CHANGED
@@ -8,6 +8,7 @@ export declare class APIClient {
8
8
  chat(user: User, messages: Sat.Msg[]): Promise<{
9
9
  content: string;
10
10
  error: boolean;
11
+ reasoning_content?: string;
11
12
  }>;
12
13
  auxiliaryChat(messages: Sat.Msg[]): Promise<{
13
14
  content: string;
package/lib/index.d.ts CHANGED
@@ -35,7 +35,7 @@ export declare class SAT extends Sat {
35
35
  content: string;
36
36
  error: boolean;
37
37
  }>;
38
- getChatResponse(user: User, messages: Sat.Msg[]): Promise<{
38
+ getChatResponse(user: User, messages: Sat.Msg[], prompt: string): Promise<{
39
39
  content: string;
40
40
  error: boolean;
41
41
  }>;
@@ -47,9 +47,10 @@ export declare class SAT extends Sat {
47
47
  getWarningList(session: Session): Promise<void>;
48
48
  private clearSession;
49
49
  private addCommonSense;
50
+ addGroupCommonSense(session: Session, content: string, groupId: string): Promise<string>;
50
51
  private handleUserLevel;
51
52
  private handleUserUsage;
52
- handleRandomMiddleware(session: Session, prompt: string): Promise<string>;
53
+ handleRandomMiddleware(session: Session): Promise<string>;
53
54
  handleNickNameMiddleware(session: Session, prompt: string): Promise<string>;
54
55
  handleChannelMemoryManager(session: Session): Promise<void>;
55
56
  }
package/lib/index.js CHANGED
@@ -258,36 +258,45 @@ function processPrompt(prompt) {
258
258
  return prompt.trim();
259
259
  }
260
260
  __name(processPrompt, "processPrompt");
261
- function filterResponse(prompt, words) {
262
- const parts = prompt.split(/([(\[【《(][^))]*[)\]】》)])/g);
263
- const filtered = parts.map((part) => {
264
- if (part.startsWith("(") && part.endsWith(")") || part.startsWith("(") && part.endsWith(")") || part.startsWith("[") && part.endsWith("]") || part.startsWith("【") && part.endsWith("】") || part.startsWith("《") && part.endsWith("》")) {
265
- return words.some((word) => part.includes(word)) ? "" : part;
266
- }
267
- return part;
268
- }).join("");
269
- const cleaned = filtered.replace(/\s+/g, "");
270
- const answerRegex = /<p>((?!<\/?p>)[\s\S])*?<\/p/g;
271
- const answerRegex2 = /<doubaothinking>((?!<\/?doubaothinking>)[\s\S])*?<\/p/g;
272
- const answerRegex3 = /<doubaothinking>((?!<\/?doubaothinking>)[\s\S])*?<\/doubaothinking>/g;
273
- const answerRegex4 = /<answer>((?!<\/?answer>)[\s\S])*?<\/answer>/g;
274
- const answerRegex5 = /<doubaothinking>((?!<\/?doubaothinking>)[\s\S])*?<\/answer>/g;
275
- const answerMatches = cleaned.match(answerRegex);
276
- const answerMatches2 = cleaned.match(answerRegex2);
277
- const answerMatches3 = cleaned.match(answerRegex3);
278
- const answerMatches4 = cleaned.match(answerRegex4);
279
- const answerMatches5 = cleaned.match(answerRegex5);
280
- const lastAnswer = answerMatches ? answerMatches[answerMatches.length - 1] : null;
281
- const lastDoubao = answerMatches2 ? answerMatches2[answerMatches2.length - 1] : null;
282
- const lastAnswer3 = answerMatches3 ? answerMatches3[answerMatches3.length - 1] : null;
283
- const lastAnswer4 = answerMatches4 ? answerMatches4[answerMatches4.length - 1] : null;
284
- const lastAnswer5 = answerMatches5 ? answerMatches5[answerMatches5.length - 1] : null;
285
- const answerContent = lastAnswer || lastDoubao || lastAnswer3 || lastAnswer4 || lastAnswer5;
286
- if (!answerContent) {
261
+ function filterResponse(prompt, words, options) {
262
+ const applyBracketFilter = options?.applyBracketFilter ?? true;
263
+ const applyTagFilter = options?.applyTagFilter ?? true;
264
+ let working = prompt;
265
+ if (applyBracketFilter) {
266
+ const parts = working.split(/([(\[【《(][^))]*[)\]】》)])/g);
267
+ const filtered = parts.map((part) => {
268
+ if (part.startsWith("(") && part.endsWith(")") || part.startsWith("(") && part.endsWith(")") || part.startsWith("[") && part.endsWith("]") || part.startsWith("【") && part.endsWith("】") || part.startsWith("《") && part.endsWith("》")) {
269
+ return words.some((word) => part.includes(word)) ? "" : part;
270
+ }
271
+ return part;
272
+ }).join("");
273
+ working = filtered.replace(/\s+/g, "");
274
+ if (!working) {
275
+ working = prompt;
276
+ }
277
+ }
278
+ if (!applyTagFilter) {
279
+ return working ? { content: working, error: false } : { content: "有点问题,请重置对话", error: true };
280
+ }
281
+ const pTagRegex = /<p>[\s\S]*?<\/p>/g;
282
+ const doubaoRegex = /<doubaothinking>[\s\S]*?<\/doubaothinking>/g;
283
+ const answerTagRegex = /<answer>[\s\S]*?<\/answer>/g;
284
+ const pMatches = working.match(pTagRegex) || [];
285
+ const doubaoMatches = working.match(doubaoRegex) || [];
286
+ const answerTagMatches = working.match(answerTagRegex) || [];
287
+ let combined = null;
288
+ if (pMatches.length > 0) {
289
+ combined = pMatches.map((s) => s.replace(/^<p>/i, "").replace(/<\/p>$/i, "")).join("");
290
+ } else if (doubaoMatches.length > 0) {
291
+ combined = doubaoMatches.map((s) => s.replace(/<doubaothinking>/i, "").replace(/<\/doubaothinking>/i, "")).join("");
292
+ } else if (answerTagMatches.length > 0) {
293
+ combined = answerTagMatches.map((s) => s.replace(/<answer>/i, "").replace(/<\/answer>/i, "")).join("");
294
+ }
295
+ if (!combined) {
287
296
  return { content: "有点问题,请重置对话", error: true };
288
297
  }
289
- const regex = /<p>|<\/p>|<doubaothinking>|<\/doubaothinking>|<\/p|<answer>|<\/answer>|<br>|<\/br>|<br\/>/g;
290
- const cleanedContent = answerContent.replace(regex, "");
298
+ const cleanupRegex = /<p>|<\/p>|<doubaothinking>|<\/doubaothinking>|<answer>|<\/answer>|<br>|<\/br>|<br\/>/gi;
299
+ const cleanedContent = combined.replace(cleanupRegex, "").trim();
291
300
  return cleanedContent ? { content: cleanedContent, error: false } : { content: "有点问题,请重置对话", error: true };
292
301
  }
293
302
  __name(filterResponse, "filterResponse");
@@ -509,7 +518,7 @@ var APIClient = class {
509
518
  logger2.warn(`返回内容与之前内容相同,重试(第${i}次)中...`);
510
519
  continue;
511
520
  }
512
- return { content, error: false };
521
+ return { content, error: false, reasoning_content };
513
522
  } catch (error) {
514
523
  if (i == this.config.maxRetryTimes) {
515
524
  return this.handleAPIError(error);
@@ -661,6 +670,9 @@ var MemoryManager = class {
661
670
  response = this.bracketFilter(response, config);
662
671
  response = this.memoryFilter(response, config);
663
672
  }
673
+ if (!response) {
674
+ response = "…";
675
+ }
664
676
  let channelId = session.channelId;
665
677
  if (config.personal_memory)
666
678
  channelId = session.userId;
@@ -673,10 +685,18 @@ var MemoryManager = class {
673
685
  const memory = this.channelMemories.get(channelId);
674
686
  memory.dialogues.push({ role: "user", content: prompt });
675
687
  this.updateChannelDialogue(session, prompt, session.username);
676
- if (this.config.enable_self_memory && response) {
677
- memory.dialogues.push({ role: "assistant", content: "<p>" + response + "</p>" });
688
+ if (this.config.enhanceReasoningProtection) {
689
+ if (this.config.enable_self_memory) {
690
+ memory.dialogues.push({ role: "assistant", content: "<p>" + response + "</p>" });
691
+ } else {
692
+ memory.dialogues.push({ role: "assistant", content: "<p>…</p>" });
693
+ }
678
694
  } else {
679
- memory.dialogues.push({ role: "assistant", content: "<p>…</p>" });
695
+ if (this.config.enable_self_memory) {
696
+ memory.dialogues.push({ role: "assistant", content: response });
697
+ } else {
698
+ memory.dialogues.push({ role: "assistant", content: "…" });
699
+ }
680
700
  }
681
701
  if (memory.dialogues.length > this.config.message_max_length) {
682
702
  memory.dialogues = memory.dialogues.slice(-this.config.message_max_length);
@@ -718,11 +738,14 @@ var MemoryManager = class {
718
738
  async searchMemories(session, prompt, type = "user") {
719
739
  const filePathMap = {
720
740
  "user": this.getUserMemoryPath(session.userId),
721
- "common": path2.join(this.config.dataDir, "common_sense.txt")
741
+ "common": path2.join(this.config.dataDir, "common_sense.txt"),
742
+ "group": path2.join(this.config.dataDir, "group_sense", `${session.channelId}.txt`)
722
743
  };
723
744
  const topNMap = {
724
745
  "user": this.config.dailogues_topN,
725
- "common": this.config.common_topN
746
+ "common": this.config.common_topN,
747
+ "group": this.config.common_topN
748
+ // 群常识和常识使用同样的topN
726
749
  };
727
750
  const filePath = filePathMap[type];
728
751
  if (!fs2.existsSync(filePath)) {
@@ -759,7 +782,8 @@ var MemoryManager = class {
759
782
  formatMatches(matched, type, topN = 5) {
760
783
  const prefixMap = {
761
784
  "common": "这是你可能用到的信息:",
762
- "user": "以下是较久之前用户说过的话和对话时间:"
785
+ "user": "以下是较久之前用户说过的话和对话时间:",
786
+ "group": "以下是本群聊你可能需要知道的信息:"
763
787
  };
764
788
  const time = `时段:${getTimeOfDay((/* @__PURE__ */ new Date()).getHours())}`;
765
789
  const date = `当前日期和时间:${(/* @__PURE__ */ new Date()).toLocaleString()} ${time}`;
@@ -772,11 +796,17 @@ ${date}
772
796
  }
773
797
  `;
774
798
  return result;
775
- } else {
799
+ } else if (type === "user") {
776
800
  matched.forEach((entry) => entry.content = entry.content + (entry.role === "user" ? "(未记录时间)" : entry.role));
777
801
  const result = `${prefixMap[type]}{
778
802
  ${matched.map((entry) => entry.content).join("\n")}
779
803
  }
804
+ `;
805
+ return result;
806
+ } else if (type === "group") {
807
+ const result = `${prefixMap[type]}{
808
+ ${matched.map((entry) => entry.content).join("\n")}
809
+ }
780
810
  `;
781
811
  return result;
782
812
  }
@@ -925,6 +955,8 @@ async function handleFavorabilitySystem(ctx, session, config) {
925
955
  }
926
956
  __name(handleFavorabilitySystem, "handleFavorabilitySystem");
927
957
  function getFavorabilityLevel(user, config) {
958
+ if (user.favorability >= config.favorability_div_3 && user?.items["镇定贴"]?.count > 0 && user?.items["镇定贴"]?.description && user?.items["镇定贴"]?.description == "on")
959
+ return "朋友";
928
960
  if (user?.items["订婚戒指"]?.count > 0 && user?.items["订婚戒指"]?.description && user?.items["订婚戒指"]?.description == "已使用")
929
961
  return "夫妻";
930
962
  if (user.favorability < config.favorability_div_1)
@@ -1074,7 +1106,7 @@ function createMiddleware(ctx, sat, config) {
1074
1106
  return await handleNickNameMessage(sat, session);
1075
1107
  }
1076
1108
  if (shouldRandomTrigger(session, config)) {
1077
- return await sat.handleRandomMiddleware(session, session.content);
1109
+ return await sat.handleRandomMiddleware(session);
1078
1110
  }
1079
1111
  return next();
1080
1112
  };
@@ -1145,6 +1177,7 @@ var Sat = class extends import_koishi5.Service {
1145
1177
  import_koishi5.Schema.transform(String, (value) => [value])
1146
1178
  ]).default([]).role("secret").description("深度思考模型api_key"),
1147
1179
  appointModel: import_koishi5.Schema.string().default("deepseek-reasoner").description("深度思考模型"),
1180
+ enhanceReasoningProtection: import_koishi5.Schema.boolean().default(true).description("是否增强思维链保护(开启后会强制输出内容带有限制标签,极大防止思维链溢出问题)"),
1148
1181
  not_reasoner_LLM_URL: import_koishi5.Schema.string().default("https://api.deepseek.com").description("非深度思考模型请求地址"),
1149
1182
  not_reasoner_LLM: import_koishi5.Schema.string().default("deepseek-chat").description("非深度思考模型(用于节省成本"),
1150
1183
  not_reasoner_LLM_key: import_koishi5.Schema.union([
@@ -1188,7 +1221,7 @@ var Sat = class extends import_koishi5.Service {
1188
1221
  dataDir: import_koishi5.Schema.string().default("./data/satori_ai").description("聊天记录保存位置(长期记忆)"),
1189
1222
  memory_block_words: import_koishi5.Schema.array(String).default(["好感"]).description("记忆屏蔽词"),
1190
1223
  remember_min_length: import_koishi5.Schema.number().description("触发保存到记忆的长度").default(20),
1191
- common_topN: import_koishi5.Schema.number().default(5).description("常识记忆检索最大匹配数"),
1224
+ common_topN: import_koishi5.Schema.number().default(5).description("群常识、常识记忆检索最大匹配数"),
1192
1225
  dailogues_topN: import_koishi5.Schema.number().default(5).description("对话记忆检索最大匹配数"),
1193
1226
  enable_fixed_dialogues: import_koishi5.Schema.boolean().default(false).description("是否启用固定对话(在dataDir中的fixed_dialogues.json修改)")
1194
1227
  }).description("记忆设置"),
@@ -1203,6 +1236,7 @@ var Sat = class extends import_koishi5.Service {
1203
1236
  duplicateDialogueCheck: import_koishi5.Schema.boolean().default(true).description("是否检查重复对话"),
1204
1237
  enable_online_user_check: import_koishi5.Schema.boolean().default(true).description("在未回答而再次提问时是否提示用户有未完成的对话"),
1205
1238
  random_min_tokens: import_koishi5.Schema.number().default(20).description("随机触发对话的最小长度"),
1239
+ enable_random_without_favorability: import_koishi5.Schema.boolean().default(true).description("是否启用随机触发对话无视高好感度(即使用户好感度很高也会最多视为朋友)"),
1206
1240
  randnum: import_koishi5.Schema.number().role("slider").min(0).max(1).step(0.01).default(0).description("在群聊中随机触发对话的概率,如需关闭可设置为 0"),
1207
1241
  sentences_divide: import_koishi5.Schema.boolean().default(true).description("是否分句发送"),
1208
1242
  min_sentences_length: import_koishi5.Schema.number().default(10).description("每个分句的最小长度"),
@@ -3058,6 +3092,7 @@ __name(wrapInHTML2, "wrapInHTML");
3058
3092
 
3059
3093
  // src/index.tsx
3060
3094
  var logger12 = new import_koishi13.Logger("satori-ai");
3095
+ var randomPrompt = "根据群聊内最近的包括所有人的聊天记录,锐评一下群聊中的话题";
3061
3096
  var puppeteer = null;
3062
3097
  function refreshPuppeteer(ctx) {
3063
3098
  if (ctx.puppeteer) {
@@ -3131,7 +3166,8 @@ var SAT = class extends Sat {
3131
3166
  channel_dialogues_max_length: this.config.channel_dialogues_max_length,
3132
3167
  remember_min_length: this.config.remember_min_length,
3133
3168
  common_topN: this.config.common_topN,
3134
- dailogues_topN: this.config.dailogues_topN
3169
+ dailogues_topN: this.config.dailogues_topN,
3170
+ enhanceReasoningProtection: this.config.enhanceReasoningProtection
3135
3171
  };
3136
3172
  }
3137
3173
  getMiddlewareConfig() {
@@ -3192,7 +3228,8 @@ var SAT = class extends Sat {
3192
3228
  registerCommands(ctx) {
3193
3229
  ctx.command("sat <text:text>", { authority: this.config.authority }).alias(...this.config.alias).action(async ({ session }, prompt) => this.handleSatCommand(session, prompt));
3194
3230
  ctx.command("sat.clear", "清空会话").option("global", "-g").action(({ session, options }) => this.clearSession(session, options.global));
3195
- ctx.command("sat.common_sense <text:text>", "添加常识").action(async ({ session }, prompt) => this.addCommonSense(session, prompt));
3231
+ ctx.command("sat.common_sense <text:text>", "添加常识", { authority: 4 }).alias("添加常识").action(async ({ session }, prompt) => this.addCommonSense(session, prompt));
3232
+ ctx.command("sat.group_sense <text:text>", "添加群常识", { authority: 3 }).alias("添加群常识").option("id", "-i <id:string>", { authority: 3 }).action(async ({ session, options }, prompt) => this.addGroupCommonSense(session, prompt, options.id));
3196
3233
  ctx.command("sat.update_user_level", "更新用户等级", { authority: 2 }).alias("更新用户").option("id", "-i <id:string>", { authority: 4 }).option("level", "-l <level:number>", { authority: 4 }).action(async ({ session, options }) => this.handleUserLevel(session, options));
3197
3234
  ctx.command("sat.user_usage", "查看用户使用次数").alias("查询次数").action(async ({ session }) => this.handleUserUsage(session));
3198
3235
  ctx.command("sat.add_output_censor <text:text>", "添加输出敏感词", { authority: 4 }).alias("添加输出屏蔽词").action(async ({ session }, word) => addOutputCensor(session, word, this.config.dataDir));
@@ -3356,15 +3393,18 @@ var SAT = class extends Sat {
3356
3393
  const messages = await this.buildMessages(session, prompt);
3357
3394
  logger12.info(`频道 ${session.channelId} 处理:${session.userId},剩余${this.getChannelParallelCount(session)}并发`);
3358
3395
  const user = await getUser(this.ctx, session.userId);
3359
- let response = await this.getChatResponse(user, messages);
3396
+ let response = await this.getChatResponse(user, messages, prompt);
3360
3397
  if (response.error)
3361
- response = await this.getChatResponse(user, messages);
3398
+ response = await this.getChatResponse(user, messages, prompt);
3362
3399
  if (response.error)
3363
3400
  updateUserUsage(this.ctx, user, -1);
3364
3401
  return response;
3365
3402
  }
3366
3403
  // 获取聊天回复
3367
- async getChatResponse(user, messages) {
3404
+ async getChatResponse(user, messages, prompt) {
3405
+ const hasTicket = user?.items?.["地灵殿通行证"]?.description && user.items["地灵殿通行证"].description === "on";
3406
+ const maxLength = hasTicket ? user?.items?.["地灵殿通行证"]?.metadata?.use_not_reasoner_LLM_length : this.config.use_not_reasoner_LLM_length;
3407
+ const useNoReasoner = prompt.length <= maxLength && this.config.enable_reasoner_like;
3368
3408
  let response = await this.apiClient.chat(user, messages);
3369
3409
  if (this.config.log_ask_response) {
3370
3410
  if (this.config.enable_favorability && this.config.enable_mood)
@@ -3372,25 +3412,38 @@ var SAT = class extends Sat {
3372
3412
  else
3373
3413
  logger12.info(`Satori AI:${response.content}`);
3374
3414
  }
3375
- if (this.config.reasoner_filter && !response.error)
3376
- response = filterResponse(response.content, this.config.reasoner_filter_word.split("-"));
3415
+ if (!response.error) {
3416
+ response = filterResponse(response.content, this.config.reasoner_filter_word.split("-"), {
3417
+ applyBracketFilter: this.config.reasoner_filter,
3418
+ applyTagFilter: useNoReasoner || this.config.enhanceReasoningProtection
3419
+ });
3420
+ }
3377
3421
  return response;
3378
3422
  }
3379
3423
  // 构建消息
3380
3424
  async buildMessages(session, prompt) {
3381
3425
  const messages = [];
3382
- const example = `<think>
3426
+ const user = await ensureUserExists(this.ctx, session.userId, session.username);
3427
+ const hasTicket = user?.items?.["地灵殿通行证"]?.description && user.items["地灵殿通行证"].description === "on";
3428
+ const maxLength = hasTicket ? user?.items?.["地灵殿通行证"]?.metadata?.use_not_reasoner_LLM_length : this.config.use_not_reasoner_LLM_length;
3429
+ const useNoReasoner = prompt.length <= maxLength && this.config.enable_reasoner_like;
3430
+ const exampleWithoutReasoner = `<think>
3383
3431
  好的,我会尽量做到的
3384
3432
  </think>
3385
3433
  <p>已明确对话要求</p>`;
3434
+ const exampleWithTag = `<p>已明确对话要求</p>`;
3435
+ const exampleWithoutTag = `已明确对话要求`;
3436
+ const example = useNoReasoner ? exampleWithoutReasoner : this.config.enhanceReasoningProtection ? exampleWithTag : exampleWithoutTag;
3386
3437
  if (this.config.no_system_prompt) {
3387
3438
  messages.push({ role: "user", content: await this.buildSystemPrompt(session, prompt) });
3388
3439
  messages.push({ role: "assistant", content: example });
3389
3440
  } else {
3390
3441
  messages.push({ role: "system", content: await this.buildSystemPrompt(session, prompt) });
3391
3442
  }
3392
- const userMemory = this.memoryManager.getChannelContext(this.config.personal_memory ? session.userId : session.channelId);
3393
- messages.push(...userMemory);
3443
+ if (prompt != randomPrompt) {
3444
+ const userMemory = this.memoryManager.getChannelContext(this.config.personal_memory ? session.userId : session.channelId);
3445
+ messages.push(...userMemory);
3446
+ }
3394
3447
  messages.push({ role: "user", content: prompt });
3395
3448
  let payload = messages.map((msg) => msg.role + ":" + msg.content).join("\n");
3396
3449
  if (this.config.log_system_prompt)
@@ -3401,20 +3454,34 @@ ${payload}`);
3401
3454
  // 构建系统提示
3402
3455
  async buildSystemPrompt(session, prompt) {
3403
3456
  const commonSense = await this.memoryManager.searchMemories(session, prompt, "common");
3457
+ const groupSense = await this.memoryManager.searchMemories(session, prompt, "group");
3404
3458
  const channelDialogue = await this.memoryManager.getChannelDialogue(session);
3405
3459
  const userMemory = await this.memoryManager.searchMemories(session, prompt);
3406
3460
  const user = await getUser(this.ctx, session.userId);
3407
3461
  const moodLevel = this.moodManager.getMoodLevel(user.userid);
3408
3462
  let systemPrompt = "";
3463
+ if (prompt == randomPrompt) {
3464
+ systemPrompt += "#首先明确一些参考信息\n";
3465
+ systemPrompt += "\n##" + channelDialogue;
3466
+ systemPrompt += this.getThinkingPrompt(user, prompt);
3467
+ systemPrompt += this.config.prompt;
3468
+ if (this.config.enhanceReasoningProtection) {
3469
+ systemPrompt += `
3470
+ #注意:你最终的回复内容必须使用“<p>”开头,使用“</p>”结尾
3471
+ `;
3472
+ if (this.config.no_system_prompt)
3473
+ systemPrompt += "\n#如果你明白以上内容,请回复“<p>已明确对话要求</p>”";
3474
+ }
3475
+ return systemPrompt;
3476
+ }
3409
3477
  systemPrompt += "#首先明确一些参考信息\n";
3410
3478
  systemPrompt += "\n##" + commonSense;
3479
+ systemPrompt += "\n##" + groupSense;
3411
3480
  systemPrompt += "\n##" + channelDialogue;
3412
3481
  systemPrompt += "\n##" + userMemory;
3413
3482
  if (moodLevel == "normal" || moodLevel == "happy")
3414
3483
  systemPrompt += "\n##" + this.portraitManager.getUserPortrait(session);
3415
- systemPrompt += "\n#参考信息到此为止,接下来是思考要求\n";
3416
3484
  systemPrompt += this.getThinkingPrompt(user, prompt);
3417
- systemPrompt += "\n#接下来是对话要求,以下要求仅对最终的回复内容生效,不限制思考过程\n";
3418
3485
  systemPrompt += this.config.prompt;
3419
3486
  if (user?.items?.["觉的衣柜"]?.count && (moodLevel == "normal" || moodLevel == "happy")) {
3420
3487
  const clothes = user?.items?.["觉的衣柜"]?.metadata?.clothes;
@@ -3442,23 +3509,31 @@ ${payload}`);
3442
3509
  if (nickName)
3443
3510
  systemPrompt += `, 昵称是:${nickName},称呼用户时请优先使用昵称
3444
3511
  `;
3445
- systemPrompt += `
3512
+ if (this.config.enhanceReasoningProtection) {
3513
+ systemPrompt += `
3446
3514
  #注意:你最终的回复内容必须使用“<p>”开头,使用“</p>”结尾
3447
3515
  `;
3448
- if (this.config.no_system_prompt)
3449
- systemPrompt += "\n#如果你明白以上内容,请回复“<p>已明确对话要求</p>”";
3516
+ if (this.config.no_system_prompt)
3517
+ systemPrompt += "\n#如果你明白以上内容,请回复“<p>已明确对话要求</p>”";
3518
+ }
3450
3519
  return systemPrompt;
3451
3520
  }
3452
3521
  // 思考提示
3453
3522
  getThinkingPrompt(user, prompt) {
3454
3523
  const reasonerPrompt = this.config.reasoner_prompt;
3455
- const promptForNoReasoner = `#请你在回复时先进行分析思考,并且模仿思维链的模式输出思考内容,${reasonerPrompt};
3524
+ const promptForNoReasoner = `
3525
+ #参考信息到此为止,接下来是思考要求
3526
+ #请你在回复时先进行分析思考,并且模仿思维链的模式输出思考内容,${reasonerPrompt};
3456
3527
  #你在思考时必须以 "<think>" 开头, "</think>" 结尾。仔细揣摩用户意图,**完整输出思考内容后**再输出正式的回复内容;
3457
- #注意:你的正式回复内容必须使用“<p>”开头,使用“</p>”结尾,并且无论如何都要把标签输出完整
3458
- `;
3459
- const promptForReasoner = `#你在思考时必须以 "嗯" 开头。仔细揣摩用户意图,思考结束后返回符合要求的回复。
3460
- #注意:你的回复内容必须使用“<p>”开头,使用“</p>”结尾
3528
+ #注意:你的正式回复内容必须使用“<p>”开头,在输出全部回复后使用“</p>”结尾(即输出且仅输出一对标签),并且无论如何都要把标签输出完整
3529
+ #接下来是对话要求,以下要求仅对最终的回复内容生效,不限制思考过程
3461
3530
  `;
3531
+ const promptForReasoner = this.config.enhanceReasoningProtection ? `
3532
+ #参考信息到此为止,接下来是思考要求
3533
+ #你在思考时必须以 "嗯" 开头。仔细揣摩用户意图,思考结束后返回符合要求的回复。
3534
+ #注意:你的回复内容必须使用“<p>”开头,在输出全部回复后使用“</p>”结尾(即输出且仅输出一对标签)
3535
+ #接下来是对话要求,以下要求仅对最终的回复内容生效,不限制思考过程
3536
+ ` : "";
3462
3537
  const hasTicket = user?.items?.["地灵殿通行证"]?.description && user.items["地灵殿通行证"].description === "on";
3463
3538
  const maxLength = hasTicket ? user?.items?.["地灵殿通行证"]?.metadata?.use_not_reasoner_LLM_length : this.config.use_not_reasoner_LLM_length;
3464
3539
  const useNoReasoner = prompt.length <= maxLength;
@@ -3559,6 +3634,18 @@ ${useNoReasoner ? promptForNoReasoner : promptForReasoner}
3559
3634
  }], filePath);
3560
3635
  return session.text("commands.sat.common_sense.messages.succeed", [content]);
3561
3636
  }
3637
+ // 添加群常识
3638
+ async addGroupCommonSense(session, content, groupId) {
3639
+ if (!content)
3640
+ return session.text("commands.sat.common_sense.messages.no-prompt");
3641
+ const id = groupId || session.channelId;
3642
+ const filePath = path6.join(this.config.dataDir, `group_sense`, `${id}.txt`);
3643
+ await this.memoryManager.saveLongTermMemory(session, [{
3644
+ role: "user",
3645
+ content: content.replace(/\"/g, "'").trim()
3646
+ }], filePath);
3647
+ return session.text("commands.sat.common_sense.messages.succeed", [`群${id}中:` + content]);
3648
+ }
3562
3649
  // 更新用户等级
3563
3650
  async handleUserLevel(session, options) {
3564
3651
  const userId = options.id || session.userId;
@@ -3587,21 +3674,10 @@ ${useNoReasoner ? promptForNoReasoner : promptForReasoner}
3587
3674
  return result;
3588
3675
  }
3589
3676
  // 随机中间件转接
3590
- async handleRandomMiddleware(session, prompt) {
3591
- const user = await getUser(this.ctx, session.userId);
3592
- const processedPrompt = processPrompt(session.content);
3593
- if (this.performPreChecks(session, processedPrompt))
3594
- return null;
3595
- if (await this.checkUserDialogueCount(session, user, 0))
3596
- return null;
3597
- if (await this.checkFavorabilityBlock(session))
3598
- return null;
3599
- let censored = processedPrompt;
3600
- if (this.ctx.censor)
3601
- censored = await this.ctx.censor.transform(processedPrompt, session);
3602
- if (censored.includes("**"))
3603
- return null;
3604
- return this.handleSatCommand(session, prompt);
3677
+ async handleRandomMiddleware(session) {
3678
+ await this.updateChannelParallelCount(session, 1);
3679
+ const response = await this.generateResponse(session, randomPrompt);
3680
+ return await this.formatResponse(session, response.content, null);
3605
3681
  }
3606
3682
  // 昵称中间件转接
3607
3683
  async handleNickNameMiddleware(session, prompt) {
package/lib/memory.d.ts CHANGED
@@ -23,7 +23,7 @@ export declare class MemoryManager {
23
23
  clearAllMemories(): void;
24
24
  getChannelMemory(channelId: string): MemoryEntry[];
25
25
  saveLongTermMemory(session: Session, dialogues: MemoryEntry[], filePath?: string): Promise<void>;
26
- searchMemories(session: Session, prompt: string, type?: 'user' | 'common'): Promise<string>;
26
+ searchMemories(session: Session, prompt: string, type?: 'user' | 'common' | 'group'): Promise<string>;
27
27
  private findBestMatches;
28
28
  private calculateMatchScore;
29
29
  private formatMatches;
package/lib/types.d.ts CHANGED
@@ -74,6 +74,7 @@ export interface MemoryConfig {
74
74
  remember_min_length: number;
75
75
  common_topN: number;
76
76
  dailogues_topN: number;
77
+ enhanceReasoningProtection: boolean;
77
78
  }
78
79
  export interface MiddlewareConfig {
79
80
  private: boolean;
@@ -148,6 +149,7 @@ export declare namespace Sat {
148
149
  baseURL: string;
149
150
  key: string[];
150
151
  appointModel: string;
152
+ enhanceReasoningProtection: boolean;
151
153
  not_reasoner_LLM_URL: string;
152
154
  not_reasoner_LLM: string;
153
155
  not_reasoner_LLM_key: string[];
@@ -191,6 +193,7 @@ export declare namespace Sat {
191
193
  duplicateDialogueCheck: boolean;
192
194
  enable_online_user_check: boolean;
193
195
  random_min_tokens: number;
196
+ enable_random_without_favorability: boolean;
194
197
  randnum: number;
195
198
  sentences_divide: boolean;
196
199
  min_sentences_length: number;
package/lib/utils.d.ts CHANGED
@@ -23,7 +23,10 @@ export declare function processPrompt(prompt: string): string;
23
23
  * @param words 需要过滤的关键词
24
24
  * @returns 处理后的字符串,删除含有关键词的部分
25
25
  */
26
- export declare function filterResponse(prompt: string, words: string[]): {
26
+ export declare function filterResponse(prompt: string, words: string[], options?: {
27
+ applyBracketFilter?: boolean;
28
+ applyTagFilter?: boolean;
29
+ }): {
27
30
  content: string;
28
31
  error: boolean;
29
32
  };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-satori-ai",
3
3
  "description": "基于 Satori 适配器的智能对话插件,具备用户画像、长期记忆、常识管理和好感度系统",
4
- "version": "1.3.8",
4
+ "version": "1.3.10",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "types": "lib/index.d.ts",