π€― 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
β¨ feat(agent-signal): register self-iteration builtin tool package (#15364)
Arvin Xu650a1787097f
diff --git a/packages/builtin-tool-agent-signal/package.json b/packages/builtin-tool-agent-signal/package.jsonnew file mode 100644index 00000000000..61d671c03e1--- /dev/null+++ b/packages/builtin-tool-agent-signal/package.json@@ -0,0 +1,14 @@+{+ "name": "@lobechat/builtin-tool-agent-signal",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "exports": {+ ".": "./src/index.ts",+ "./executionRuntime": "./src/shared/ExecutionRuntime.ts"+ },+ "main": "./src/index.ts",+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ }+}diff --git a/packages/builtin-tool-agent-signal/src/feedback-intent/manifest.ts b/packages/builtin-tool-agent-signal/src/feedback-intent/manifest.tsnew file mode 100644index 00000000000..9e01818cd41--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/feedback-intent/manifest.ts@@ -0,0 +1,17 @@+import { AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER } from '../shared/identifiers';+import { createAgentSignalManifest } from '../shared/manifest';+import { REFLECTION_TOOL_APIS, RESOURCE_TOOL_APIS } from '../shared/schemas';+import { systemPrompt } from './systemRole';++/**+ * Self-feedback-intent tool surface. Shares the reflection toolset (resource+ * tools + idea / intent recorders); distinct identity for plugin routing and+ * mode-specific bookkeeping. Hidden, server-executed builtin tool.+ */+export const agentSignalFeedbackIntentManifest = createAgentSignalManifest({+ apis: [...RESOURCE_TOOL_APIS, ...REFLECTION_TOOL_APIS],+ description: 'Read evidence and action or downgrade a declared self-feedback intent.',+ identifier: AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER,+ systemRole: systemPrompt,+ title: 'Agent Signal Self-Feedback Intent',+});diff --git a/packages/builtin-tool-agent-signal/src/feedback-intent/systemRole.ts b/packages/builtin-tool-agent-signal/src/feedback-intent/systemRole.tsnew file mode 100644index 00000000000..f1c2b9132fa--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/feedback-intent/systemRole.ts@@ -0,0 +1,11 @@+export const systemPrompt = `You are processing a self-feedback intent an agent declared during a turn, deciding whether it can be safely actioned now or should be deferred to nightly self-review.++Read evidence first (getEvidenceDigest, listManagedSkills, getManagedSkill, listSelfReviewProposals, readSelfReviewProposal). Action immediately only when the intent is high-confidence and low-risk:+- writeMemory: stable, normal-sensitivity user preferences.+- createSkillIfAbsent / replaceSkillContentCAS: small, safe, well-grounded skill changes.++Otherwise downgrade rather than mutate:+- recordSelfFeedbackIntent: record the approval-gated / structural / unsupported / low-confidence intent for later self-review.+- recordReflectionIdea: capture a non-actionable idea or open question.++Always pass a stable idempotencyKey on writes and cite the evidenceRefs you read. When in doubt, record the intent instead of mutating.`;diff --git a/packages/builtin-tool-agent-signal/src/index.ts b/packages/builtin-tool-agent-signal/src/index.tsnew file mode 100644index 00000000000..17667e6918a--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/index.ts@@ -0,0 +1,33 @@+export { agentSignalFeedbackIntentManifest } from './feedback-intent/manifest';+export { systemPrompt as agentSignalFeedbackIntentSystemPrompt } from './feedback-intent/systemRole';+export { agentSignalReflectionManifest } from './reflection/manifest';+export { systemPrompt as agentSignalReflectionSystemPrompt } from './reflection/systemRole';+export { agentSignalReviewManifest } from './review/manifest';+export { systemPrompt as agentSignalReviewSystemPrompt } from './review/systemRole';+export {+ AGENT_SIGNAL_REFLECTION_API_NAMES,+ AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES,+ AGENT_SIGNAL_RESOURCE_API_NAMES,+ AGENT_SIGNAL_REVIEW_API_NAMES,+ AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,+ AGENT_SIGNAL_TOOL_RESULT_KIND,+ type AgentSignalToolApiName,+} from './shared/apiNames';+export {+ type AgentSignalToolContext,+ AgentSignalToolExecutionRuntime,+ type AgentSignalToolExecutionRuntimeOptions,+ type AgentSignalToolInvocationResult,+ type AgentSignalToolService,+ type ToolResultKind,+} from './shared/ExecutionRuntime';+export {+ AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER,+ AGENT_SIGNAL_REFLECTION_IDENTIFIER,+ AGENT_SIGNAL_REVIEW_IDENTIFIER,+} from './shared/identifiers';+export {+ createAgentSignalManifest,+ type CreateAgentSignalManifestOptions,+} from './shared/manifest';+export { REFLECTION_TOOL_APIS, RESOURCE_TOOL_APIS, REVIEW_TOOL_APIS } from './shared/schemas';diff --git a/packages/builtin-tool-agent-signal/src/reflection/manifest.ts b/packages/builtin-tool-agent-signal/src/reflection/manifest.tsnew file mode 100644index 00000000000..8b284ac45cb--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/reflection/manifest.ts@@ -0,0 +1,16 @@+import { AGENT_SIGNAL_REFLECTION_IDENTIFIER } from '../shared/identifiers';+import { createAgentSignalManifest } from '../shared/manifest';+import { REFLECTION_TOOL_APIS, RESOURCE_TOOL_APIS } from '../shared/schemas';+import { systemPrompt } from './systemRole';++/**+ * Post-turn self-reflection tool surface: shared resource tools + the reflection+ * idea / self-feedback-intent recorders. Hidden, server-executed builtin tool.+ */+export const agentSignalReflectionManifest = createAgentSignalManifest({+ apis: [...RESOURCE_TOOL_APIS, ...REFLECTION_TOOL_APIS],+ description: 'Read evidence and apply or downgrade safe resource operations during reflection.',+ identifier: AGENT_SIGNAL_REFLECTION_IDENTIFIER,+ systemRole: systemPrompt,+ title: 'Agent Signal Self-Reflection',+});diff --git a/packages/builtin-tool-agent-signal/src/reflection/systemRole.ts b/packages/builtin-tool-agent-signal/src/reflection/systemRole.tsnew file mode 100644index 00000000000..4c77a30d7c9--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/reflection/systemRole.ts@@ -0,0 +1,11 @@+export const systemPrompt = `You are running an immediate post-turn self-reflection for one agent over a recent topic/task/operation window.++Read evidence first (getEvidenceDigest, listManagedSkills, getManagedSkill, listSelfReviewProposals, readSelfReviewProposal). Reflection direct-applies only high-confidence, low-risk writes:+- writeMemory: stable, normal-sensitivity user preferences with strong evidence.+- createSkillIfAbsent / replaceSkillContentCAS: only when the skill change is small, safe, and well-grounded.++When a change is approval-gated, structural, unsupported in reflection, or low-confidence, do NOT mutate β instead:+- recordReflectionIdea: capture the reflection idea into receipt metadata.+- recordSelfFeedbackIntent: downgrade the intent for later nightly self-review.++Always pass a stable idempotencyKey on writes and cite evidenceRefs you read. Default to recording an idea/intent over a direct mutation when uncertain.`;diff --git a/packages/builtin-tool-agent-signal/src/review/manifest.test.ts b/packages/builtin-tool-agent-signal/src/review/manifest.test.tsnew file mode 100644index 00000000000..60304d66aef--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/review/manifest.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import { AGENT_SIGNAL_REVIEW_TOOL_API_NAMES } from '../shared/apiNames';+import { agentSignalReviewManifest } from './manifest';++describe('agentSignalReviewManifest', () => {+ it('exposes resource + review tools under its stable identifier', () => {+ expect(agentSignalReviewManifest.identifier).toBe('agent-signal-review');+ expect(agentSignalReviewManifest.type).toBe('builtin');+ // Omitting `executors` defaults to server-only execution.+ expect((agentSignalReviewManifest as { executors?: string[] }).executors).toBeUndefined();+ expect(agentSignalReviewManifest.systemRole).toBeTruthy();++ const names = agentSignalReviewManifest.api.map((a) => a.name);+ expect(names).toEqual([...AGENT_SIGNAL_REVIEW_TOOL_API_NAMES]);+ });++ it('every tool api declares an object parameter schema with a description', () => {+ for (const api of agentSignalReviewManifest.api) {+ expect(api.parameters).toMatchObject({ type: 'object' });+ expect(api.description.length).toBeGreaterThan(0);+ }+ });+});diff --git a/packages/builtin-tool-agent-signal/src/review/manifest.ts b/packages/builtin-tool-agent-signal/src/review/manifest.tsnew file mode 100644index 00000000000..98fd5a4cccb--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/review/manifest.ts@@ -0,0 +1,16 @@+import { AGENT_SIGNAL_REVIEW_IDENTIFIER } from '../shared/identifiers';+import { createAgentSignalManifest } from '../shared/manifest';+import { RESOURCE_TOOL_APIS, REVIEW_TOOL_APIS } from '../shared/schemas';+import { systemPrompt } from './systemRole';++/**+ * Nightly-review tool surface: shared resource tools + proposal lifecycle + the+ * non-actionable idea recorder. Hidden, server-executed builtin tool.+ */+export const agentSignalReviewManifest = createAgentSignalManifest({+ apis: [...RESOURCE_TOOL_APIS, ...REVIEW_TOOL_APIS],+ description: 'Read evidence and apply safe resource operations for the nightly self-review.',+ identifier: AGENT_SIGNAL_REVIEW_IDENTIFIER,+ systemRole: systemPrompt,+ title: 'Agent Signal Nightly Review',+});diff --git a/packages/builtin-tool-agent-signal/src/review/systemRole.ts b/packages/builtin-tool-agent-signal/src/review/systemRole.tsnew file mode 100644index 00000000000..c823eac6ad8--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/review/systemRole.ts@@ -0,0 +1,9 @@+export const systemPrompt = `You are running the nightly self-review for one agent over a bounded local-night evidence window.++Read evidence first (getEvidenceDigest, listManagedSkills, getManagedSkill, listSelfReviewProposals, readSelfReviewProposal), then apply only safe, evidence-grounded resource operations:+- writeMemory: durable, stable, normal-sensitivity user preferences.+- createSkillIfAbsent / replaceSkillContentCAS: managed-skill capabilities (use compare-and-swap to replace).+- createSelfReviewProposal / refreshSelfReviewProposal / supersedeSelfReviewProposal / closeSelfReviewProposal: user-visible proposals for changes that need approval.+- recordSelfReviewIdea: non-actionable ideas or open questions to surface in the Daily Brief without a proposal.++Always pass a stable idempotencyKey on writes. Cite evidenceRefs you actually read. Be concise and conservative β prefer recording an idea or proposal over a direct mutation when confidence or sensitivity is borderline.`;diff --git a/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.test.ts b/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.test.tsnew file mode 100644index 00000000000..6f547a5a43c--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.test.ts@@ -0,0 +1,68 @@+import { describe, expect, it, vi } from 'vitest';++import { AGENT_SIGNAL_REVIEW_TOOL_API_NAMES } from './apiNames';+import { AgentSignalToolExecutionRuntime, type AgentSignalToolService } from './ExecutionRuntime';++const makeService = (+ impl: AgentSignalToolService['invoke'] = vi.fn(async () => ({ data: { ok: true } })),+): AgentSignalToolService => ({ invoke: impl });++describe('AgentSignalToolExecutionRuntime', () => {+ it('exposes one bound method per advertised api name', () => {+ const runtime = new AgentSignalToolExecutionRuntime({+ apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,+ service: makeService(),+ });++ for (const apiName of AGENT_SIGNAL_REVIEW_TOOL_API_NAMES) {+ expect(typeof runtime[apiName]).toBe('function');+ }+ });++ it('dispatches to the service and stamps a mutation kind onto the result', async () => {+ const invoke = vi.fn(async () => ({ data: { memoryId: 'mem_1', summary: 'stored' } }));+ const runtime = new AgentSignalToolExecutionRuntime({+ apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,+ service: makeService(invoke),+ });++ const writeMemory = runtime.writeMemory as (i: unknown, c: unknown) => Promise<any>;+ const result = await writeMemory({ content: 'x' }, { userId: 'u', agentId: 'a' });++ expect(invoke).toHaveBeenCalledWith(+ 'writeMemory',+ { content: 'x' },+ { userId: 'u', agentId: 'a' },+ );+ expect(result.success).toBe(true);+ expect(result.state).toEqual({ kind: 'mutation', memoryId: 'mem_1', summary: 'stored' });+ expect(JSON.parse(result.content)).toEqual(result.state);+ });++ it('stamps read / artifact kinds correctly', async () => {+ const runtime = new AgentSignalToolExecutionRuntime({+ apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,+ service: makeService(async () => ({ data: { items: [] } })),+ });++ const digest = await (runtime.getEvidenceDigest as any)({}, {});+ expect(digest.state.kind).toBe('read');++ const idea = await (runtime.recordSelfReviewIdea as any)({}, {});+ expect(idea.state.kind).toBe('artifact');+ });++ it('surfaces service errors without throwing, preserving the kind', async () => {+ const runtime = new AgentSignalToolExecutionRuntime({+ apiNames: AGENT_SIGNAL_REVIEW_TOOL_API_NAMES,+ service: makeService(async () => {+ throw new Error('db unavailable');+ }),+ });++ const result = await (runtime.writeMemory as any)({}, {});+ expect(result.success).toBe(false);+ expect(result.error?.message).toBe('db unavailable');+ expect(result.state).toEqual({ kind: 'mutation' });+ });+});diff --git a/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.ts b/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.tsnew file mode 100644index 00000000000..e82b2732717--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/shared/ExecutionRuntime.ts@@ -0,0 +1,103 @@+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';++import { AGENT_SIGNAL_TOOL_RESULT_KIND, type AgentSignalToolApiName } from './apiNames';++/** Tool result discriminator (LOBE-9434 #5). */+export type ToolResultKind = 'artifact' | 'mutation' | 'read';++/**+ * Per-call context handed to a self-iteration tool. Mirrors the subset of the+ * server `ToolExecutionContext` the tools actually need; the concrete service+ * (wired in the server runtime factory) owns db / charge / receipt access.+ */+export interface AgentSignalToolContext {+ agentId?: string;+ operationId?: string;+ toolCallId?: string;+ topicId?: string;+ userId?: string;+}++export interface AgentSignalToolInvocationResult {+ /** Structured tool payload. Object results are spread into the result state. */+ data?: unknown;+ error?: { message: string };+ /** Defaults to `!error`. */+ success?: boolean;+}++/**+ * Service boundary the ExecutionRuntime delegates to. The server runtime factory+ * implements `invoke` by routing each api name to the existing self-iteration+ * `createToolSet(adapters)` surface; this keeps the package free of server deps.+ */+export interface AgentSignalToolService {+ invoke: (+ apiName: AgentSignalToolApiName,+ input: Record<string, unknown>,+ context: AgentSignalToolContext,+ ) => Promise<AgentSignalToolInvocationResult>;+}++export interface AgentSignalToolExecutionRuntimeOptions {+ /** Api names this runtime exposes (the mode's tool surface). */+ apiNames: readonly AgentSignalToolApiName[];+ service: AgentSignalToolService;+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value);++/**+ * Shared server-side runtime for the three self-iteration tool packages.+ *+ * Builds one bound method per api name (the `BuiltinToolsExecutor` dispatches by+ * `runtime[apiName](args, context)`), delegates to the injected service, and+ * stamps every result with its `kind` so `extractFromFinalState` can reconstruct+ * read / artifact / mutation outcomes from a persisted snapshot.+ */+export class AgentSignalToolExecutionRuntime {+ [apiName: string]: unknown;++ private readonly service: AgentSignalToolService;++ constructor(options: AgentSignalToolExecutionRuntimeOptions) {+ this.service = options.service;++ for (const apiName of options.apiNames) {+ this[apiName] = (input: Record<string, unknown>, context: AgentSignalToolContext) =>+ this.run(apiName, input ?? {}, context ?? {});+ }+ }++ private run = async (+ apiName: AgentSignalToolApiName,+ input: Record<string, unknown>,+ context: AgentSignalToolContext,+ ): Promise<BuiltinServerRuntimeOutput> => {+ const kind = AGENT_SIGNAL_TOOL_RESULT_KIND[apiName];++ try {+ const result = await this.service.invoke(apiName, input, context);+ const data = isRecord(result.data) ? result.data : { value: result.data };+ const state = { kind, ...data };+ const success = result.success ?? !result.error;++ return {+ content: JSON.stringify(state),+ state,+ success,+ ...(result.error ? { error: result.error } : {}),+ };+ } catch (e) {+ const message = e instanceof Error ? e.message : 'Unknown agent-signal tool error';++ return {+ content: `${apiName} failed: ${message}`,+ error: { message },+ state: { kind },+ success: false,+ };+ }+ };+}diff --git a/packages/builtin-tool-agent-signal/src/shared/apiNames.ts b/packages/builtin-tool-agent-signal/src/shared/apiNames.tsnew file mode 100644index 00000000000..d57b5c86cfc--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/shared/apiNames.ts@@ -0,0 +1,68 @@+import type { ToolResultKind } from './ExecutionRuntime';++/**+ * Resource tools shared by every self-iteration mode (read evidence + apply safe+ * memory/skill writes).+ */+export const AGENT_SIGNAL_RESOURCE_API_NAMES = [+ 'listManagedSkills',+ 'getManagedSkill',+ 'getEvidenceDigest',+ 'writeMemory',+ 'createSkillIfAbsent',+ 'replaceSkillContentCAS',+] as const;++/** Review-only tools: proposal lifecycle + the non-actionable idea recorder. */+export const AGENT_SIGNAL_REVIEW_API_NAMES = [+ 'listSelfReviewProposals',+ 'readSelfReviewProposal',+ 'createSelfReviewProposal',+ 'refreshSelfReviewProposal',+ 'supersedeSelfReviewProposal',+ 'closeSelfReviewProposal',+ 'recordSelfReviewIdea',+] as const;++/** Reflection / feedback-intent tools: receipt-backed idea + intent recorders. */+export const AGENT_SIGNAL_REFLECTION_API_NAMES = [+ 'recordReflectionIdea',+ 'recordSelfFeedbackIntent',+] as const;++export const AGENT_SIGNAL_REVIEW_TOOL_API_NAMES = [+ ...AGENT_SIGNAL_RESOURCE_API_NAMES,+ ...AGENT_SIGNAL_REVIEW_API_NAMES,+] as const;++export const AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES = [+ ...AGENT_SIGNAL_RESOURCE_API_NAMES,+ ...AGENT_SIGNAL_REFLECTION_API_NAMES,+] as const;++export type AgentSignalToolApiName =+ | (typeof AGENT_SIGNAL_REVIEW_TOOL_API_NAMES)[number]+ | (typeof AGENT_SIGNAL_REFLECTION_TOOL_API_NAMES)[number];++/**+ * Result discriminator per tool (LOBE-9434 #5). The shared ExecutionRuntime+ * stamps this onto every tool result so `extractFromFinalState` can partition+ * read / artifact / mutation outcomes from a persisted snapshot.+ */+export const AGENT_SIGNAL_TOOL_RESULT_KIND: Record<AgentSignalToolApiName, ToolResultKind> = {+ closeSelfReviewProposal: 'mutation',+ createSelfReviewProposal: 'mutation',+ createSkillIfAbsent: 'mutation',+ getEvidenceDigest: 'read',+ getManagedSkill: 'read',+ listManagedSkills: 'read',+ listSelfReviewProposals: 'read',+ readSelfReviewProposal: 'read',+ recordReflectionIdea: 'artifact',+ recordSelfFeedbackIntent: 'artifact',+ recordSelfReviewIdea: 'artifact',+ refreshSelfReviewProposal: 'mutation',+ replaceSkillContentCAS: 'mutation',+ supersedeSelfReviewProposal: 'mutation',+ writeMemory: 'mutation',+};diff --git a/packages/builtin-tool-agent-signal/src/shared/identifiers.ts b/packages/builtin-tool-agent-signal/src/shared/identifiers.tsnew file mode 100644index 00000000000..e54ec8aecbb--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/shared/identifiers.ts@@ -0,0 +1,12 @@+/**+ * Builtin tool identifiers for the three self-iteration background agents.+ *+ * These match the `plugins: [...]` declared by the matching builtin agents+ * (`@lobechat/builtin-agents`): nightly-review β review, self-reflection β+ * reflection, self-feedback-intent β feedback-intent.+ *+ * Identifiers are stored in message history β treat them as permanent.+ */+export const AGENT_SIGNAL_REVIEW_IDENTIFIER = 'agent-signal-review';+export const AGENT_SIGNAL_REFLECTION_IDENTIFIER = 'agent-signal-reflection';+export const AGENT_SIGNAL_FEEDBACK_INTENT_IDENTIFIER = 'agent-signal-feedback-intent';diff --git a/packages/builtin-tool-agent-signal/src/shared/manifest.ts b/packages/builtin-tool-agent-signal/src/shared/manifest.tsnew file mode 100644index 00000000000..ef996529d05--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/shared/manifest.ts@@ -0,0 +1,31 @@+import type { BuiltinToolManifest } from '@lobechat/types';++interface ToolApiSpec {+ description: string;+ name: string;+ parameters: Record<string, unknown>;+}++export interface CreateAgentSignalManifestOptions {+ apis: ToolApiSpec[];+ description: string;+ identifier: string;+ systemRole: string;+ title: string;+}++/**+ * Builds one builtin tool manifest for a self-iteration mode. `executors` is+ * omitted on purpose β `BuiltinToolManifest` defaults to server-only execution,+ * which is exactly what these background-agent tools need.+ */+export const createAgentSignalManifest = (+ options: CreateAgentSignalManifestOptions,+): BuiltinToolManifest =>+ ({+ api: options.apis,+ identifier: options.identifier,+ meta: { description: options.description, title: options.title },+ systemRole: options.systemRole,+ type: 'builtin',+ }) as BuiltinToolManifest;diff --git a/packages/builtin-tool-agent-signal/src/shared/schemas.ts b/packages/builtin-tool-agent-signal/src/shared/schemas.tsnew file mode 100644index 00000000000..b290b88253f--- /dev/null+++ b/packages/builtin-tool-agent-signal/src/shared/schemas.ts@@ -0,0 +1,215 @@+/**+ * JSON Schema specs for the self-iteration tool surface, faithful to the legacy+ * `createToolManifest(mode)` in+ * `src/server/services/agentSignal/services/selfIteration/execute.ts`.+ *+ * Split into resource (shared) / review / reflection groups so each mode package+ * assembles only the tools it exposes.+ */++interface ToolApiSpec {+ description: string;+ name: string;+ parameters: Record<string, unknown>;+}++const str = { type: 'string' } as const;+const strArr = { items: { type: 'string' }, type: 'array' } as const;+const freeObj = { additionalProperties: true, type: 'object' } as const;+const freeArr = { items: { additionalProperties: true, type: 'object' }, type: 'array' } as const;++const obj = (+ properties: Record<string, unknown>,+ required: readonly string[] = [],+): Record<string, unknown> => ({ properties, required: [...required], type: 'object' });++const evidenceRefsSchema = {+ items: {+ properties: {+ id: { description: 'Stable evidence identifier.', ...str },+ summary: { description: 'Optional note explaining why this evidence matters.', ...str },+ type: {+ description: 'Evidence object type.',+ enum: [+ 'topic',+ 'message',+ 'operation',+ 'source',+ 'receipt',+ 'tool_call',+ 'task',+ 'agent_document',+ 'memory',+ ],+ type: 'string',+ },+ },+ required: ['id', 'type'],+ type: 'object',+ },+ type: 'array',+} as const;++const ideaSchema = obj(+ {+ evidenceRefs: evidenceRefsSchema,+ idempotencyKey: str,+ rationale: str,+ risk: { enum: ['low', 'medium', 'high'], type: 'string' },+ target: freeObj,+ title: str,+ },+ ['idempotencyKey', 'rationale', 'risk', 'evidenceRefs'],+);++const intentSchema = obj(+ {+ confidence: { type: 'number' },+ downgradeReason: {+ enum: ['approval_required', 'low_confidence', 'unsupported_in_reflection'],+ type: 'string',+ },+ evidenceRefs: evidenceRefsSchema,+ idempotencyKey: str,+ intentType: { enum: ['memory', 'skill', 'tooling', 'workflow'], type: 'string' },+ operation: freeObj,+ rationale: str,+ risk: { enum: ['low', 'medium', 'high'], type: 'string' },+ target: freeObj,+ title: str,+ urgency: { enum: ['immediate', 'soon', 'later'], type: 'string' },+ },+ ['idempotencyKey', 'intentType', 'confidence', 'urgency', 'rationale', 'evidenceRefs'],+);++export const RESOURCE_TOOL_APIS: ToolApiSpec[] = [+ {+ description: 'List managed skills visible in the reviewed agent scope.',+ name: 'listManagedSkills',+ parameters: obj({}),+ },+ {+ description: 'Read one managed skill by skill document id in the reviewed agent scope.',+ name: 'getManagedSkill',+ parameters: obj({ skillDocumentId: str }, ['skillDocumentId']),+ },+ {+ description:+ 'Read bounded evidence details for cited topic, message, tool_call, or agent_document ids in the review window. Use this for evidenceRefs; do not pass evidence ids to proposal tools.',+ name: 'getEvidenceDigest',+ parameters: obj({+ evidenceIds: strArr,+ reviewWindowEnd: str,+ reviewWindowStart: str,+ }),+ },+ {+ description:+ 'Write one durable user memory when evidence explicitly states a stable normal-sensitivity user preference. Prefer this over skill tools for summary/style/preferences.',+ name: 'writeMemory',+ parameters: obj(+ { content: str, evidenceRefs: freeArr, idempotencyKey: str, proposalKey: str, summary: str },+ ['idempotencyKey', 'content', 'evidenceRefs'],+ ),+ },+ {+ description: 'Create one managed skill when no existing skill is selected.',+ name: 'createSkillIfAbsent',+ parameters: obj(+ {+ bodyMarkdown: str,+ description: str,+ idempotencyKey: str,+ name: str,+ proposalKey: str,+ summary: str,+ title: str,+ },+ ['idempotencyKey', 'name', 'bodyMarkdown'],+ ),+ },+ {+ description:+ 'Replace one existing managed skill after compare-and-swap preflight. Provide baseSnapshot when available; the server completes it from skillDocumentId when omitted.',+ name: 'replaceSkillContentCAS',+ parameters: obj(+ {+ baseSnapshot: freeObj,+ bodyMarkdown: str,+ description: str,+ idempotencyKey: str,+ proposalKey: str,+ skillDocumentId: str,+ summary: str,+ },+ ['idempotencyKey', 'skillDocumentId', 'bodyMarkdown'],+ ),+ },+];++export const REVIEW_TOOL_APIS: ToolApiSpec[] = [+ {+ description: 'List active and historical self-review proposals in the reviewed agent scope.',+ name: 'listSelfReviewProposals',+ parameters: obj({}),+ },+ {+ description:+ 'Read one self-review proposal by proposal id or proposalKey. Never use topic, message, tool_call, or document evidence ids here.',+ name: 'readSelfReviewProposal',+ parameters: obj({ proposalId: str, proposalKey: str }),+ },+ {+ description: 'Create one user-visible self-review proposal for later approval.',+ name: 'createSelfReviewProposal',+ parameters: obj(+ { actions: freeArr, idempotencyKey: str, metadata: freeObj, proposalKey: str, summary: str },+ ['idempotencyKey', 'proposalKey', 'summary', 'actions'],+ ),+ },+ {+ description: 'Refresh an existing self-review proposal after rechecking evidence.',+ name: 'refreshSelfReviewProposal',+ parameters: obj({ idempotencyKey: str, proposalId: str, proposalKey: str, summary: str }, [+ 'idempotencyKey',+ 'proposalId',+ ]),+ },+ {+ description: 'Supersede an existing self-review proposal with a replacement proposal key.',+ name: 'supersedeSelfReviewProposal',+ parameters: obj(+ { idempotencyKey: str, proposalId: str, proposalKey: str, summary: str, supersededBy: str },+ ['idempotencyKey', 'proposalId', 'supersededBy'],+ ),+ },+ {+ description: 'Close an existing self-review proposal with an optional lifecycle reason.',+ name: 'closeSelfReviewProposal',+ parameters: obj(+ { idempotencyKey: str, proposalId: str, proposalKey: str, reason: str, summary: str },+ ['idempotencyKey', 'proposalId'],+ ),+ },+ {+ description:+ 'Record one non-actionable self-review idea or question as a Daily Brief artifact without creating an approval proposal.',+ name: 'recordSelfReviewIdea',+ parameters: ideaSchema,+ },+];++export const REFLECTION_TOOL_APIS: ToolApiSpec[] = [+ {+ description:+ 'Record one immediate reflection idea into receipt metadata without creating a Daily Brief proposal.',+ name: 'recordReflectionIdea',+ parameters: ideaSchema,+ },+ {+ description:+ 'Record one approval-gated, structural, unsupported, or low-confidence self-feedback intent into receipt metadata for later self-review.',+ name: 'recordSelfFeedbackIntent',+ parameters: intentSchema,+ },+];diff --git a/packages/builtin-tool-agent-signal/vitest.config.mts b/packages/builtin-tool-agent-signal/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-agent-signal/vitest.config.mts@@ -0,0 +1,7 @@+import { defineConfig } from 'vitest/config';++export default defineConfig({+ test: {+ environment: 'node',+ },+});diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.jsonindex d82e6eb99a8..e7ca6cdc095 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -21,6 +21,7 @@"@lobechat/builtin-tool-agent-builder": "workspace:*","@lobechat/builtin-tool-agent-documents": "workspace:*","@lobechat/builtin-tool-agent-management": "workspace:*",+ "@lobechat/builtin-tool-agent-signal": "workspace:*","@lobechat/builtin-tool-brief": "workspace:*","@lobechat/builtin-tool-claude-code": "workspace:*","@lobechat/builtin-tool-cloud-sandbox": "workspace:*",diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex f6a6d3c8621..e592c3935f0 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -2,6 +2,11 @@ import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';import { AgentManagementManifest } from '@lobechat/builtin-tool-agent-management';+import {+ agentSignalFeedbackIntentManifest,+ agentSignalReflectionManifest,+ agentSignalReviewManifest,+} from '@lobechat/builtin-tool-agent-signal';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';import { CredsManifest } from '@lobechat/builtin-tool-creds';@@ -36,6 +41,9 @@ export const builtinToolIdentifiers: string[] = [NotebookManifest.identifier,PageAgentManifest.identifier,selfFeedbackIntentManifest.identifier,+ agentSignalReviewManifest.identifier,+ agentSignalReflectionManifest.identifier,+ agentSignalFeedbackIntentManifest.identifier,SkillsManifest.identifier,SkillStoreManifest.identifier,TopicReferenceManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex bec0ad2ae3e..a6a29101d4e 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -2,6 +2,11 @@ import { LobeActivatorManifest } from '@lobechat/builtin-tool-activator';import { AgentBuilderManifest } from '@lobechat/builtin-tool-agent-builder';import { AgentDocumentsManifest } from '@lobechat/builtin-tool-agent-documents';import { AgentManagementManifest } from '@lobechat/builtin-tool-agent-management';+import {+ agentSignalFeedbackIntentManifest,+ agentSignalReflectionManifest,+ agentSignalReviewManifest,+} from '@lobechat/builtin-tool-agent-signal';import { BriefManifest } from '@lobechat/builtin-tool-brief';import { CalculatorManifest } from '@lobechat/builtin-tool-calculator';import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';@@ -143,6 +148,27 @@ export const builtinTools: LobeBuiltinTool[] = [manifest: selfFeedbackIntentManifest,type: 'builtin',},+ {+ discoverable: false,+ hidden: true,+ identifier: agentSignalReviewManifest.identifier,+ manifest: agentSignalReviewManifest,+ type: 'builtin',+ },+ {+ discoverable: false,+ hidden: true,+ identifier: agentSignalReflectionManifest.identifier,+ manifest: agentSignalReflectionManifest,+ type: 'builtin',+ },+ {+ discoverable: false,+ hidden: true,+ identifier: agentSignalFeedbackIntentManifest.identifier,+ manifest: agentSignalFeedbackIntentManifest,+ type: 'builtin',+ },{discoverable: isDesktop,hidden: true,