Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion packages/core/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { computed, defineComponent, h, ref, resolveComponent } from "vue";

import "./section.css";
import { ModelGroups } from "./model-groups";

let nextSectionId = 0;

Expand Down Expand Up @@ -49,7 +50,8 @@ export const ConfigSection = defineComponent({
});

export default function apply(ctx) {
ctx.schema({ type: "array", role: "yib-model-groups", component: ModelGroups });
for (const type of ["object", "intersect"]) {
ctx.extendSchema({ type, role: "yib-section", component: ConfigSection });
ctx.schema({ type, role: "yib-section", component: ConfigSection });
}
}
101 changes: 101 additions & 0 deletions packages/core/client/model-groups.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import { defineComponent, h, ref, resolveComponent, watch } from "vue";

const copy = (value: unknown): any[] => JSON.parse(JSON.stringify(value ?? []));

export const ModelGroups = defineComponent({
name: "YibModelGroups",
inheritAttrs: false,
props: ["schema", "modelValue", "initial", "disabled", "prefix", "extra"],
emits: ["update:modelValue"],
setup(props, { emit, attrs, slots }) {
const rows = ref(copy(props.modelValue));
watch(
() => props.modelValue,
(value) => {
if (JSON.stringify(value ?? []) !== JSON.stringify(rows.value)) rows.value = copy(value);
},
{ deep: true },
);
const update = () => emit("update:modelValue", copy(rows.value));
const remove = (index: number) => {
if (props.disabled) return;
rows.value.splice(index, 1);
update();
};
const move = (index: number, offset: number) => {
const destination = index + offset;
if (props.disabled || destination < 0 || destination >= rows.value.length) return;
rows.value.splice(destination, 0, ...rows.value.splice(index, 1));
update();
};
return () =>
h("div", { ...attrs, class: ["yib-model-groups", attrs.class] }, [
slots.title ? h("div", { class: "yib-model-group-title" }, slots.title()) : null,
slots.desc?.(),
slots.menu ? h("details", { class: "yib-model-group-menu" }, [h("summary", "更多操作"), slots.menu()]) : null,
h(
"p",
{ class: "yib-model-group-note" },
rows.value.length ? "删除正在使用的模型组后,请检查任务分配。" : "尚无模型组。启动或重载插件时会自动创建默认模型组。",
),
...rows.value.map((row, index) =>
h("div", { class: "yib-model-group-row", key: index }, [
h("div", { class: "yib-model-group-actions" }, [
h("span", row?.name || `模型组 ${index + 1}`),
h(
"button",
{
type: "button",
disabled: props.disabled || index === 0,
"aria-label": `上移模型组 ${index + 1}`,
onClick: () => move(index, -1),
},
"上移",
),
h(
"button",
{
type: "button",
disabled: props.disabled || index === rows.value.length - 1,
"aria-label": `下移模型组 ${index + 1}`,
onClick: () => move(index, 1),
},
"下移",
),
h(
"button",
{ type: "button", disabled: props.disabled, "aria-label": `删除模型组 ${index + 1}`, onClick: () => remove(index) },
"删除模型组",
),
]),
h(resolveComponent("k-schema"), {
schema: props.schema.inner,
modelValue: row,
initial: props.initial?.[index],
disabled: props.disabled,
prefix: `${(props.prefix ?? "modelGroups.").replace(/\.$/, "")}[${index}].`,
extra: { foldable: true },
"onUpdate:modelValue": (value) => {
if (props.disabled) return;
rows.value[index] = value;
update();
},
}),
]),
),
h(
"button",
{
type: "button",
disabled: props.disabled,
onClick: () => {
if (props.disabled) return;
rows.value.push({ name: "", strategy: "failover", models: [] });
update();
},
},
"添加模型组",
),
]);
},
});
36 changes: 36 additions & 0 deletions packages/core/client/section.css
Original file line number Diff line number Diff line change
Expand Up @@ -55,3 +55,39 @@
margin-left: 2px;
}
}

.yib-model-group-row {
border: 1px solid var(--k-color-divider);
border-radius: 4px;
padding: 12px;
margin-bottom: 12px;
}
.yib-model-group-actions {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px;
margin-bottom: 8px;
}
.yib-model-group-actions > span {
flex: 1;
min-width: 8rem;
}
.yib-model-groups button {
color: var(--k-text-normal);
background: var(--k-card-bg);
border: 1px solid var(--k-color-divider);
border-radius: 4px;
padding: 6px 10px;
cursor: pointer;
}
.yib-model-groups button:disabled {
opacity: 0.5;
cursor: default;
}
.yib-model-groups button:focus-visible {
outline: 2px solid var(--k-color-primary);
}
.yib-model-group-note {
color: var(--k-text-light);
}
54 changes: 41 additions & 13 deletions packages/core/src/agent/agent-core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@ import { TopicManager, TopicSnapshot } from "./topics";
import { TypeSafeEvaluator } from "./typesafe";
import { WillingnessManager } from "./willing";

type TracedStimulus = AgentStimulus<any> & { decisionId?: string; topic?: TopicSnapshot; continuation?: ContinuationMatch; continuationRequired?: boolean };
type TracedStimulus = AgentStimulus<any> & {
decisionId?: string;
topic?: TopicSnapshot;
scoringTopic?: TopicSnapshot;
continuation?: ContinuationMatch;
continuationRequired?: boolean;
};

declare module "koishi" {
interface Tables {
Expand Down Expand Up @@ -282,7 +288,7 @@ export class AgentCore extends YesImBotService<Config> {
this.cancelAssessment(key, false);
this.activeTurns.get(key)?.abort(new Error("聊天任务已取消"));
this.decisions.update(this.activeDecisionIds.get(key), { stage: "cancelled", reason, success: false });
this.resetWillingness(key);
this.resetWillingness(key, reason);
this.scheduler?.cancel(key);
},
async (target, reason, rule, actor) => {
Expand Down Expand Up @@ -377,7 +383,7 @@ export class AgentCore extends YesImBotService<Config> {
this.activeDecisionIds.delete(channelCid);
}

const replyTopic = (stimulus as TracedStimulus).topic;
const replyTopic = (stimulus as TracedStimulus).scoringTopic ?? (stimulus as TracedStimulus).topic;
if (success && valid() && (!replyTopic || this.topicScores.get(channelCid)?.has(replyTopic.scoreKey))) {
const scoreKey = replyTopic?.scoreKey ?? channelCid;
const willingnessBeforeReply = this.willing.getCurrentWillingness(scoreKey);
Expand All @@ -392,7 +398,9 @@ export class AgentCore extends YesImBotService<Config> {
stage: completed ? "completed" : "cancelled",
reason: !completed ? "invalid_generation" : success ? undefined : "no_reply",
success: success && completed,
score: this.willing.getCurrentWillingness((stimulus as TracedStimulus).topic?.scoreKey ?? channelCid),
score: this.willing.getCurrentWillingness(
(stimulus as TracedStimulus).scoringTopic?.scoreKey ?? (stimulus as TracedStimulus).topic?.scoreKey ?? channelCid,
),
participation: this.willing.getParticipation(channelCid),
});
},
Expand All @@ -405,7 +413,7 @@ export class AgentCore extends YesImBotService<Config> {
this.cancelAssessment(key, false, "muted");
this.activeTurns.get(key)?.abort(new Error("机器人已被禁言"));
this.decisions.update(this.activeDecisionIds.get(key), { stage: "cancelled", reason: "muted", success: false });
this.resetWillingness(key);
this.resetWillingness(key, "muted");
this.scheduler.cancel(key, "muted");
});
}
Expand Down Expand Up @@ -536,9 +544,14 @@ export class AgentCore extends YesImBotService<Config> {

if (type === "user_message") {
try {
const topic = (stimulus as TracedStimulus).topic;
const candidates = topic ? (this.topics?.getTopics(channelCid) ?? []) : [];
if (topic) this.trackTopicScores(channelCid, candidates);
const inputTopic = stimulus.topic;
const retained = this.config.topics?.enabled ? (this.topics?.getTopics(channelCid) ?? []) : [];
const focusId = retained.length ? this.topics?.getFocus(channelCid)?.id : undefined;
const fallback = retained.find((item) => item.id === focusId) ?? retained[0];
// Retain score ownership without injecting a stale inferred topic into source-anchored context.
const topic = inputTopic ?? (fallback ? { ...fallback, multiplier: 1 } : undefined);
const candidates = inputTopic ? retained : topic ? [topic] : [];
if (topic) this.trackTopicScores(channelCid, retained);
const willingnessBefore = this.willing.getCurrentWillingness(topic?.scoreKey ?? channelCid);
const replyRule = this.replyControl.get(this.replyTarget(session));
const categories = replyRule ? allowed : undefined;
Expand All @@ -564,7 +577,7 @@ export class AgentCore extends YesImBotService<Config> {
const focus = candidates.find((candidate) => candidate.scoreKey === scoreKey);
if (focus) {
this.topics?.chooseFocus(channelCid, focus.id);
stimulus = { ...stimulus, topic: focus } as TracedStimulus;
stimulus = { ...stimulus, scoringTopic: focus, ...(inputTopic ? { topic: focus } : {}) } as TracedStimulus;
}
}
const forcedMention = this.config.prioritizeMentions && !replyRule && isBotMention(session) && allowed.includes("at");
Expand All @@ -581,6 +594,7 @@ export class AgentCore extends YesImBotService<Config> {
roll: result.roll,
calculation: result.calculation,
score: willingnessAfter,
scoreKey,
participation: this.willing.getParticipation?.(channelCid),
reason: forcedMention
? "forced_reply_by_mention"
Expand All @@ -598,7 +612,7 @@ export class AgentCore extends YesImBotService<Config> {
);
}
/* prettier-ignore */
this.logger.debug(`[${channelCid}] 意愿计算: ${(result.calculation?.before ?? willingnessBefore).toFixed(2)} -> ${willingnessAfter.toFixed(2)} | 回复概率: ${(result.probability * 100).toFixed(1)}% | 初步决策: ${decision} | 处理: ${!allowSchedule ? "仅结算,不调度" : decision ? "准备提交调度" : "未达到回复条件"} | 消息ID: ${session.messageId ?? "未知"}`);
this.logger.debug(`[${channelCid}] 意愿计算 | 计分键: ${scoreKey} | ${(result.calculation?.before ?? willingnessBefore).toFixed(2)} -> ${willingnessAfter.toFixed(2)} | 回复概率: ${(result.probability * 100).toFixed(1)}% | 初步决策: ${decision} | 处理: ${!allowSchedule ? "仅结算,不调度" : decision ? "准备提交调度" : "未达到回复条件"} | 消息ID: ${session.messageId ?? "未知"}`);
} catch (error) {
this.recordDecision(stimulus, { stage: "failed", reason: "exception" });
handleError(
Expand Down Expand Up @@ -653,11 +667,19 @@ export class AgentCore extends YesImBotService<Config> {
}

private clearTopicScores(channelKey: string): void {
for (const key of this.topicScores.get(channelKey) ?? []) this.willing.reset(key);
for (const key of this.topicScores.get(channelKey) ?? []) {
this.logger.debug(
`[${channelKey}] 清除话题意愿 | 计分键: ${key} | 原因: 话题重置或到期 | 清除前: ${this.willing.getCurrentWillingness(key).toFixed(2)}`,
);
this.willing.reset(key);
}
this.topicScores.delete(channelKey);
}

private resetWillingness(channelKey: string): void {
private resetWillingness(channelKey: string, reason = "reset"): void {
this.logger.debug(
`[${channelKey}] 清除意愿状态 | 原因: ${reason} | 普通意愿: ${this.willing.getCurrentWillingness(channelKey).toFixed(2)} | 话题数: ${this.topicScores.get(channelKey)?.size ?? 0}`,
);
this.continuationEpochs?.delete(channelKey);
this.topics?.reset(channelKey);
this.clearTopicScores(channelKey);
Expand All @@ -666,7 +688,13 @@ export class AgentCore extends YesImBotService<Config> {

private trackTopicScores(channelKey: string, snapshots: TopicSnapshot[]): void {
const keys = new Set(snapshots.map((topic) => topic.scoreKey));
for (const old of this.topicScores.get(channelKey) ?? []) if (!keys.has(old)) this.willing.reset(old);
for (const old of this.topicScores.get(channelKey) ?? [])
if (!keys.has(old)) {
this.logger.debug(
`[${channelKey}] 清除话题意愿 | 计分键: ${old} | 原因: 话题移出候选 | 清除前: ${this.willing.getCurrentWillingness(old).toFixed(2)}`,
);
this.willing.reset(old);
}
this.topicScores.set(channelKey, keys);
}

Expand Down
4 changes: 3 additions & 1 deletion packages/core/src/agent/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,9 @@ export const VisionConfigSchema: Schema<VisionConfig> = Schema.object({
enableVision: Schema.boolean().default(false).description("是否启用视觉功能"),
allowedImageTypes: Schema.array(Schema.string()).default(["image/jpeg", "image/png"]).description("允许的图片类型"),
maxImagesInContext: Schema.number().default(3).description("在上下文中允许包含的最大图片数量"),
imageLifecycleCount: Schema.number().default(2).description("图片的上下文生命周期(出现次数)。超过此次数的图片将被忽略,除非被引用"),
imageLifecycleCount: Schema.number()
.default(2)
.description("单条消息中图片在成功请求上下文中的最大出现次数,按会话与机器人账号分别计算;引用原图时可再次查看"),
detail: Schema.union(["low", "high", "auto"]).default("low").description("图片细节程度"),
});

Expand Down
Loading
Loading