Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

♻️ refactor(agent-signal): adapt response language for prompts (#14890)

Neko04e9f7fcea9b
diff --git a/locales/en-US/home.json b/locales/en-US/home.json
index 7228265d9fd..24735d3131b 100644
--- a/locales/en-US/home.json
+++ b/locales/en-US/home.json
@@ -11,6 +11,19 @@
"brief.action.ignore": "Ignore",
"brief.action.retry": "Retry",
"brief.addFeedback": "Share feedback",
+ "brief.agentSignal.selfReview.applied.heading": "Updated",
+ "brief.agentSignal.selfReview.applied.summary": "{{count}} dream update was applied.",
+ "brief.agentSignal.selfReview.applied.summary_plural": "{{count}} dream updates were applied.",
+ "brief.agentSignal.selfReview.applied.title": "Dream updated resources",
+ "brief.agentSignal.selfReview.error.heading": "Issue",
+ "brief.agentSignal.selfReview.error.summary": "Some work could not be completed during this dream.",
+ "brief.agentSignal.selfReview.error.title": "Dream ran into an issue",
+ "brief.agentSignal.selfReview.ideas.summary": "Saved dream notes for future review.",
+ "brief.agentSignal.selfReview.ideas.title": "Dream notes",
+ "brief.agentSignal.selfReview.proposal.heading": "Suggestion",
+ "brief.agentSignal.selfReview.proposal.summary": "{{count}} dream suggestion needs your review.",
+ "brief.agentSignal.selfReview.proposal.summary_plural": "{{count}} dream suggestions need your review.",
+ "brief.agentSignal.selfReview.proposal.title": "Dream suggestion needs review",
"brief.collapse": "Show less",
"brief.commentPlaceholder": "Share your feedback...",
"brief.commentSubmit": "Submit feedback",
diff --git a/locales/zh-CN/home.json b/locales/zh-CN/home.json
index b889e198c87..2e5fd5b98d0 100644
--- a/locales/zh-CN/home.json
+++ b/locales/zh-CN/home.json
@@ -11,6 +11,19 @@
"brief.action.ignore": "忽略",
"brief.action.retry": "重试",
"brief.addFeedback": "分享反馈",
+ "brief.agentSignal.selfReview.applied.heading": "已更新",
+ "brief.agentSignal.selfReview.applied.summary": "已应用 {{count}} 条夜间回顾更新。",
+ "brief.agentSignal.selfReview.applied.summary_plural": "已应用 {{count}} 条夜间回顾更新。",
+ "brief.agentSignal.selfReview.applied.title": "夜间回顾已更新资源",
+ "brief.agentSignal.selfReview.error.heading": "问题",
+ "brief.agentSignal.selfReview.error.summary": "部分夜间回顾内容未能完成。",
+ "brief.agentSignal.selfReview.error.title": "夜间回顾遇到了问题",
+ "brief.agentSignal.selfReview.ideas.summary": "已保存夜间回顾记录,供后续查看。",
+ "brief.agentSignal.selfReview.ideas.title": "夜间回顾记录",
+ "brief.agentSignal.selfReview.proposal.heading": "建议",
+ "brief.agentSignal.selfReview.proposal.summary": "有 {{count}} 条夜间回顾建议需要你确认。",
+ "brief.agentSignal.selfReview.proposal.summary_plural": "有 {{count}} 条夜间回顾建议需要你确认。",
+ "brief.agentSignal.selfReview.proposal.title": "有夜间回顾建议需要确认",
"brief.collapse": "收起",
"brief.commentPlaceholder": "分享你的反馈…",
"brief.commentSubmit": "提交反馈",
diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/__snapshots__/skillIntent.test.ts.snap b/packages/prompts/src/prompts/agentSignal/analyzeIntent/__snapshots__/skillIntent.test.ts.snap
new file mode 100644
index 00000000000..c42d880762f
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/__snapshots__/skillIntent.test.ts.snap
@@ -0,0 +1,14 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`agent signal skill intent prompt > renders classifier messages 1`] = `
+[
+ {
+ "content": "Classify skill intent for Agent Signal using semantic meaning and structured evidence. Return direct_decision only for explicit skill actions or implicit strong future-use procedural learning. Return accumulate for generic praise or weak approval. Return non_skill for user preference that does not belong to skill management. Do not author skills.",
+ "role": "system",
+ },
+ {
+ "content": "{"message":"For future PR reviews, reuse this checklist.","serializedContext":"topic=PR review; checklist: inspect locale keys","topicLabel":"PR review"}",
+ "role": "user",
+ },
+]
+`;
diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts
index df0c54b4422..3b4a2cb053c 100644
--- a/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts
+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/index.ts
@@ -3,3 +3,4 @@ export * from './feedbackSatisfaction';
export * from './gate';
export * from './planMemory';
export * from './route';
+export * from './skillIntent';
diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/skillIntent.test.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/skillIntent.test.ts
new file mode 100644
index 00000000000..de31b9c151c
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/skillIntent.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { createAgentSignalAnalyzeIntentSkillIntentMessages } from './skillIntent';
+
+describe('agent signal skill intent prompt', () => {
+ /**
+ * @example
+ * Skill intent classifier messages include serialized context and strict route labels.
+ */
+ it('renders classifier messages', () => {
+ expect(
+ createAgentSignalAnalyzeIntentSkillIntentMessages({
+ message: 'For future PR reviews, reuse this checklist.',
+ serializedContext: 'topic=PR review; checklist: inspect locale keys',
+ topicLabel: 'PR review',
+ }),
+ ).toMatchSnapshot();
+ });
+});
diff --git a/packages/prompts/src/prompts/agentSignal/analyzeIntent/skillIntent.ts b/packages/prompts/src/prompts/agentSignal/analyzeIntent/skillIntent.ts
new file mode 100644
index 00000000000..b9cb43616b1
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/analyzeIntent/skillIntent.ts
@@ -0,0 +1,49 @@
+export interface AgentSignalSkillIntentPromptInput {
+ /** User feedback message to classify. */
+ message: string;
+ /** Compact same-turn context serialized by the service layer. */
+ serializedContext?: string;
+ /** Optional human-readable topic label extracted from context. */
+ topicLabel?: string;
+}
+
+export const AGENT_SIGNAL_ANALYZE_INTENT_SKILL_INTENT_SYSTEM_ROLE =
+ 'Classify skill intent for Agent Signal using semantic meaning and structured evidence. Return direct_decision only for explicit skill actions or implicit strong future-use procedural learning. Return accumulate for generic praise or weak approval. Return non_skill for user preference that does not belong to skill management. Do not author skills.';
+
+const createAgentSignalAnalyzeIntentSkillIntentPrompt = (
+ input: AgentSignalSkillIntentPromptInput,
+) =>
+ JSON.stringify({
+ message: input.message,
+ serializedContext:
+ input.serializedContext && input.serializedContext.length > 1800
+ ? `${input.serializedContext.slice(0, 1800)}...`
+ : input.serializedContext,
+ topicLabel: input.topicLabel,
+ });
+
+/**
+ * Builds semantic skill-intent classifier messages for Agent Signal feedback.
+ *
+ * Use when:
+ * - Structural rules cannot decide whether feedback should create, refine, or accumulate skill intent
+ * - The service layer needs compact, snapshottable classifier input
+ *
+ * Expects:
+ * - `serializedContext` is already bounded and excludes full document bodies
+ *
+ * Returns:
+ * - System and user messages for structured skill-intent classification
+ */
+export const createAgentSignalAnalyzeIntentSkillIntentMessages = (
+ input: AgentSignalSkillIntentPromptInput,
+) => [
+ {
+ content: AGENT_SIGNAL_ANALYZE_INTENT_SKILL_INTENT_SYSTEM_ROLE,
+ role: 'system' as const,
+ },
+ {
+ content: createAgentSignalAnalyzeIntentSkillIntentPrompt(input),
+ role: 'user' as const,
+ },
+];
diff --git a/packages/prompts/src/prompts/agentSignal/index.ts b/packages/prompts/src/prompts/agentSignal/index.ts
index 719f435147d..8c41c6fc95f 100644
--- a/packages/prompts/src/prompts/agentSignal/index.ts
+++ b/packages/prompts/src/prompts/agentSignal/index.ts
@@ -1,2 +1,5 @@
export * from './analyzeIntent';
+export * from './memoryWriter';
export * from './nightlyReview';
+export * from './selfIteration';
+export * from './skillManagement';
diff --git a/packages/prompts/src/prompts/agentSignal/memoryWriter.test.ts b/packages/prompts/src/prompts/agentSignal/memoryWriter.test.ts
new file mode 100644
index 00000000000..91b1a1fe1df
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/memoryWriter.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createAgentSignalMemoryWriterPrompt,
+ createAgentSignalMemoryWriterSystemRole,
+} from './memoryWriter';
+
+describe('agent signal memory writer prompt', () => {
+ /**
+ * @example
+ * Memory writer explicitly receives memory language.
+ */
+ it('renders memory language in the system role', () => {
+ expect(createAgentSignalMemoryWriterSystemRole({ memoryLanguage: 'zh-CN' })).toContain(
+ 'Write durable memory content in zh-CN.',
+ );
+ });
+
+ /**
+ * @example
+ * User prompt keeps routing context inspectable.
+ */
+ it('renders the user memory prompt with routing context blocks', () => {
+ expect(
+ createAgentSignalMemoryWriterPrompt({
+ evidence: [{ cue: 'going forward', excerpt: 'Going forward, use terse summaries.' }],
+ feedbackHint: 'not_satisfied',
+ memoryLanguage: 'English',
+ message: 'Going forward, use terse summaries.',
+ reason: 'durable preference',
+ }),
+ ).toMatchInlineSnapshot(`
+ "User feedback to analyze for durable memory:
+ Going forward, use terse summaries.
+
+ Memory language: English
+
+ Routing context:
+ Feedback satisfaction hint: not_satisfied
+
+ Domain routing reason: durable preference
+
+ Domain evidence:
+ [{"cue":"going forward","excerpt":"Going forward, use terse summaries."}]"
+ `);
+ });
+});
diff --git a/packages/prompts/src/prompts/agentSignal/memoryWriter.ts b/packages/prompts/src/prompts/agentSignal/memoryWriter.ts
new file mode 100644
index 00000000000..5cc65bde768
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/memoryWriter.ts
@@ -0,0 +1,107 @@
+export interface AgentSignalMemoryWriterLanguageInput {
+ /** Language required for persisted memory text. */
+ memoryLanguage: string;
+}
+
+export interface AgentSignalMemoryWriterPromptInput extends AgentSignalMemoryWriterLanguageInput {
+ /** Conflict policy selected by routing, when present. */
+ conflictPolicy?: unknown;
+ /** Evidence snippets that justify the memory decision. */
+ evidence?: unknown[];
+ /** Feedback satisfaction hint from the classifier. */
+ feedbackHint?: 'not_satisfied' | 'satisfied';
+ /** User feedback being evaluated for durable memory. */
+ message: string;
+ /** Domain-routing reason, when present. */
+ reason?: string;
+ /** Serialized runtime context from the source event. */
+ serializedContext?: string;
+ /** Source-level classifier hints, when present. */
+ sourceHints?: unknown;
+}
+
+const MEMORY_WRITER_SYSTEM_ROLE = `You are the Agent Signal memory writer.
+
+You are not chatting with the user.
+Your job is to decide whether the feedback should update durable user memory.
+
+Use only the lobe-user-memory built-in tool when a durable memory write is justified.
+Choose the correct memory API based on the feedback:
+- addPreferenceMemory for stable future-facing preferences
+- addIdentityMemory / updateIdentityMemory / removeIdentityMemory for enduring identity facts or corrections
+- addContextMemory for ongoing situations, environments, or projects
+- addExperienceMemory for reusable lessons from outcomes or workflows
+- addActivityMemory for notable concrete events worth remembering
+
+Do not use memory tools for requests to create, update, refine, merge, consolidate, or store reusable skills, procedures, workflows, playbooks, checklists, agent capabilities, agent prompts, or agent documents.
+If the feedback asks for a "reusable skill", "future workflow", "PR review checklist skill", "agent capability", or similar operational artifact, skip memory and leave it to the skill/document management path.
+Apply the same boundary to Chinese feedback such as "复用 skill", "可复用流程", "review 流程", "检查清单", "下次参考这个流程", "保留这个流程", or "合并/更新清单".
+Do not summarize skill-management requests as preferences.
+
+If the feedback should not become durable memory, do not call any tools and end briefly.
+Do not invent your own JSON schema. Use the built-in tool exactly as exposed.`;
+
+/**
+ * Builds the system role for Agent Signal durable memory writing.
+ *
+ * Use when:
+ * - Agent Signal routes feedback to the memory action agent
+ * - Persisted memory language must be explicit at the prompt boundary
+ *
+ * Expects:
+ * - `memoryLanguage` is resolved by the server boundary or falls back to English
+ *
+ * Returns:
+ * - Model-facing memory writer system instructions
+ */
+export const createAgentSignalMemoryWriterSystemRole = (
+ input: AgentSignalMemoryWriterLanguageInput,
+) =>
+ [MEMORY_WRITER_SYSTEM_ROLE, `Write durable memory content in ${input.memoryLanguage}.`].join(
+ '\n\n',
+ );
+
+/**
+ * Builds the user prompt for Agent Signal durable memory writing.
+ *
+ * Use when:
+ * - The memory action agent needs feedback plus routing context
+ * - Tests need the exact prompt sent to the model
+ *
+ * Expects:
+ * - `message` is already trimmed and non-empty
+ *
+ * Returns:
+ * - Model-facing user prompt with memory language and routing context blocks
+ */
+export const createAgentSignalMemoryWriterPrompt = (input: AgentSignalMemoryWriterPromptInput) => {
+ const feedbackHintBlock = input.feedbackHint
+ ? `Feedback satisfaction hint: ${input.feedbackHint}`
+ : undefined;
+ const domainReasonBlock = input.reason ? `Domain routing reason: ${input.reason}` : undefined;
+ const evidenceBlock =
+ input.evidence && input.evidence.length > 0
+ ? `Domain evidence:\n${JSON.stringify(input.evidence)}`
+ : undefined;
+ const sourceHintsBlock = input.sourceHints
+ ? `Source hints:\n${JSON.stringify(input.sourceHints)}`
+ : undefined;
+ const conflictPolicyBlock = input.conflictPolicy
+ ? `Conflict policy:\n${JSON.stringify(input.conflictPolicy)}`
+ : undefined;
+ const routingContextBlock = [
+ feedbackHintBlock,
+ domainReasonBlock,
+ evidenceBlock,
+ sourceHintsBlock,
+ conflictPolicyBlock,
+ ]
+ .filter(Boolean)
+ .join('\n\n');
+ const contextBlock = input.serializedContext?.trim()
+ ? `\n\nAdditional runtime context:\n${input.serializedContext}`
+ : '';
+ const hintBlock = routingContextBlock ? `\n\nRouting context:\n${routingContextBlock}` : '';
+
+ return `User feedback to analyze for durable memory:\n${input.message}\n\nMemory language: ${input.memoryLanguage}${hintBlock}${contextBlock}`;
+};
diff --git a/packages/prompts/src/prompts/agentSignal/selfIteration/__snapshots__/runtime.test.ts.snap b/packages/prompts/src/prompts/agentSignal/selfIteration/__snapshots__/runtime.test.ts.snap
new file mode 100644
index 00000000000..d64c1d1b07d
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/selfIteration/__snapshots__/runtime.test.ts.snap
@@ -0,0 +1,23 @@
+// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
+
+exports[`agent signal self-iteration runtime prompt > renders reflection mode prompt with explicit mode and context JSON 1`] = `
+"Agent id: agent-1
+User id: user-1
+Source id: source-2
+Mode: reflection
+Evidence window: 2026-05-09T15:00:00.000Z to 2026-05-09T16:00:00.000Z
+Self-iteration context JSON:
+{"selfFeedbackCandidates":[{"messageId":"m-1"}]}"
+`;
+
+exports[`agent signal self-iteration runtime prompt > renders review mode prompt in stable XML sections 1`] = `
+"<self_iteration_review agent_id="agent-1" review_window_end="2026-05-09T16:00:00.000Z" review_window_start="2026-05-08T16:00:00.000Z" source_id="source-1" user_id="user-1"><review_objective>Inspect this nightly review context and create a self-review proposal when the evidence supports an approval-gated change. Do not finish with only text when a proposal is required.</review_objective><review_policy_markdown>Use these deterministic self-review signal rules before deciding to finish without tools.
+
+| Signal kind | Required decision | Tool call | Notes |
+| --- | --- | --- | --- |
+| \`skill_document_with_tool_failure\` | Approval-gated skill refinement proposal | \`createSelfReviewProposal\` with one \`refine_skill\` action | Use the matching \`managedSkills[].documentId\` or \`documentActivity.skillBucket[].agentDocumentId\` as \`target.skillDocumentId\`; include \`operation: { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }\`; cite topic/message/agent_document evidence refs. |
+| \`repeated_tool_failure\` involving \`replaceSkillContentCAS\` | Do not retry the write directly during nightly review | \`createSelfReviewProposal\` when the failed args contain a corrected skill body or a clear skill target | Prefer the failed tool args as the proposed body; call \`getEvidenceDigest\` first if the body or target is not visible in context. |
+| \`skill_documents_maybe_overlap\` | Consolidation candidate | \`createSelfReviewProposal\` with \`consolidate_skill\` only when there is a canonical skill and explicit source skills | Otherwise record no proposal for this signal alone. |
+
+If a rule says \`createSelfReviewProposal\`, do not stop with only explanatory text. If required fields are missing, use read tools once to gather them; only skip when evidence remains insufficient after reading.</review_policy_markdown><review_window>Review window: 2026-05-08T16:00:00.000Z to 2026-05-09T16:00:00.000Z</review_window><nightly_review_context_json>{"selfReviewSignals":[{"evidenceRefs":[{"id":"doc-1","type":"agent_document"}],"kind":"skill_document_with_tool_failure"}],"topics":[{"id":"topic-1","summary":"Skill update failed after a tool call."}]}</nightly_review_context_json></self_iteration_review>"
+`;
diff --git a/packages/prompts/src/prompts/agentSignal/selfIteration/index.ts b/packages/prompts/src/prompts/agentSignal/selfIteration/index.ts
new file mode 100644
index 00000000000..2bc3e7914d6
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/selfIteration/index.ts
@@ -0,0 +1 @@
+export * from './runtime';
diff --git a/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.test.ts b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.test.ts
new file mode 100644
index 00000000000..ececec50f08
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ createAgentSignalSelfIterationPrompt,
+ createAgentSignalSelfIterationSystemRole,
+ createAgentSignalSelfIterationToolSystemRole,
+} from './runtime';
+
+describe('agent signal self-iteration runtime prompt', () => {
+ /**
+ * @example
+ * Review mode renders the stable nightly review XML envelope.
+ */
+ it('renders review mode prompt in stable XML sections', () => {
+ expect(
+ createAgentSignalSelfIterationPrompt({
+ agentId: 'agent-1',
+ context: {
+ selfReviewSignals: [
+ {
+ evidenceRefs: [{ id: 'doc-1', type: 'agent_document' }],
+ kind: 'skill_document_with_tool_failure',
+ },
+ ],
+ topics: [{ id: 'topic-1', summary: 'Skill update failed after a tool call.' }],
+ },
+ mode: 'review',
+ sourceId: 'source-1',
+ userId: 'user-1',
+ window: {
+ end: '2026-05-09T16:00:00.000Z',
+ start: '2026-05-08T16:00:00.000Z',
+ },
+ }),
+ ).toMatchSnapshot();
+ });
+
+ /**
+ * @example
+ * Reflection mode keeps bounded context visible without nightly review policy XML.
+ */
+ it('renders reflection mode prompt with explicit mode and context JSON', () => {
+ expect(
+ createAgentSignalSelfIterationPrompt({
+ agentId: 'agent-1',
+ context: { selfFeedbackCandidates: [{ messageId: 'm-1' }] },
+ mode: 'reflection',
+ sourceId: 'source-2',
+ userId: 'user-1',
+ window: {
+ end: '2026-05-09T16:00:00.000Z',
+ start: '2026-05-09T15:00:00.000Z',
+ },
+ }),
+ ).toMatchSnapshot();
+ });
+
+ /**
+ * @example
+ * System roles and tool roles stay generated by the prompt package.
+ */
+ it('renders system and tool role text', () => {
+ expect(createAgentSignalSelfIterationSystemRole()).toContain(
+ 'You are the Agent Signal self-iteration agent.',
+ );
+ expect(createAgentSignalSelfIterationToolSystemRole('review')).toContain(
+ 'Use resource read tools before writes',
+ );
+ expect(createAgentSignalSelfIterationToolSystemRole('reflection')).toContain(
+ 'recordSelfFeedbackIntent',
+ );
+ });
+});
diff --git a/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts
new file mode 100644
index 00000000000..3fa2da03ebb
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/selfIteration/runtime.ts
@@ -0,0 +1,146 @@
+import { u } from 'unist-builder';
+import { toXml } from 'xast-util-to-xml';
+import { x } from 'xastscript';
+
+export interface AgentSignalSelfIterationPromptInput {
+ /** Stable agent id being reviewed. */
+ agentId: string;
+ /** Bounded self-iteration context serialized into the runtime prompt. */
+ context: unknown;
+ /** Runtime mode that controls review-specific policy text. */
+ mode: 'feedback' | 'reflection' | 'review';
+ /** Stable source id used for tracing and idempotency. */
+ sourceId: string;
+ /** Stable user id owning the reviewed agent. */
+ userId: string;
+ /** Evidence window exposed to tools and prompt renderers. */
+ window: {
+ /** Review or reflection window end ISO timestamp. */
+ end: string;
+ /** Optional user-local date for nightly review. */
+ localDate?: string;
+ /** Review or reflection window start ISO timestamp. */
+ start: string;
+ /** Optional IANA timezone for user-local windows. */
+ timezone?: string;
+ };
+}
+
+const SELF_ITERATION_SYSTEM_ROLE = [
+ 'You are the Agent Signal self-iteration agent.',
+ 'Inspect the bounded nightly review context and use the provided self-iteration tools to read evidence or apply safe write operations.',
+ 'Evidence ids and proposal keys are different namespaces: read topic/message/tool_call/agent_document evidence with getEvidenceDigest; read proposals with readSelfReviewProposal only when using proposalActivity.active[].proposalKey or keys returned from listSelfReviewProposals.',
+ 'Never claim that a write happened unless a write tool result confirms it.',
+ 'Use writeMemory for explicit durable user preferences such as response style, summary structure, or verification-reporting preferences. Do not turn those preference memories into skills or proposals.',
+ 'Use createSkillIfAbsent only when evidence describes a reusable workflow and you can provide a non-empty skill name and full bodyMarkdown.',
+ 'When review evidence supports an approval-gated change, call createSelfReviewProposal in this run; do not offer to draft it later.',
+ 'For createSelfReviewProposal actions, use actionType exactly create_skill, refine_skill, consolidate_skill, or record_idea. For refine_skill include target.skillDocumentId and operation { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }. For consolidate_skill include operation { domain: "skill", operation: "consolidate", input: { canonicalSkillDocumentId, sourceSkillIds, bodyMarkdown } }. Prefer recordSelfReviewIdea instead of proposal actions when the output is only a thought or question.',
+ 'Stop after the useful self-iteration work is complete and summarize the confirmed outcome.',
+].join('\n');
+
+/**
+ * Builds the system role for Agent Signal self-iteration runtime calls.
+ *
+ * Use when:
+ * - A server AgentRuntime call executes bounded self-iteration work
+ * - Tests need the exact model-facing system role text
+ *
+ * Expects:
+ * - Tool manifests are provided by the service layer
+ *
+ * Returns:
+ * - Stable model-facing system instructions
+ */
+export const createAgentSignalSelfIterationSystemRole = () => SELF_ITERATION_SYSTEM_ROLE;
+
+/**
+ * Builds the tool manifest system role for Agent Signal self-iteration tools.
+ *
+ * Use when:
+ * - Review mode needs proposal-specific read/write rules
+ * - Reflection and intent modes need immediate feedback capture rules
+ *
+ * Expects:
+ * - `mode` matches the runtime prompt mode
+ *
+ * Returns:
+ * - Stable model-facing tool-use instructions
+ */
+export const createAgentSignalSelfIterationToolSystemRole = (
+ mode: AgentSignalSelfIterationPromptInput['mode'],
+) =>
+ mode === 'review'
+ ? 'Use resource read tools before writes when evidence is incomplete. Use getEvidenceDigest for topic/message/tool_call/agent_document evidenceRefs. Use readSelfReviewProposal only with proposal keys from proposalActivity.active or listSelfReviewProposals, never with evidence ids. Treat write tool results as the source of truth.'
+ : 'Use resource read tools before writes when evidence is incomplete. Direct-apply only safe memory or bounded skill updates. Record approval-gated or unsupported reflection output with recordSelfFeedbackIntent, and record non-actionable thoughts with recordReflectionIdea.';
+
+const createNightlyReviewPromptXml = (input: AgentSignalSelfIterationPromptInput) =>
+ toXml(
+ u('root', [
+ x(
+ 'self_iteration_review',
+ {
+ agent_id: input.agentId,
+ review_window_end: input.window.end,
+ review_window_start: input.window.start,
+ source_id: input.sourceId,
+ user_id: input.userId,
+ },
+ x(
+ 'review_objective',
+ 'Inspect this nightly review context and create a self-review proposal when the evidence supports an approval-gated change. Do not finish with only text when a proposal is required.',
+ ),
+ x(
+ 'review_policy_markdown',
+ // NOTICE:
+ // Keep this as a rule table, not a precomputed proposal payload.
+ // Root cause summary: changing this to generic self-iteration wording made the local
+ // E2E review source complete without producing the expected Daily Brief proposal.
+ // Source/context: `devtools/agent-signal/self-iteration-e2e/run-local-e2e.ts`.
+ // Removal condition: nightly self-review prompt/eval coverage proves generic wording
+ // still produces equivalent proposal behavior.
+ [
+ 'Use these deterministic self-review signal rules before deciding to finish without tools.',
+ '',
+ '| Signal kind | Required decision | Tool call | Notes |',
+ '| --- | --- | --- | --- |',
+ '| `skill_document_with_tool_failure` | Approval-gated skill refinement proposal | `createSelfReviewProposal` with one `refine_skill` action | Use the matching `managedSkills[].documentId` or `documentActivity.skillBucket[].agentDocumentId` as `target.skillDocumentId`; include `operation: { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }`; cite topic/message/agent_document evidence refs. |',
+ '| `repeated_tool_failure` involving `replaceSkillContentCAS` | Do not retry the write directly during nightly review | `createSelfReviewProposal` when the failed args contain a corrected skill body or a clear skill target | Prefer the failed tool args as the proposed body; call `getEvidenceDigest` first if the body or target is not visible in context. |',
+ '| `skill_documents_maybe_overlap` | Consolidation candidate | `createSelfReviewProposal` with `consolidate_skill` only when there is a canonical skill and explicit source skills | Otherwise record no proposal for this signal alone. |',
+ '',
+ 'If a rule says `createSelfReviewProposal`, do not stop with only explanatory text. If required fields are missing, use read tools once to gather them; only skip when evidence remains insufficient after reading.',
+ ].join('\n'),
+ ),
+ x('review_window', `Review window: ${input.window.start} to ${input.window.end}`),
+ x('nightly_review_context_json', JSON.stringify(input.context)),
+ ),
+ ]),
+ );
+
+/**
+ * Builds the user prompt for Agent Signal self-iteration runtime calls.
+ *
+ * Use when:
+ * - The self-iteration service needs review, reflection, or intent runtime prompts
+ * - Tests need stable rendered prompt snapshots
+ *
+ * Expects:
+ * - Context has already been collected and bounded by the service layer
+ *
+ * Returns:
+ * - Stable model-facing user prompt text
+ */
+export const createAgentSignalSelfIterationPrompt = (
+ input: AgentSignalSelfIterationPromptInput,
+) => {
+ if (input.mode === 'review') return createNightlyReviewPromptXml(input);
+
+ return [
+ `Agent id: ${input.agentId}`,
+ `User id: ${input.userId}`,
+ `Source id: ${input.sourceId}`,
+ `Mode: ${input.mode}`,
+ `Evidence window: ${input.window.start} to ${input.window.end}`,
+ 'Self-iteration context JSON:',
+ JSON.stringify(input.context),
+ ].join('\n');
+};
diff --git a/packages/prompts/src/prompts/agentSignal/skillManagement/index.ts b/packages/prompts/src/prompts/agentSignal/skillManagement/index.ts
new file mode 100644
index 00000000000..9c9abdc8682
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/skillManagement/index.ts
@@ -0,0 +1 @@
+export * from './languageInstruction';
diff --git a/packages/prompts/src/prompts/agentSignal/skillManagement/languageInstruction.test.ts b/packages/prompts/src/prompts/agentSignal/skillManagement/languageInstruction.test.ts
new file mode 100644
index 00000000000..850adcf1706
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/skillManagement/languageInstruction.test.ts
@@ -0,0 +1,49 @@
+import { describe, expect, it } from 'vitest';
+
+import { createAgentSignalSkillLanguageInstruction } from './languageInstruction';
+
+describe('agent signal skill language instruction', () => {
+ /**
+ * @example
+ * Create defaults to responseLanguage when evidence does not imply a better language.
+ */
+ it('renders create instruction with response language default', () => {
+ expect(
+ createAgentSignalSkillLanguageInstruction({
+ mode: 'create',
+ responseLanguage: 'zh-CN',
+ }),
+ ).toContain(
+ 'Default to zh-CN when the source evidence does not imply a better artifact language.',
+ );
+ });
+
+ /**
+ * @example
+ * Refine preserves existing skill language.
+ */
+ it('renders refine instruction with existing language preservation', () => {
+ expect(
+ createAgentSignalSkillLanguageInstruction({
+ existingSkillLanguage: 'English',
+ mode: 'refine',
+ responseLanguage: 'zh-CN',
+ }),
+ ).toContain('Preserve the existing skill primary language: English.');
+ });
+
+ /**
+ * @example
+ * Domain target language beats UI language for work products.
+ */
+ it('documents domain target language over UI language', () => {
+ expect(
+ createAgentSignalSkillLanguageInstruction({
+ mode: 'create',
+ responseLanguage: 'zh-CN',
+ }),
+ ).toContain(
+ 'English academic writing skill under Chinese UI should keep the reusable writing artifact in English',
+ );
+ });
+});
diff --git a/packages/prompts/src/prompts/agentSignal/skillManagement/languageInstruction.ts b/packages/prompts/src/prompts/agentSignal/skillManagement/languageInstruction.ts
new file mode 100644
index 00000000000..2f2708caf25
--- /dev/null
+++ b/packages/prompts/src/prompts/agentSignal/skillManagement/languageInstruction.ts
@@ -0,0 +1,38 @@
+export interface AgentSignalSkillLanguageInstructionInput {
+ /** Current primary language of an existing skill, when refining or consolidating. */
+ existingSkillLanguage?: string;
+ /** Authoring mode that controls preservation rules. */
+ mode: 'consolidate' | 'create' | 'refine';
+ /** User-visible response language from settings. */
+ responseLanguage: string;
+}
+
+/**
+ * Builds the language policy block for Agent Signal skill artifacts.
+ *
+ * Use when:
+ * - Agent Signal asks a model to create, refine, or consolidate persisted skill content
+ * - Skill artifact language must be chosen separately from UI response language
+ *
+ * Expects:
+ * - `responseLanguage` comes from user settings
+ * - `existingSkillLanguage` is supplied when known for refine/consolidate flows
+ *
+ * Returns:
+ * - Prompt text that explains skill artifact language selection
+ */
+export const createAgentSignalSkillLanguageInstruction = (
+ input: AgentSignalSkillLanguageInstructionInput,
+) =>
+ [
+ 'Skill artifact language rules:',
+ '- Explicit user language instruction wins.',
+ input.existingSkillLanguage
+ ? `- Preserve the existing skill primary language: ${input.existingSkillLanguage}.`
+ : `- Default to ${input.responseLanguage} when the source evidence does not imply a better artifact language.`,
+ '- Writing, academic, PR, marketing, legal, translation, and domain-specific skills should use the target work language, not the UI language.',
+ '- English academic writing skill under Chinese UI should keep the reusable writing artifact in English.',
+ '- Chinese PR copy skill under English UI should keep the reusable writing artifact in Chinese.',
+ '- Mixed-language skills are allowed when useful, such as Chinese instructions with English reusable copy templates.',
+ '- User-visible proposal summaries still use responseLanguage; skill name, title, description, and bodyMarkdown follow these artifact-language rules.',
+ ].join('\n');
diff --git a/packages/prompts/src/prompts/agentSkillManager/authoring.test.ts b/packages/prompts/src/prompts/agentSkillManager/authoring.test.ts
index 0580f119d54..734494d72c2 100644
--- a/packages/prompts/src/prompts/agentSkillManager/authoring.test.ts
+++ b/packages/prompts/src/prompts/agentSkillManager/authoring.test.ts
@@ -4,6 +4,9 @@ import {
AGENT_SKILL_CONSOLIDATE_SYSTEM_ROLE,
AGENT_SKILL_CREATE_SYSTEM_ROLE,
AGENT_SKILL_REFINE_SYSTEM_ROLE,
+ createAgentSkillConsolidatePrompt,
+ createAgentSkillCreatePrompt,
+ createAgentSkillRefinePrompt,
} from './index';
const authoringRoles = [
@@ -66,4 +69,39 @@ describe('agent skill authoring prompts', () => {
'Do not add bodyMarkdown sections named Trigger',
);
});
+
+ /**
+ * @example
+ * Skill authoring prompts include caller-supplied artifact language instructions.
+ */
+ it('renders artifact language instructions in authoring prompts', () => {
+ const languageInstruction = [
+ 'Skill artifact language rules:',
+ '- Explicit user language instruction wins.',
+ ].join('\n');
+ const prompts = [
+ createAgentSkillCreatePrompt({
+ agentId: 'agent-1',
+ evidence: [{ cue: 'future', excerpt: 'Use this checklist later.' }],
+ feedbackMessage: 'Keep this as a reusable checklist.',
+ languageInstruction,
+ }),
+ createAgentSkillRefinePrompt({
+ languageInstruction,
+ reason: 'New evidence',
+ skillContent: '# Existing',
+ skillMetadata: {},
+ }),
+ createAgentSkillConsolidatePrompt({
+ languageInstruction,
+ reason: 'Overlap',
+ sourceSkills: [{ content: '# A', id: 'skill-1', metadata: {} }],
+ }),
+ ];
+
+ for (const prompt of prompts) {
+ expect(prompt).toContain('Skill artifact language rules:');
+ expect(prompt).toContain('Explicit user language instruction wins.');
+ }
+ });
});
diff --git a/packages/prompts/src/prompts/agentSkillManager/consolidate.ts b/packages/prompts/src/prompts/agentSkillManager/consolidate.ts
index dd7813aad0e..fa7255ccfc3 100644
--- a/packages/prompts/src/prompts/agentSkillManager/consolidate.ts
+++ b/packages/prompts/src/prompts/agentSkillManager/consolidate.ts
@@ -2,6 +2,8 @@
* Input used by the focused skill consolidation prompt.
*/
export interface AgentSkillConsolidatePromptInput {
+ /** Language instruction block for persisted skill artifact text. */
+ languageInstruction?: string;
/** Reason the source skills should be consolidated. */
reason: string;
/** Overlapping skills that should be reconciled. */
@@ -84,5 +86,7 @@ Output ONLY the JSON object, no markdown fences or explanations.`;
* - A compact prompt containing serialized consolidation context
*/
export const createAgentSkillConsolidatePrompt = (input: AgentSkillConsolidatePromptInput) => {
- return `Consolidate these skills.\ninput=${JSON.stringify(input)}`;
+ const languageInstruction = input.languageInstruction ? `\n\n${input.languageInstruction}` : '';
+
+ return `Consolidate these skills.${languageInstruction}\ninput=${JSON.stringify(input)}`;
};
diff --git a/packages/prompts/src/prompts/agentSkillManager/create.ts b/packages/prompts/src/prompts/agentSkillManager/create.ts
index 7ee91d6ff8f..0c498497f1c 100644
--- a/packages/prompts/src/prompts/agentSkillManager/create.ts
+++ b/packages/prompts/src/prompts/agentSkillManager/create.ts
@@ -14,6 +14,8 @@ export interface AgentSkillCreatePromptInput {
evidence: Array<{ cue: string; excerpt: string }>;
/** Original feedback or instruction that triggered skill creation. */
feedbackMessage: string;
+ /** Language instruction block for persisted skill artifact text. */
+ languageInstruction?: string;
/** Optional source agent document id selected by the decision worker. */
sourceAgentDocumentId?: string;
/** Optional source document content selected by the decision worker. */
@@ -92,5 +94,7 @@ Output ONLY the JSON object, no markdown fences or explanations.`;
* - A compact prompt containing serialized creation context
*/
export const createAgentSkillCreatePrompt = (input: AgentSkillCreatePromptInput) => {
- return `Create a managed Agent Skill from this evidence.\ninput=${JSON.stringify(input)}`;
+ const languageInstruction = input.languageInstruction ? `\n\n${input.languageInstruction}` : '';
+
+ return `Create a managed Agent Skill from this evidence.${languageInstruction}\ninput=${JSON.stringify(input)}`;
};
diff --git a/packages/prompts/src/prompts/agentSkillManager/refine.ts b/packages/prompts/src/prompts/agentSkillManager/refine.ts
index d56a757bfb4..35e4cba9ac2 100644
--- a/packages/prompts/src/prompts/agentSkillManager/refine.ts
+++ b/packages/prompts/src/prompts/agentSkillManager/refine.ts
@@ -2,6 +2,8 @@
* Input used by the focused skill refinement prompt.
*/
export interface AgentSkillRefinePromptInput {
+ /** Language instruction block for persisted skill artifact text. */
+ languageInstruction?: string;
/** Reason the skill should be refined. */
reason: string;
/** Optional package tree summary for adjacent resources. */
@@ -80,5 +82,7 @@ Output ONLY the JSON object, no markdown fences or explanations.`;
* - A compact prompt containing serialized refinement context
*/
export const createAgentSkillRefinePrompt = (input: AgentSkillRefinePromptInput) => {
- return `Refine this skill.\ninput=${JSON.stringify(input)}`;
+ const languageInstruction = input.languageInstruction ? `\n\n${input.languageInstruction}` : '';
+
+ return `Refine this skill.${languageInstruction}\ninput=${JSON.stringify(input)}`;
};
diff --git a/src/locales/default/home.ts b/src/locales/default/home.ts
index 5cfed511603..c05310dce27 100644
--- a/src/locales/default/home.ts
+++ b/src/locales/default/home.ts
@@ -11,6 +11,21 @@ export default {
'brief.action.feedback': 'Feedback',
'brief.action.ignore': 'Ignore',
'brief.action.retry': 'Retry',
+ 'brief.agentSignal.selfReview.applied.heading': 'Updated',
+ 'brief.agentSignal.selfReview.applied.summary': '{{count}} dream update was applied.',
+ 'brief.agentSignal.selfReview.applied.summary_plural': '{{count}} dream updates were applied.',
+ 'brief.agentSignal.selfReview.applied.title': 'Dream updated resources',
+ 'brief.agentSignal.selfReview.error.heading': 'Issue',
+ 'brief.agentSignal.selfReview.error.summary':
+ 'Some work could not be completed during this dream.',
+ 'brief.agentSignal.selfReview.error.title': 'Dream ran into an issue',
+ 'brief.agentSignal.selfReview.ideas.summary': 'Saved dream notes for future review.',
+ 'brief.agentSignal.selfReview.ideas.title': 'Dream notes',
+ 'brief.agentSignal.selfReview.proposal.heading': 'Suggestion',
+ 'brief.agentSignal.selfReview.proposal.summary': '{{count}} dream suggestion needs your review.',
+ 'brief.agentSignal.selfReview.proposal.summary_plural':
+ '{{count}} dream suggestions need your review.',
+ 'brief.agentSignal.selfReview.proposal.title': 'Dream suggestion needs review',
'brief.collapse': 'Show less',
'brief.commentPlaceholder': 'Share your feedback...',
'brief.commentSubmit': 'Submit feedback',
diff --git a/src/server/services/agentSignal/__tests__/promptBoundaries.test.ts b/src/server/services/agentSignal/__tests__/promptBoundaries.test.ts
new file mode 100644
index 00000000000..dd6a0f7c4a9
--- /dev/null
+++ b/src/server/services/agentSignal/__tests__/promptBoundaries.test.ts
@@ -0,0 +1,37 @@
+// @vitest-environment node
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+const root = process.cwd();
+
+const read = (filePath: string) => readFileSync(path.join(root, filePath), 'utf8');
+
+describe('agent signal prompt boundaries', () => {
+ /**
+ * @example
+ * Self-iteration execute delegates model-facing runtime prompt text to @lobechat/prompts.
+ */
+ it('keeps self-iteration runtime prompt words out of execute service', () => {
+ const source = read('src/server/services/agentSignal/services/selfIteration/execute.ts');
+
+ expect(source).not.toContain('const SELF_ITERATION_SYSTEM_ROLE');
+ expect(source).not.toContain('const createNightlyReviewPromptXml');
+ expect(source).toContain('createAgentSignalSelfIterationPrompt');
+ });
+
+ /**
+ * @example
+ * Memory writer delegates model-facing prompt words to @lobechat/prompts.
+ */
+ it('keeps memory writer prompt words out of user memory action service', () => {
+ const source = read(
+ 'src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts',
+ );
+
+ expect(source).not.toContain('const MEMORY_WRITER_SYSTEM_ROLE');
+ expect(source).not.toContain('const toMemoryWriterPrompt');
+ expect(source).toContain('createAgentSignalMemoryWriterPrompt');
+ });
+});
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts
index 9e72275988e..724d91f020c 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/__tests__/skillManagement.test.ts
@@ -455,6 +455,7 @@ describe('defineSkillManagementActionHandler', () => {
const handler = defineSkillManagementActionHandler({
db: {} as never,
+ responseLanguage: 'zh-CN',
selfIterationEnabled: true,
skillCreateRunner,
skillDecisionRunner,
@@ -495,6 +496,18 @@ describe('defineSkillManagementActionHandler', () => {
turnContext: '{"surface":"chat"}',
}),
);
+ expect(skillCreateRunner).toHaveBeenCalledWith(
+ expect.objectContaining({
+ languageInstruction: expect.stringContaining('Skill artifact language rules:'),
+ }),
+ );
+ expect(skillCreateRunner).toHaveBeenCalledWith(
+ expect.objectContaining({
+ languageInstruction: expect.stringContaining(
+ 'Default to zh-CN when the source evidence does not imply a better artifact language.',
+ ),
+ }),
+ );
expect(result).toMatchObject({
output: {
decision: { action: 'create', confidence: 0.9, reason: 'reusable workflow feedback' },
@@ -528,6 +541,7 @@ describe('defineSkillManagementActionHandler', () => {
const handler = defineSkillManagementActionHandler({
db: {} as never,
+ responseLanguage: 'zh-CN',
selfIterationEnabled: true,
skillCandidateSkillsFactory: async () => [
{ id: 'review-skill-bundle-id', name: 'Review Skill', scope: 'agent' },
@@ -1132,6 +1146,7 @@ describe('defineSkillManagementActionHandler', () => {
expect(skillMaintainerRunner).toHaveBeenCalledWith(
expect.objectContaining({
+ languageInstruction: expect.stringContaining('Skill artifact language rules:'),
targetSkills: [
expect.objectContaining({
content: '# review-skill-bundle-id',
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
index 92b08fd8781..27d76da50b6 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/skillManagement.ts
@@ -27,6 +27,7 @@ import {
AGENT_SKILL_CREATE_SYSTEM_ROLE,
AGENT_SKILL_MANAGER_DECISION_SYSTEM_ROLE,
AGENT_SKILL_REFINE_SYSTEM_ROLE,
+ createAgentSignalSkillLanguageInstruction,
createAgentSkillConsolidatePrompt,
createAgentSkillCreatePrompt,
createAgentSkillManagerDecisionPrompt,
@@ -145,6 +146,8 @@ export interface SkillManagementActionHandlerOptions {
db: LobeChatDatabase;
/** Optional procedure state used to read user-stage skill intent records. */
procedureState?: Pick<ProcedureStateService, 'skillIntentRecords'>;
+ /** User-visible response language used as the default for newly-authored skill artifacts. */
+ responseLanguage?: string;
selfIterationEnabled: boolean;
skillCandidateSkillsFactory?: (input: {
agentId: string;
@@ -285,6 +288,8 @@ export interface SkillManagementAgentModelConfig {
export interface SkillMaintainerWorkflowInput {
decision: SkillManagementDecision;
+ /** Language instruction block for persisted skill artifact text. */
+ languageInstruction?: string;
signal: SkillManagementActionInput;
targetSkills: Array<{
content: string;
@@ -309,6 +314,8 @@ export interface SkillMaintainerWorkflowResult {
export interface SkillCreateAuthoringInput {
candidateSkills?: SkillManagementCandidateSkill[];
decision: SkillManagementDecision;
+ /** Language instruction block for persisted skill artifact text. */
+ languageInstruction?: string;
signal: SkillManagementActionInput;
sourceAgentDocumentId?: string;
sourceDocumentContent?: string;
@@ -1225,6 +1232,7 @@ class SkillMaintainerWorkflowAgentService {
const isRefine = input.type === 'refine';
const content = isRefine
? createAgentSkillRefinePrompt({
+ languageInstruction: input.languageInstruction,
reason: input.decision.reason ?? input.signal.reason ?? 'Refine selected skill.',
signalContext: {
evidence: input.signal.evidence,
@@ -1236,6 +1244,7 @@ class SkillMaintainerWorkflowAgentService {
skillMetadata: input.targetSkills[0]?.metadata ?? {},
})
: createAgentSkillConsolidatePrompt({
+ languageInstruction: input.languageInstruction,
reason: input.decision.reason ?? input.signal.reason ?? 'Consolidate selected skills.',
sourceSkills: input.targetSkills,
});
@@ -1298,6 +1307,7 @@ class SkillCreateAuthoringAgentService {
...(input.candidateSkills?.length ? { candidateSkills: input.candidateSkills } : {}),
evidence: input.signal.evidence ?? [],
feedbackMessage: input.signal.message,
+ languageInstruction: input.languageInstruction,
sourceAgentDocumentId: input.sourceAgentDocumentId,
sourceDocumentContent: input.sourceDocumentContent,
turnContext: input.signal.serializedContext,
@@ -1435,6 +1445,26 @@ const readTargetSkills = async (
return results.filter((skill): skill is SkillDetail => Boolean(skill));
};
+const readSkillPrimaryLanguage = (skill?: SkillDetail) => {
+ const frontmatter = skill?.frontmatter;
+ if (!frontmatter || typeof frontmatter !== 'object') return undefined;
+
+ const language = (frontmatter as unknown as Record<string, unknown>).language;
+
+ return typeof language === 'string' && language.trim().length > 0 ? language.trim() : undefined;
+};
+
+const createSkillArtifactLanguageInstruction = (input: {
+ existingSkillLanguage?: string;
+ mode: 'consolidate' | 'create' | 'refine';
+ responseLanguage?: string;
+}) =>
+ createAgentSignalSkillLanguageInstruction({
+ existingSkillLanguage: input.existingSkillLanguage,
+ mode: input.mode,
+ responseLanguage: input.responseLanguage ?? 'en-US',
+ });
+
const runMaintainerWorkflow = async (
input: SkillManagementActionInput,
options: SkillManagementActionHandlerOptions,
@@ -1485,6 +1515,11 @@ const runMaintainerWorkflow = async (
SkillMaintainerWorkflowResultSchema.parse(
await workflowRunner({
decision,
+ languageInstruction: createSkillArtifactLanguageInstruction({
+ existingSkillLanguage: readSkillPrimaryLanguage(targetSkills[0]),
+ mode: decision.action,
+ responseLanguage: options.responseLanguage,
+ }),
signal: input,
targetSkills: targetSkills.map((skill) => ({
content: skill.content ?? '',
@@ -1656,6 +1691,10 @@ const runCreateWorkflow = async (
await createRunner({
candidateSkills: input.candidateSkills,
decision,
+ languageInstruction: createSkillArtifactLanguageInstruction({
+ mode: 'create',
+ responseLanguage: options.responseLanguage,
+ }),
signal: input,
sourceAgentDocumentId: source?.sourceAgentDocumentId,
sourceDocumentContent: source?.sourceDocumentContent,
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
index 9247cdbedc1..597b77d80c6 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/actions/userMemory.ts
@@ -7,6 +7,10 @@ import type {
} from '@lobechat/agent-signal';
import { MemoryApiName, MemoryIdentifier } from '@lobechat/builtin-tool-memory';
import type { LobeToolManifest, ToolExecutor, ToolSource } from '@lobechat/context-engine';
+import {
+ createAgentSignalMemoryWriterPrompt,
+ createAgentSignalMemoryWriterSystemRole,
+} from '@lobechat/prompts';
import { RequestTrigger } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
@@ -52,27 +56,6 @@ const MEMORY_WRITE_TOOL_NAMES = new Set(
].map((apiName) => `${MemoryIdentifier}/${apiName}`),
);
-const MEMORY_WRITER_SYSTEM_ROLE = `You are the Agent Signal memory writer.
-
-You are not chatting with the user.
-Your job is to decide whether the feedback should update durable user memory.
-
-Use only the lobe-user-memory built-in tool when a durable memory write is justified.
-Choose the correct memory API based on the feedback:
-- addPreferenceMemory for stable future-facing preferences
-- addIdentityMemory / updateIdentityMemory / removeIdentityMemory for enduring identity facts or corrections
-- addContextMemory for ongoing situations, environments, or projects
-- addExperienceMemory for reusable lessons from outcomes or workflows
-- addActivityMemory for notable concrete events worth remembering
-
-Do not use memory tools for requests to create, update, refine, merge, consolidate, or store reusable skills, procedures, workflows, playbooks, checklists, agent capabilities, agent prompts, or agent documents.
-If the feedback asks for a "reusable skill", "future workflow", "PR review checklist skill", "agent capability", or similar operational artifact, skip memory and leave it to the skill/document management path.
-Apply the same boundary to Chinese feedback such as "复用 skill", "可复用流程", "review 流程", "检查清单", "下次参考这个流程", "保留这个流程", or "合并/更新清单".
-Do not summarize skill-management requests as preferences.
-
-If the feedback should not become durable memory, do not call any tools and end briefly.
-Do not invent your own JSON schema. Use the built-in tool exactly as exposed.`;
-
export interface MemoryAgentActionResult {
detail?: string;
status: 'applied' | 'failed' | 'skipped';
@@ -86,6 +69,7 @@ export interface UserMemoryActionHandlerOptions {
conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;
evidence?: AgentSignalFeedbackEvidence[];
feedbackHint?: 'not_satisfied' | 'satisfied';
+ memoryLanguage?: string;
message: string;
reason?: string;
serializedContext?: string;
@@ -123,46 +107,6 @@ const isUserMemoryAction = (action: BaseAction): action is ActionUserMemoryHandl
return action.actionType === AGENT_SIGNAL_POLICY_ACTION_TYPES.userMemoryHandle;
};
-const toMemoryWriterPrompt = (input: {
- conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;
- evidence?: AgentSignalFeedbackEvidence[];
- feedbackHint?: 'not_satisfied' | 'satisfied';
- message: string;
- reason?: string;
- serializedContext?: string;
- sourceHints?: AgentSignalFeedbackSourceHints;
-}) => {
- const feedbackHintBlock = input.feedbackHint
- ? `Feedback satisfaction hint: ${input.feedbackHint}`
- : undefined;
- const domainReasonBlock = input.reason ? `Domain routing reason: ${input.reason}` : undefined;
- const evidenceBlock =
- input.evidence && input.evidence.length > 0
- ? `Domain evidence:\n${JSON.stringify(input.evidence)}`
- : undefined;
- const sourceHintsBlock = input.sourceHints
- ? `Source hints:\n${JSON.stringify(input.sourceHints)}`
- : undefined;
- const conflictPolicyBlock = input.conflictPolicy
- ? `Conflict policy:\n${JSON.stringify(input.conflictPolicy)}`
- : undefined;
- const routingContextBlock = [
- feedbackHintBlock,
- domainReasonBlock,
- evidenceBlock,
- sourceHintsBlock,
- conflictPolicyBlock,
- ]
- .filter(Boolean)
- .join('\n\n');
- const contextBlock = input.serializedContext?.trim()
- ? `\n\nAdditional runtime context:\n${input.serializedContext}`
- : '';
- const hintBlock = routingContextBlock ? `\n\nRouting context:\n${routingContextBlock}` : '';
-
- return `User feedback to analyze for durable memory:\n${input.message}${hintBlock}${contextBlock}`;
-};
-
const createInitialContext = (operationId: string): AgentRuntimeContext => {
return {
payload: { message: [] },
@@ -215,6 +159,7 @@ export const runMemoryActionAgent = async (
conflictPolicy?: AgentSignalFeedbackDomainConflictPolicy;
evidence?: AgentSignalFeedbackEvidence[];
feedbackHint?: 'not_satisfied' | 'satisfied';
+ memoryLanguage?: string;
message: string;
reason?: string;
serializedContext?: string;
@@ -233,6 +178,7 @@ export const runMemoryActionAgent = async (
const agentService = options.agentService ?? new AgentService(options.db, options.userId);
const pluginModel = options.pluginModel ?? new PluginModel(options.db, options.userId);
const agentConfig = await agentService.getAgentConfig(input.agentId);
+ const memoryLanguage = input.memoryLanguage ?? 'English';
if (!agentConfig?.model || !agentConfig?.provider) {
return {
@@ -259,7 +205,7 @@ export const runMemoryActionAgent = async (
const memoryRuntimeAgentConfig = {
...agentConfig,
plugins: [MemoryIdentifier],
- systemRole: MEMORY_WRITER_SYSTEM_ROLE,
+ systemRole: createAgentSignalMemoryWriterSystemRole({ memoryLanguage }),
};
const toolsEngine = createServerAgentToolsEngine(toolsContext, {
@@ -308,7 +254,12 @@ export const runMemoryActionAgent = async (
},
autoStart: false,
initialContext,
- initialMessages: [{ content: toMemoryWriterPrompt(input), role: 'user' }],
+ initialMessages: [
+ {
+ content: createAgentSignalMemoryWriterPrompt({ ...input, memoryLanguage }),
+ role: 'user',
+ },
+ ],
modelRuntimeConfig: {
model: agentConfig.model,
provider: agentConfig.provider,
diff --git a/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts b/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts
index 91777e85dee..5c06984d8e2 100644
--- a/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts
+++ b/src/server/services/agentSignal/policies/analyzeIntent/skillIntent.ts
@@ -1,5 +1,6 @@
import { DEFAULT_MINI_SYSTEM_AGENT_ITEM } from '@lobechat/const';
-import type { GenerateObjectPayload, GenerateObjectSchema } from '@lobechat/model-runtime';
+import type { GenerateObjectSchema } from '@lobechat/model-runtime';
+import { createAgentSignalAnalyzeIntentSkillIntentMessages } from '@lobechat/prompts';
import { RequestTrigger } from '@lobechat/types';
import debug from 'debug';
import { z } from 'zod';
@@ -254,27 +255,6 @@ export interface SkillIntentClassifierAgentModelConfig {
provider: string;
}
-const createSkillIntentClassifierMessages = (
- input: SkillIntentClassifierInput,
-): GenerateObjectPayload['messages'] => [
- {
- content:
- 'Classify skill intent for Agent Signal using semantic meaning and structured evidence. Return direct_decision only for explicit skill actions or implicit strong future-use procedural learning. Return accumulate for generic praise or weak approval. Return non_skill for user preference that does not belong to skill management. Do not author skills.',
- role: 'system',
- },
- {
- content: JSON.stringify({
- message: input.message,
- serializedContext:
- input.serializedContext && input.serializedContext.length > 1800
- ? `${input.serializedContext.slice(0, 1800)}...`
- : input.serializedContext,
- topicLabel: input.topicLabel,
- }),
- role: 'user',
- },
-];
-
/**
* Model-backed skill-intent classifier for skill-domain feedback.
*
@@ -335,7 +315,7 @@ export class SkillIntentClassifierAgentService implements SkillIntentClassifierS
const result = await modelRuntime.generateObject(
{
- messages: createSkillIntentClassifierMessages(input),
+ messages: createAgentSignalAnalyzeIntentSkillIntentMessages(input),
model: this.modelConfig.model,
schema: SkillIntentGenerateObjectSchema,
},
diff --git a/src/server/services/agentSignal/services/selfIteration/execute.ts b/src/server/services/agentSignal/services/selfIteration/execute.ts
index 7ea3a1052f1..ef2f9ba9fbd 100644
--- a/src/server/services/agentSignal/services/selfIteration/execute.ts
+++ b/src/server/services/agentSignal/services/selfIteration/execute.ts
@@ -7,11 +7,13 @@ import type { ChatStreamPayload, ModelRuntime } from '@lobechat/model-runtime';
import { consumeStreamUntilDone } from '@lobechat/model-runtime';
import { SpanStatusCode } from '@lobechat/observability-otel/api';
import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
+import {
+ createAgentSignalSelfIterationPrompt,
+ createAgentSignalSelfIterationSystemRole,
+ createAgentSignalSelfIterationToolSystemRole,
+} from '@lobechat/prompts';
import type { ChatToolPayload, MessageToolCall, ModelUsage } from '@lobechat/types';
import { RequestTrigger } from '@lobechat/types';
-import { u } from 'unist-builder';
-import { toXml } from 'xast-util-to-xml';
-import { x } from 'xastscript';
import type { NightlyReviewContext } from './review/collect';
import type { SelfReviewIdea, SelfReviewProposalBaseSnapshot } from './review/proposal';
@@ -427,28 +429,13 @@ const createToolManifest = (mode: IterationMode): LobeToolManifest => {
description: 'Read evidence and apply safe resource operations.',
title: 'Agent Signal Self-Iteration',
},
- systemRole:
- mode === 'review'
- ? 'Use resource read tools before writes when evidence is incomplete. Use getEvidenceDigest for topic/message/tool_call/agent_document evidenceRefs. Use readSelfReviewProposal only with proposal keys from proposalActivity.active or listSelfReviewProposals, never with evidence ids. Treat write tool results as the source of truth.'
- : 'Use resource read tools before writes when evidence is incomplete. Direct-apply only safe memory or bounded skill updates. Record approval-gated or unsupported reflection output with recordSelfFeedbackIntent, and record non-actionable thoughts with recordReflectionIdea.',
+ systemRole: createAgentSignalSelfIterationToolSystemRole(mode),
type: 'builtin',
};
};
export const selfIterationToolManifest = createToolManifest('review');
-const SELF_ITERATION_SYSTEM_ROLE = [
- 'You are the Agent Signal self-iteration agent.',
- 'Inspect the bounded nightly review context and use the provided self-iteration tools to read evidence or apply safe write operations.',
- 'Evidence ids and proposal keys are different namespaces: read topic/message/tool_call/agent_document evidence with getEvidenceDigest; read proposals with readSelfReviewProposal only when using proposalActivity.active[].proposalKey or keys returned from listSelfReviewProposals.',
- 'Never claim that a write happened unless a write tool result confirms it.',
- 'Use writeMemory for explicit durable user preferences such as response style, summary structure, or verification-reporting preferences. Do not turn those preference memories into skills or proposals.',
- 'Use createSkillIfAbsent only when evidence describes a reusable workflow and you can provide a non-empty skill name and full bodyMarkdown.',
- 'When review evidence supports an approval-gated change, call createSelfReviewProposal in this run; do not offer to draft it later.',
- 'For createSelfReviewProposal actions, use actionType exactly create_skill, refine_skill, consolidate_skill, or record_idea. For refine_skill include target.skillDocumentId and operation { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }. For consolidate_skill include operation { domain: "skill", operation: "consolidate", input: { canonicalSkillDocumentId, sourceSkillIds, bodyMarkdown } }. Prefer recordSelfReviewIdea instead of proposal actions when the output is only a thought or question.',
- 'Stop after the useful self-iteration work is complete and summarize the confirmed outcome.',
-].join('\n');
-
const TOOL_NAME_SEPARATOR = '____';
const SELF_ITERATION_TOOL_ERROR_MESSAGE = 'Self-iteration tool call failed.';
const FORCE_FINISH_EXTRA_STEPS = 4;
@@ -463,79 +450,15 @@ const getIterationWindow = (input: ExecuteSelfIterationInput): IterationWindow =
timezone: input.window?.timezone,
});
-const createNightlyReviewPromptXml = (
- input: ExecuteSelfIterationInput,
- window: IterationWindow,
-) => {
- return toXml(
- u('root', [
- x(
- 'self_iteration_review',
- {
- agent_id: input.agentId,
- review_window_end: window.end,
- review_window_start: window.start,
- source_id: input.sourceId,
- user_id: input.userId,
- },
- x(
- 'review_objective',
- 'Inspect this nightly review context and create a self-review proposal when the evidence supports an approval-gated change. Do not finish with only text when a proposal is required.',
- ),
- x(
- 'review_policy_markdown',
- // Keep this as a rule table, not a precomputed proposal payload. The model still has
- // to decide and call the write tool, so local E2E proves the self-review path instead
- // of only proving that a hard-coded proposal candidate was copied into the tool call.
- [
- 'Use these deterministic self-review signal rules before deciding to finish without tools.',
- '',
- '| Signal kind | Required decision | Tool call | Notes |',
- '| --- | --- | --- | --- |',
- '| `skill_document_with_tool_failure` | Approval-gated skill refinement proposal | `createSelfReviewProposal` with one `refine_skill` action | Use the matching `managedSkills[].documentId` or `documentActivity.skillBucket[].agentDocumentId` as `target.skillDocumentId`; include `operation: { domain: "skill", operation: "refine", input: { skillDocumentId, bodyMarkdown } }`; cite topic/message/agent_document evidence refs. |',
- '| `repeated_tool_failure` involving `replaceSkillContentCAS` | Do not retry the write directly during nightly review | `createSelfReviewProposal` when the failed args contain a corrected skill body or a clear skill target | Prefer the failed tool args as the proposed body; call `getEvidenceDigest` first if the body or target is not visible in context. |',
- '| `skill_documents_maybe_overlap` | Consolidation candidate | `createSelfReviewProposal` with `consolidate_skill` only when there is a canonical skill and explicit source skills | Otherwise record no proposal for this signal alone. |',
- '',
- 'If a rule says `createSelfReviewProposal`, do not stop with only explanatory text. If required fields are missing, use read tools once to gather them; only skip when evidence remains insufficient after reading.',
- ].join('\n'),
- ),
- x('review_window', `Review window: ${window.start} to ${window.end}`),
- x('nightly_review_context_json', JSON.stringify(input.context)),
- ),
- ]),
- );
-};
-
-const createRuntimePrompt = (input: ExecuteSelfIterationInput) => {
- const window = getIterationWindow(input);
- const mode = getIterationMode(input);
-
- if (mode === 'review') {
- // TODO:
- // Rework this compatibility branch with the user before committing. The review prompt should
- // eventually share the self-iteration wording, but the current seeded local E2E proved that a
- // naive wording change can drop the Daily Brief proposal path.
- // NOTICE:
- // Keep the original nightly review prompt labels for the review mode.
- // Root cause summary: changing this to the generic self-iteration wording made the local E2E
- // review source complete without producing the expected Daily Brief proposal.
- // Source/context: `devtools/agent-signal/self-iteration-e2e/run-local-e2e.ts` requires one
- // review brief and one approval-gated proposal for the seeded nightly review data.
- // Removal condition: nightly self-review prompt/eval coverage proves the generic prompt still
- // produces equivalent proposal behavior.
- return createNightlyReviewPromptXml(input, window);
- }
-
- return [
- `Agent id: ${input.agentId}`,
- `User id: ${input.userId}`,
- `Source id: ${input.sourceId}`,
- `Mode: ${mode}`,
- `Evidence window: ${window.start} to ${window.end}`,
- 'Self-iteration context JSON:',
- JSON.stringify(input.context),
- ].join('\n');
-};
+const createRuntimePrompt = (input: ExecuteSelfIterationInput) =>
+ createAgentSignalSelfIterationPrompt({
+ agentId: input.agentId,
+ context: input.context,
+ mode: getIterationMode(input),
+ sourceId: input.sourceId,
+ userId: input.userId,
+ window: getIterationWindow(input),
+ });
const toNullableString = (value: unknown) =>
typeof value === 'string' && value.trim().length > 0 ? value : undefined;
@@ -1025,7 +948,7 @@ const createInitialState = ({
const createdAt = new Date().toISOString();
const operationId = `agent-signal-self-iteration:${input.sourceId}`;
const messages: ChatStreamPayload['messages'] = [
- { content: SELF_ITERATION_SYSTEM_ROLE, role: 'system' },
+ { content: createAgentSignalSelfIterationSystemRole(), role: 'system' },
{ content: createRuntimePrompt(input), role: 'user' },
];
diff --git a/src/server/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts
index 700c0b4080a..ac25598f9dd 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/brief.test.ts
@@ -5,6 +5,7 @@ import { BriefModel } from '@/database/models/brief';
import { ActionStatus, ApplyMode, ReviewRunStatus, Risk, Scope } from '../../types';
import { createBriefSelfReviewService, createServerSelfReviewBriefWriter } from '../brief';
+import type { SelfReviewBriefTextTranslator } from '../briefText';
afterEach(() => {
vi.restoreAllMocks();
@@ -27,6 +28,30 @@ const getSelfReviewProposal = (
brief: ReturnType<ReturnType<typeof createBriefSelfReviewService>['projectNightlyReviewBrief']>,
) => getNightlySelfReview(brief)?.selfReviewProposal;
+const zhCNBriefText: Record<string, string> = {
+ 'brief.agentSignal.selfReview.applied.heading': '已更新',
+ 'brief.agentSignal.selfReview.applied.summary': '已应用 {{count}} 条夜间回顾更新。',
+ 'brief.agentSignal.selfReview.applied.summary_plural': '已应用 {{count}} 条夜间回顾更新。',
+ 'brief.agentSignal.selfReview.applied.title': '夜间回顾已更新资源',
+ 'brief.agentSignal.selfReview.error.heading': '问题',
+ 'brief.agentSignal.selfReview.error.summary': '部分夜间回顾内容未能完成。',
+ 'brief.agentSignal.selfReview.error.title': '夜间回顾遇到了问题',
+ 'brief.agentSignal.selfReview.ideas.summary': '已保存夜间回顾记录,供后续查看。',
+ 'brief.agentSignal.selfReview.ideas.title': '夜间回顾记录',
+ 'brief.agentSignal.selfReview.proposal.heading': '建议',
+ 'brief.agentSignal.selfReview.proposal.summary': '有 {{count}} 条夜间回顾建议需要你确认。',
+ 'brief.agentSignal.selfReview.proposal.summary_plural': '有 {{count}} 条夜间回顾建议需要你确认。',
+ 'brief.agentSignal.selfReview.proposal.title': '有夜间回顾建议需要确认',
+};
+
+const createTranslator =
+ (resources: Record<string, string>): SelfReviewBriefTextTranslator =>
+ (key, options = {}) =>
+ Object.entries(options).reduce(
+ (content, [name, value]) => content.replace(`{{${name}}}`, value),
+ resources[key] ?? key,
+ );
+
describe('briefSelfReviewService', () => {
/**
* @example
@@ -177,11 +202,46 @@ describe('briefSelfReviewService', () => {
type: 'decision',
});
expect(brief?.priority).toBe('normal');
- expect(brief?.summary).toContain('1 self-review proposal need review.');
- expect(brief?.summary).toContain('**Proposal**');
+ expect(brief?.summary).toContain('1 dream suggestion needs your review.');
+ expect(brief?.summary).toContain('**Suggestion**');
expect(brief?.summary).toContain('- Review skill consolidation proposal.');
});
+ /**
+ * @example
+ * Nightly proposal briefs use server-translated shell text before persistence.
+ */
+ it('projects proposal results to Chinese decision briefs', () => {
+ const service = createBriefSelfReviewService();
+
+ const brief = service.projectNightlyReviewBrief({
+ agentId: 'agent-1',
+ localDate: '2026-05-09',
+ result: {
+ actions: [
+ {
+ idempotencyKey: 'source:proposal_only:skill:merge',
+ receiptId: 'receipt-2',
+ status: ActionStatus.Proposed,
+ summary: '检查技能合并建议。',
+ },
+ ],
+ status: ReviewRunStatus.Completed,
+ },
+ reviewWindowEnd: '2026-05-09T20:00:00.000Z',
+ reviewWindowStart: '2026-05-09T18:00:00.000Z',
+ t: createTranslator(zhCNBriefText),
+ timezone: 'Asia/Shanghai',
+ userId: 'user-1',
+ });
+
+ expect(brief?.title).toBe('有夜间回顾建议需要确认');
+ expect(brief?.summary).toBe(
+ '有 1 条夜间回顾建议需要你确认。\n\n**建议**\n- 检查技能合并建议。',
+ );
+ expect(brief?.type).toBe('decision');
+ });
+
/**
* @example
* Proposal briefs retain the frozen action payload needed for later approval.
@@ -333,7 +393,7 @@ describe('briefSelfReviewService', () => {
});
expect(getNightlySelfReview(projected)?.actionCounts.proposed).toBe(1);
- expect(projected?.summary).toContain('1 self-review proposal need review.');
+ expect(projected?.summary).toContain('1 dream suggestion needs your review.');
expect(projected?.summary).not.toContain('No self-iteration change is needed.');
expect(getSelfReviewProposal(projected)?.actions).toHaveLength(1);
expect(getSelfReviewProposal(projected)?.actions[0]).toMatchObject({
@@ -443,8 +503,8 @@ describe('briefSelfReviewService', () => {
id: 'brief-1',
metadata: {},
priority: 'info',
- summary: '1 self-iteration update applied.',
- title: 'Agent self-review updated resources',
+ summary: '1 dream update was applied.',
+ title: 'Dream updated resources',
trigger: 'agent-signal:nightly-review',
type: 'insight',
userId: 'user-1',
diff --git a/src/server/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts
new file mode 100644
index 00000000000..9e96859114c
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/briefText.test.ts
@@ -0,0 +1,92 @@
+// @vitest-environment node
+import { describe, expect, it } from 'vitest';
+
+import { createSelfReviewBriefText, type SelfReviewBriefTextTranslator } from '../briefText';
+
+const zhCN: Record<string, string> = {
+ 'brief.agentSignal.selfReview.applied.heading': '已更新',
+ 'brief.agentSignal.selfReview.applied.summary': '已应用 {{count}} 条夜间回顾更新。',
+ 'brief.agentSignal.selfReview.applied.summary_plural': '已应用 {{count}} 条夜间回顾更新。',
+ 'brief.agentSignal.selfReview.applied.title': '夜间回顾已更新资源',
+ 'brief.agentSignal.selfReview.error.heading': '问题',
+ 'brief.agentSignal.selfReview.error.summary': '部分夜间回顾内容未能完成。',
+ 'brief.agentSignal.selfReview.error.title': '夜间回顾遇到了问题',
+ 'brief.agentSignal.selfReview.ideas.summary': '已保存夜间回顾记录,供后续查看。',
+ 'brief.agentSignal.selfReview.ideas.title': '夜间回顾记录',
+ 'brief.agentSignal.selfReview.proposal.heading': '建议',
+ 'brief.agentSignal.selfReview.proposal.summary': '有 {{count}} 条夜间回顾建议需要你确认。',
+ 'brief.agentSignal.selfReview.proposal.summary_plural': '有 {{count}} 条夜间回顾建议需要你确认。',
+ 'brief.agentSignal.selfReview.proposal.title': '有夜间回顾建议需要确认',
+};
+
+const createTranslator =
+ (resources: Record<string, string>): SelfReviewBriefTextTranslator =>
+ (key, options = {}) =>
+ Object.entries(options).reduce(
+ (content, [name, value]) => content.replace(`{{${name}}}`, value),
+ resources[key] ?? key,
+ );
+
+describe('agent signal self-review brief text', () => {
+ /**
+ * @example
+ * Proposal outcomes produce default English decision text with action details.
+ */
+ it('renders default English proposal text with proposal details', () => {
+ expect(
+ createSelfReviewBriefText({
+ actionCounts: { applied: 0, failed: 0, proposed: 2, skipped: 1 },
+ actionSummaries: {
+ applied: [],
+ failed: [],
+ proposed: ['Review skill consolidation proposal.', 'Review PR checklist refinement.'],
+ },
+ outcome: 'proposal',
+ }),
+ ).toEqual({
+ priority: 'normal',
+ summary:
+ '2 dream suggestions need your review.\n\n**Suggestion**\n- Review skill consolidation proposal.\n- Review PR checklist refinement.',
+ title: 'Dream suggestion needs review',
+ type: 'decision',
+ });
+ });
+
+ /**
+ * @example
+ * Persisted Brief shell text uses the supplied server translator.
+ */
+ it('renders proposal text through the supplied translator', () => {
+ expect(
+ createSelfReviewBriefText({
+ actionCounts: { applied: 0, failed: 0, proposed: 1, skipped: 0 },
+ actionSummaries: { applied: [], failed: [], proposed: ['检查技能合并建议。'] },
+ outcome: 'proposal',
+ t: createTranslator(zhCN),
+ }),
+ ).toEqual({
+ priority: 'normal',
+ summary: '有 1 条夜间回顾建议需要你确认。\n\n**建议**\n- 检查技能合并建议。',
+ title: '有夜间回顾建议需要确认',
+ type: 'decision',
+ });
+ });
+
+ /**
+ * @example
+ * Without a translator the helper falls back to default English locale resources.
+ */
+ it('falls back to default English resources', () => {
+ expect(
+ createSelfReviewBriefText({
+ actionCounts: { applied: 1, failed: 0, proposed: 0, skipped: 0 },
+ actionSummaries: {
+ applied: ['Saved concise PR summary preference.'],
+ failed: [],
+ proposed: [],
+ },
+ outcome: 'applied',
+ }).title,
+ ).toBe('Dream updated resources');
+ });
+});
diff --git a/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
index 31c3a43b4bc..56fa7488c4f 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/handler.test.ts
@@ -119,6 +119,19 @@ const reviewAgentResult = {
stepCount: 1,
} satisfies AgentRunResult;
+const zhCNBriefText = {
+ 'brief.agentSignal.selfReview.proposal.heading': '建议',
+ 'brief.agentSignal.selfReview.proposal.summary': '有 {{count}} 条夜间回顾建议需要你确认。',
+ 'brief.agentSignal.selfReview.proposal.summary_plural': '有 {{count}} 条夜间回顾建议需要你确认。',
+ 'brief.agentSignal.selfReview.proposal.title': '有夜间回顾建议需要确认',
+};
+
+const t = (key: string, options: Record<string, string> = {}) =>
+ Object.entries(options).reduce(
+ (content, [name, value]) => content.replace(`{{${name}}}`, value),
+ zhCNBriefText[key as keyof typeof zhCNBriefText] ?? key,
+ );
+
const createDependencies = (
overrides: Partial<CreateNightlyReviewSourceHandlerDependencies> = {},
): CreateNightlyReviewSourceHandlerDependencies => ({
@@ -227,6 +240,7 @@ describe('nightly review source handler', () => {
],
} satisfies SelfReviewProposalPlan,
})),
+ resolveBriefTextTranslator: vi.fn(async () => t),
writeDailyBrief: vi.fn(async () => {
calls.push('brief');
@@ -274,6 +288,8 @@ describe('nightly review source handler', () => {
}),
}),
}),
+ summary: expect.stringContaining('有 1 条夜间回顾建议需要你确认。'),
+ title: '有夜间回顾建议需要确认',
trigger: 'agent-signal:nightly-review',
type: 'decision',
}),
@@ -353,7 +369,7 @@ describe('nightly review source handler', () => {
}),
}),
}),
- title: 'Agent self-review updated resources',
+ title: 'Dream updated resources',
trigger: 'agent-signal:nightly-review',
type: 'insight',
}),
diff --git a/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts b/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
index bf71b540c32..a083ea91aaf 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/__test__/server.test.ts
@@ -19,6 +19,27 @@ const mocks = vi.hoisted(() => ({
executeSelfIteration: vi.fn(),
skillReadTargetSnapshot: vi.fn(),
skillReplaceSkillIndex: vi.fn(),
+ translation: vi.fn(async () => ({
+ locale: 'zh-CN',
+ t: (key: string, options: Record<string, string> = {}) => {
+ const resources: Record<string, string> = {
+ 'brief.agentSignal.selfReview.proposal.heading': '建议',
+ 'brief.agentSignal.selfReview.proposal.summary': '有 {{count}} 条助理建议需要你确认。',
+ 'brief.agentSignal.selfReview.proposal.summary_plural':
+ '有 {{count}} 条助理建议需要你确认。',
+ 'brief.agentSignal.selfReview.proposal.title': '有助理建议需要确认',
+ };
+
+ return Object.entries(options).reduce(
+ (content, [name, value]) => content.replace(`{{${name}}}`, value),
+ resources[key] ?? key,
+ );
+ },
+ })),
+ userGetInfoForAIGeneration: vi.fn(async () => ({
+ responseLanguage: 'zh-CN',
+ userName: 'User',
+ })),
}));
vi.mock('@/server/modules/ModelRuntime', () => ({
@@ -54,6 +75,16 @@ vi.mock('@/database/models/brief', () => ({
},
}));
+vi.mock('@/database/models/user', () => ({
+ UserModel: {
+ getInfoForAIGeneration: mocks.userGetInfoForAIGeneration,
+ },
+}));
+
+vi.mock('@/server/translation', () => ({
+ translation: mocks.translation,
+}));
+
vi.mock('@/server/services/skillManagement', async (importOriginal) => ({
...(await importOriginal<typeof SkillManagementModule>()),
SkillManagementDocumentService: class {
@@ -596,6 +627,8 @@ describe('createServerSelfReviewPolicyOptions', () => {
},
},
},
+ summary: expect.stringContaining('有 1 条助理建议需要你确认。'),
+ title: '有助理建议需要确认',
type: 'decision',
});
expect(result.execution.actions).toEqual([]);
diff --git a/src/server/services/agentSignal/services/selfIteration/review/brief.ts b/src/server/services/agentSignal/services/selfIteration/review/brief.ts
index 6a94c80895f..449703befeb 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/brief.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/brief.ts
@@ -8,6 +8,11 @@ import type { LobeChatDatabase } from '@/database/type';
import type { EvidenceRef, RunResult } from '../types';
import { ActionStatus, ReviewRunStatus } from '../types';
+import {
+ createSelfReviewBriefText,
+ type SelfReviewBriefTextActionSummaries,
+ type SelfReviewBriefTextTranslator,
+} from './briefText';
import type {
SelfReviewIdea,
SelfReviewProposalMetadata,
@@ -260,6 +265,8 @@ export interface ProjectNightlyReviewBriefInput {
reviewWindowEnd: string;
/** Review window start ISO timestamp. */
reviewWindowStart: string;
+ /** Locale-aware translator for persisted Daily Brief text. */
+ t?: SelfReviewBriefTextTranslator;
/** IANA timezone used for nightly scheduling. */
timezone: string;
/** User that owns the agent and brief. */
@@ -353,37 +360,30 @@ const getOutcome = (
return;
};
-const formatActionSummaries = (
+const collectActionSummaries = (
result: RunResult,
- status: ActionStatus,
- heading: string,
plan?: SelfReviewProposalPlan,
-) => {
+): SelfReviewBriefTextActionSummaries => {
const planActionByIdempotencyKey = getPlanActionByIdempotencyKey(plan);
- const summaries = result.actions
- .filter((action) => {
- if (status !== ActionStatus.Proposed) return action.status === status;
-
- return isVisibleProposalResult(action, planActionByIdempotencyKey);
- })
- .map((action) => action.summary?.trim() ?? '')
- .filter(Boolean);
+ const summaries: SelfReviewBriefTextActionSummaries = {
+ applied: [],
+ failed: [],
+ proposed: [],
+ };
- if (summaries.length === 0) return;
+ for (const action of result.actions) {
+ const summary = action.summary?.trim();
- return [`**${heading}**`, ...summaries.map((summary) => `- ${summary}`)].join('\n');
-};
+ if (!summary) continue;
-const createDetailedSummary = (
- summary: string,
- result: RunResult,
- status: ActionStatus,
- heading: string,
- plan?: SelfReviewProposalPlan,
-) => {
- const details = formatActionSummaries(result, status, heading, plan);
+ if (action.status === ActionStatus.Applied) summaries.applied.push(summary);
+ if (action.status === ActionStatus.Failed) summaries.failed.push(summary);
+ if (isVisibleProposalResult(action, planActionByIdempotencyKey)) {
+ summaries.proposed.push(summary);
+ }
+ }
- return details ? `${summary}\n\n${details}` : summary;
+ return summaries;
};
const collectBriefArtifactDocuments = ({
@@ -429,53 +429,6 @@ const createBriefArtifacts = (input: {
return documents.length > 0 ? { documents } : undefined;
};
-const createBriefCopy = (
- outcome: SelfReviewBriefMetadata['outcome'],
- counts: SelfReviewBriefActionCounts,
- result: RunResult,
- plan?: SelfReviewProposalPlan,
-) => {
- if (outcome === 'proposal') {
- const summary = `${counts.proposed} self-review proposal${counts.proposed === 1 ? '' : 's'} need review.`;
-
- return {
- priority: 'normal' as const,
- summary: createDetailedSummary(summary, result, ActionStatus.Proposed, 'Proposal', plan),
- title: 'Agent self-review proposal',
- type: 'decision' as const,
- };
- }
-
- if (outcome === 'error') {
- const summary = 'Agent self-review could not finish all self-review actions.';
-
- return {
- priority: 'normal' as const,
- summary: createDetailedSummary(summary, result, ActionStatus.Failed, 'Failure'),
- title: 'Agent self-review needs attention',
- type: 'error' as const,
- };
- }
-
- if (outcome === 'ideas') {
- return {
- priority: 'info' as const,
- summary: 'Agent self-review saved shared ideas for future review.',
- title: 'Agent self-review ideas',
- type: 'insight' as const,
- };
- }
-
- const summary = `${counts.applied} self-iteration update${counts.applied === 1 ? '' : 's'} applied.`;
-
- return {
- priority: 'info' as const,
- summary: createDetailedSummary(summary, result, ActionStatus.Applied, 'Updated'),
- title: 'Agent self-review updated resources',
- type: 'insight' as const,
- };
-};
-
/**
* Creates projection helpers for Agent Signal self-review Daily Briefs.
*
@@ -552,7 +505,12 @@ export const createBriefSelfReviewService = () => ({
if (!outcome) return;
- const copy = createBriefCopy(outcome, actionCounts, input.result, input.plan);
+ const copy = createSelfReviewBriefText({
+ actionCounts,
+ actionSummaries: collectActionSummaries(input.result, input.plan),
+ outcome,
+ t: input.t,
+ });
const proposal =
outcome === 'proposal' && input.plan
? buildSelfReviewProposalFromPlan({
diff --git a/src/server/services/agentSignal/services/selfIteration/review/briefText.ts b/src/server/services/agentSignal/services/selfIteration/review/briefText.ts
new file mode 100644
index 00000000000..e7880fbeea9
--- /dev/null
+++ b/src/server/services/agentSignal/services/selfIteration/review/briefText.ts
@@ -0,0 +1,170 @@
+import home from '@/locales/default/home';
+
+/**
+ * Counts of self-review actions grouped by execution status.
+ */
+export interface SelfReviewBriefTextActionCounts {
+ /** Number of actions applied to durable resources. */
+ applied: number;
+ /** Number of actions that failed after planning or execution. */
+ failed: number;
+ /** Number of actions left as user-visible proposals. */
+ proposed: number;
+ /** Number of actions skipped by planner or executor policy. */
+ skipped: number;
+}
+
+/**
+ * User-visible action summaries grouped by brief outcome.
+ */
+export interface SelfReviewBriefTextActionSummaries {
+ /** User-visible summaries for actions applied to durable resources. */
+ applied: string[];
+ /** User-visible summaries for actions that failed. */
+ failed: string[];
+ /** User-visible summaries for non-noop proposal actions. */
+ proposed: string[];
+}
+
+/**
+ * Translation function used to render persisted Agent Signal Daily Brief text.
+ */
+export interface SelfReviewBriefTextTranslator {
+ /** Resolves a `home` namespace key with simple string interpolation. */
+ (key: string, options?: Record<string, string>): string;
+}
+
+/**
+ * Input context for deterministic nightly self-review Daily Brief copy.
+ */
+export interface SelfReviewBriefTextInput {
+ /** Per-status action counts computed by the Agent Signal projection service. */
+ actionCounts: SelfReviewBriefTextActionCounts;
+ /** User-visible action summaries grouped by outcome status. */
+ actionSummaries: SelfReviewBriefTextActionSummaries;
+ /** Coarse outcome selected by the projection service. */
+ outcome: 'applied' | 'error' | 'ideas' | 'proposal';
+ /** Locale-aware translator for the `home` namespace. Defaults to English resources. */
+ t?: SelfReviewBriefTextTranslator;
+}
+
+/**
+ * Localized Daily Brief shell text produced by nightly self-review.
+ */
+export interface SelfReviewBriefText {
+ /** Brief priority expected by the Daily Brief model. */
+ priority: 'info' | 'normal';
+ /** User-visible summary, optionally including action bullets. */
+ summary: string;
+ /** User-visible Daily Brief title. */
+ title: string;
+ /** Daily Brief display type. */
+ type: 'decision' | 'error' | 'insight';
+}
+
+const defaultTranslate: SelfReviewBriefTextTranslator = (key, options = {}) => {
+ const template = home[key as keyof typeof home] ?? key;
+
+ return Object.entries(options).reduce(
+ (content, [name, value]) => content.replace(`{{${name}}}`, value),
+ template,
+ );
+};
+
+const actionCountKey = (input: {
+ count: number;
+ pluralKey: string;
+ singularKey: string;
+ t: SelfReviewBriefTextTranslator;
+}) =>
+ input.t(input.count === 1 ? input.singularKey : input.pluralKey, {
+ count: String(input.count),
+ });
+
+const withDetails = (summary: string, heading: string, details: string[] = []) => {
+ const cleanDetails = details.map((detail) => detail.trim()).filter(Boolean);
+
+ return cleanDetails.length > 0
+ ? `${summary}\n\n**${heading}**\n${cleanDetails.map((detail) => `- ${detail}`).join('\n')}`
+ : summary;
+};
+
+/**
+ * Builds localized Daily Brief shell text for Agent Signal nightly self-review.
+ *
+ * Use when:
+ * - Nightly self-review projection needs title, summary, type, and priority
+ * - The output is user-visible and must be translated before persistence
+ *
+ * Expects:
+ * - `outcome` and `actionCounts` have already been computed by service policy
+ * - Action summaries are already user-safe strings from execution/proposal results
+ *
+ * Returns:
+ * - Deterministic brief text without making a model call
+ */
+export const createSelfReviewBriefText = (input: SelfReviewBriefTextInput): SelfReviewBriefText => {
+ const t = input.t ?? defaultTranslate;
+
+ if (input.outcome === 'proposal') {
+ const summary = actionCountKey({
+ count: input.actionCounts.proposed,
+ pluralKey: 'brief.agentSignal.selfReview.proposal.summary_plural',
+ singularKey: 'brief.agentSignal.selfReview.proposal.summary',
+ t,
+ });
+
+ return {
+ priority: 'normal',
+ summary: withDetails(
+ summary,
+ t('brief.agentSignal.selfReview.proposal.heading'),
+ input.actionSummaries.proposed,
+ ),
+ title: t('brief.agentSignal.selfReview.proposal.title'),
+ type: 'decision',
+ };
+ }
+
+ if (input.outcome === 'error') {
+ const summary = t('brief.agentSignal.selfReview.error.summary');
+
+ return {
+ priority: 'normal',
+ summary: withDetails(
+ summary,
+ t('brief.agentSignal.selfReview.error.heading'),
+ input.actionSummaries.failed,
+ ),
+ title: t('brief.agentSignal.selfReview.error.title'),
+ type: 'error',
+ };
+ }
+
+ if (input.outcome === 'ideas') {
+ return {
+ priority: 'info',
+ summary: t('brief.agentSignal.selfReview.ideas.summary'),
+ title: t('brief.agentSignal.selfReview.ideas.title'),
+ type: 'insight',
+ };
+ }
+
+ const summary = actionCountKey({
+ count: input.actionCounts.applied,
+ pluralKey: 'brief.agentSignal.selfReview.applied.summary_plural',
+ singularKey: 'brief.agentSignal.selfReview.applied.summary',
+ t,
+ });
+
+ return {
+ priority: 'info',
+ summary: withDetails(
+ summary,
+ t('brief.agentSignal.selfReview.applied.heading'),
+ input.actionSummaries.applied,
+ ),
+ title: t('brief.agentSignal.selfReview.applied.title'),
+ type: 'insight',
+ };
+};
diff --git a/src/server/services/agentSignal/services/selfIteration/review/handler.ts b/src/server/services/agentSignal/services/selfIteration/review/handler.ts
index b22f6c6d74a..99cf774c14d 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/handler.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/handler.ts
@@ -11,6 +11,7 @@ import type { EvidenceRef, Plan, RunResult } from '../types';
import { buildNightlyReviewSourceId, ReviewRunStatus } from '../types';
import type { SelfReviewBriefProjection } from './brief';
import { createBriefSelfReviewService, getNightlySelfReviewBriefMetadata } from './brief';
+import type { SelfReviewBriefTextTranslator } from './briefText';
import type { CollectNightlyReviewContextInput, NightlyReviewContext } from './collect';
import type { SelfReviewProposalPlan } from './proposal';
@@ -86,6 +87,10 @@ export interface CreateNightlyReviewSourceHandlerDependencies {
canRunReview: (input: NightlyReviewSourceGuardInput) => Promise<boolean>;
/** Collects bounded digest context without mutating shared resources. */
collectContext: (input: CollectNightlyReviewContextInput) => Promise<NightlyReviewContext>;
+ /** Resolves a home-namespace translator for persisted nightly Brief text. */
+ resolveBriefTextTranslator?: (input: {
+ userId: string;
+ }) => Promise<SelfReviewBriefTextTranslator | undefined>;
/** Runs the bounded self-iteration agent and returns execution plus the frozen projection plan. */
runSelfReviewAgent: (input: {
context: NightlyReviewContext;
@@ -503,6 +508,7 @@ export const createNightlyReviewSourceHandler = (
await writeNightlyReceipts(deps, receipts);
+ const t = await deps.resolveBriefTextTranslator?.({ userId: payload.userId });
const brief = createBriefSelfReviewService().projectNightlyReviewBrief({
agentId: payload.agentId,
evidenceRefs: collectPlanEvidenceRefs(plan),
@@ -512,6 +518,7 @@ export const createNightlyReviewSourceHandler = (
result: executionWithReceipts,
reviewWindowEnd: payload.reviewWindowEnd,
reviewWindowStart: payload.reviewWindowStart,
+ t,
timezone: payload.timezone,
userId: payload.userId,
});
diff --git a/src/server/services/agentSignal/services/selfIteration/review/server.ts b/src/server/services/agentSignal/services/selfIteration/review/server.ts
index a0c5551ebf1..7bcc6ae86bb 100644
--- a/src/server/services/agentSignal/services/selfIteration/review/server.ts
+++ b/src/server/services/agentSignal/services/selfIteration/review/server.ts
@@ -5,6 +5,7 @@ import { tracer } from '@lobechat/observability-otel/modules/agent-signal';
import { AgentSignalNightlyReviewModel } from '@/database/models/agentSignal/nightlyReview';
import { AgentSignalReviewContextModel } from '@/database/models/agentSignal/reviewContext';
import { BriefModel } from '@/database/models/brief';
+import { UserModel } from '@/database/models/user';
import type { BriefItem } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';
@@ -13,6 +14,7 @@ import { isAgentSignalEnabledForUser } from '@/server/services/agentSignal/featu
import { runMemoryActionAgent } from '@/server/services/agentSignal/policies/analyzeIntent/actions/userMemory';
import { redisSourceEventStore } from '@/server/services/agentSignal/store/adapters/redis/sourceEventStore';
import { SkillManagementDocumentService } from '@/server/services/skillManagement';
+import { translation } from '@/server/translation';
import { persistAgentSignalReceipts } from '../../receiptService';
import { createAgentRunner, executeSelfIteration } from '../execute';
@@ -35,6 +37,7 @@ import { createMemoryService, createToolSet } from '../tools/shared';
import type { EvidenceRef } from '../types';
import { Risk, Scope } from '../types';
import { createBriefSelfReviewService, createServerSelfReviewBriefWriter } from './brief';
+import type { SelfReviewBriefTextTranslator } from './briefText';
import type {
FeedbackActivityDigest,
NightlyReviewManagedSkillSummary,
@@ -543,6 +546,7 @@ const updateSelfReviewProposalBrief = async ({
export const createServerToolSet = ({
agentId,
briefModel,
+ briefTextTranslator,
context,
db,
localDate,
@@ -553,6 +557,7 @@ export const createServerToolSet = ({
}: {
agentId: string;
briefModel: BriefModel;
+ briefTextTranslator?: SelfReviewBriefTextTranslator;
context: Parameters<
CreateNightlyReviewSourceHandlerDependencies['runSelfReviewAgent']
>[0]['context'];
@@ -632,6 +637,7 @@ export const createServerToolSet = ({
result: projection.execution,
reviewWindowEnd: context.reviewWindowEnd,
reviewWindowStart: context.reviewWindowStart,
+ t: briefTextTranslator,
timezone: 'UTC',
userId,
});
@@ -1058,6 +1064,12 @@ export const createServerSelfReviewPolicyOptions = ({
},
});
const briefWriter = createServerSelfReviewBriefWriter(db, userId);
+ const resolveBriefTextTranslator = async ({ userId }: { userId: string }) => {
+ const userInfo = await UserModel.getInfoForAIGeneration(db, userId);
+ const { t } = await translation('home', userInfo.responseLanguage ?? 'en-US');
+
+ return t;
+ };
return {
acquireReviewGuard: (input) =>
@@ -1083,6 +1095,7 @@ export const createServerSelfReviewPolicyOptions = ({
},
collectContext: (input) => collector.collect(input),
runSelfReviewAgent: async ({ context, localDate, sourceId, userId: runnerUserId }) => {
+ const briefTextTranslator = await resolveBriefTextTranslator({ userId: runnerUserId });
const modelRuntime = await initModelRuntimeFromDB(
db,
runnerUserId,
@@ -1091,6 +1104,7 @@ export const createServerSelfReviewPolicyOptions = ({
const toolSet = createServerToolSet({
agentId: context.agentId,
briefModel,
+ briefTextTranslator,
context,
db,
localDate: localDate ?? context.reviewWindowEnd.slice(0, 10),
@@ -1140,6 +1154,7 @@ export const createServerSelfReviewPolicyOptions = ({
userId: runnerUserId,
});
},
+ resolveBriefTextTranslator,
writeDailyBrief: (brief) => briefWriter.writeDailyBrief(brief),
writeReceipts: (receipts) => persistAgentSignalReceipts(receipts),
};