π€― 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
π fix(lobe-agent): cap vent per run and reject repeated or empty reports (#20052)
Arvin Xu9130079402c6
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.tsindex 68ed90e497b..d85f67ad4e5 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/lobeAgent.ts@@ -29,9 +29,15 @@ import { parseDataUri } from '@lobechat/utils/uriParser';import { MessageModel } from '@/database/models/message';import { toolsEnv } from '@/envs/tools';+import { getAgentRuntimeRedisClient } from '@/server/modules/AgentRuntime/redis';import { initModelRuntimeFromDB } from '@/server/modules/ModelRuntime';import { FileService } from '@/server/services/file';-import { createVentService, formatVentResultContent } from '@/server/services/vent';+import {+ createRedisVentLedger,+ createVentService,+ formatVentResultContent,+ type VentRuntimeService,+} from '@/server/services/vent';import type { ToolExecutionContext } from '../types';import { normalizeMultimodalImageItems } from './lobeAgentImage';@@ -40,9 +46,20 @@ import type { ServerRuntimeRegistration } from './types';// The durable record of a vent is the persisted vent tool-call message itself.// This shared service only validates input, assigns a stable id, and enforces-// per-scope rate limits. Module-scoped so the rate-limit state survives across-// per-request runtime instances.-const sharedVentService = createVentService({ nextToolCallId: () => nanoid() });+// the per-run cap. The cap lives in Redis because consecutive steps of one run+// may execute on different instances; created lazily so importing this module+// does not open a connection.+let sharedVentService: VentRuntimeService | undefined;+const getVentService = () => {+ if (!sharedVentService) {+ const redis = getAgentRuntimeRedisClient();+ sharedVentService = createVentService({+ ledger: redis ? createRedisVentLedger(redis) : undefined,+ nextToolCallId: () => nanoid(),+ });+ }+ return sharedVentService;+};interface LobeAgentRuntimeContext {agentId?: string | null;@@ -299,7 +316,7 @@ class LobeAgentExecutionRuntime {}try {- const result = await sharedVentService.recordVent({+ const result = await getVentService().recordVent({agentId: this.agentId,input: params,topicId: this.topicId,diff --git a/apps/server/src/services/vent/__tests__/vent.test.ts b/apps/server/src/services/vent/__tests__/vent.test.tsindex c15712c86ee..d309bc2ef80 100644--- a/apps/server/src/services/vent/__tests__/vent.test.ts+++ b/apps/server/src/services/vent/__tests__/vent.test.ts@@ -1,6 +1,28 @@-import { describe, expect, it } from 'vitest';--import { createVentService, formatVentResultContent, type VentRecordInput } from '../index';+import { describe, expect, it, vi } from 'vitest';++import {+ createRedisVentLedger,+ createVentService,+ formatVentResultContent,+ type VentRecordInput,+ type VentRedisClient,+} from '../index';++/** Runs the admit script's semantics against an in-memory set store. */+const createFakeRedis = (): VentRedisClient & { sets: Map<string, Set<string>> } => {+ const sets = new Map<string, Set<string>>();+ return {+ eval: async (_script, _numKeys, key, member, limit) => {+ const set = sets.get(String(key)) ?? new Set<string>();+ if (set.has(String(member))) return 'duplicate';+ if (set.size >= Number(limit)) return 'rate_limited';+ set.add(String(member));+ sets.set(String(key), set);+ return 'accepted';+ },+ sets,+ };+};const baseInput = (overrides: Partial<VentRecordInput> = {}): VentRecordInput => ({agentId: 'agent-1',@@ -52,7 +74,11 @@ describe('createVentService', () => {const input = baseInput({ operationId: 'op-1', toolCallId: 'tc-1' });const first = await service.recordVent(input);- const second = await service.recordVent({ ...input, toolCallId: 'tc-2' });+ const second = await service.recordVent({+ ...input,+ input: { ...input.input, summary: 'Another complaint.' },+ toolCallId: 'tc-2',+ });expect(first.recorded).toBe(true);expect(second).toEqual({ recorded: false, reason: 'rate_limited' });@@ -64,7 +90,11 @@ describe('createVentService', () => {const results = [];for (let i = 0; i < 4; i += 1) {- results.push(await service.recordVent(baseInput()));+ results.push(+ await service.recordVent(+ baseInput({ input: { ...baseInput().input, summary: `complaint ${i}` } }),+ ),+ );}expect(results.filter((r) => r.recorded)).toHaveLength(3);@@ -72,6 +102,90 @@ describe('createVentService', () => {});});+describe('vent ledger across instances', () => {+ // Consecutive steps of one server run can execute on different instances.+ // A per-instance count let several operations record more than one vent.+ it('holds the per-run cap when two instances share the Redis ledger', async () => {+ const redis = createFakeRedis();+ const instanceA = createVentService({+ ledger: createRedisVentLedger(redis),+ nextToolCallId: () => 'a',+ });+ const instanceB = createVentService({+ ledger: createRedisVentLedger(redis),+ nextToolCallId: () => 'b',+ });+ const input = baseInput({ operationId: 'op-1' });++ const first = await instanceA.recordVent(input);+ const second = await instanceB.recordVent({+ ...input,+ input: { ...input.input, summary: 'A different complaint.' },+ });+ const repeat = await instanceB.recordVent(input);++ expect(first.recorded).toBe(true);+ expect(second).toEqual({ recorded: false, reason: 'rate_limited' });+ expect(repeat).toEqual({ recorded: false, reason: 'duplicate' });+ expect([...redis.sets.keys()]).toEqual(['vent:ledger:user-1:agent-1:operation:op-1']);+ });++ it('falls back to the memory ledger when Redis fails', async () => {+ const service = createVentService({+ ledger: createRedisVentLedger({+ eval: async () => {+ throw new Error('down');+ },+ }),+ nextToolCallId: () => 'tool-1',+ });+ const input = baseInput({ operationId: 'op-1' });+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ expect((await service.recordVent(input)).recorded).toBe(true);+ expect(await service.recordVent(input)).toEqual({ recorded: false, reason: 'duplicate' });+ errorSpy.mockRestore();+ });++ it('keeps the cap when Redis fails after admitting the first vent', async () => {+ const redis = createFakeRedis();+ let redisDown = false;+ const service = createVentService({+ ledger: createRedisVentLedger({+ eval: (...args) => (redisDown ? Promise.reject(new Error('down')) : redis.eval(...args)),+ }),+ nextToolCallId: () => 'tool-1',+ });+ const input = baseInput({ operationId: 'op-1' });+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});++ expect((await service.recordVent(input)).recorded).toBe(true);+ redisDown = true;+ const second = await service.recordVent({+ ...input,+ input: { ...input.input, summary: 'A different complaint.' },+ });++ expect(second).toEqual({ recorded: false, reason: 'rate_limited' });+ errorSpy.mockRestore();+ });++ it('rejects an empty report before it reaches the ledger', async () => {+ const redis = createFakeRedis();+ const service = createVentService({+ ledger: createRedisVentLedger(redis),+ nextToolCallId: () => 'tool-1',+ });++ const result = await service.recordVent(+ baseInput({ input: { ...baseInput().input, details: '', summary: ' ' } }),+ );++ expect(result).toEqual({ recorded: false, reason: 'empty_content' });+ expect(redis.sets.size).toBe(0);+ });+});+describe('formatVentResultContent', () => {it('renders a readable confirmation instead of raw JSON when recorded', () => {const content = formatVentResultContent({@@ -83,14 +197,14 @@ describe('formatVentResultContent', () => {});expect(content).toBe(- 'Vent recorded (high missing_tool), id vent:user-1:agent-1:topic:topic-1:tool-1. The friction report has been filed for the platform team. No user-facing action is needed β continue your task.',+ 'Vent recorded (high missing_tool), id vent:user-1:agent-1:topic:topic-1:tool-1. The friction report has been filed for the platform team. It does not end your turn or change anything β continue your task, and do not vent again in this run.',);expect(() => JSON.parse(content)).toThrow();});it('explains each rejection reason in plain text', () => {expect(formatVentResultContent({ reason: 'rate_limited', recorded: false })).toContain(- 'vent limit for this scope',+ 'this run already filed its vent',);expect(formatVentResultContent({ reason: 'invalid_category', recorded: false })).toContain('Valid categories: missing_tool',diff --git a/apps/server/src/services/vent/index.ts b/apps/server/src/services/vent/index.tsindex 569f63cbed4..6d12ece1ebc 100644--- a/apps/server/src/services/vent/index.ts+++ b/apps/server/src/services/vent/index.ts@@ -1,10 +1,18 @@+import { createHash } from 'node:crypto';+import type {- VentCategory,+ VentLedger,VentParams,- VentSeverity,- VentState,+ VentRejectionReason,+} from '@lobechat/builtin-tool-lobe-agent';+import {+ createMemoryVentLedger,+ getVentFingerprint,+ getVentScope,+ validateVentParams,} from '@lobechat/builtin-tool-lobe-agent';-import { VENT_CATEGORIES, VENT_SEVERITIES } from '@lobechat/builtin-tool-lobe-agent';++export { formatVentResultContent } from '@lobechat/builtin-tool-lobe-agent';/** Input used by the vent service to record one report. */export interface VentRecordInput {@@ -22,7 +30,7 @@ export interface VentRecordInput {userId: string;}-export type VentRecordRejection = 'invalid_category' | 'invalid_severity' | 'rate_limited';+export type VentRecordRejection = VentRejectionReason;/** Result returned after one vent attempt. */export interface VentResult {@@ -41,113 +49,111 @@ export interface VentRuntimeService {/** Dependencies used by the pure vent recording service. */export interface VentServiceDependencies {+ /** Tracks admitted vents per scope. Defaults to an in-memory ledger. */+ ledger?: VentLedger;/** Creates a stable tool-call id when the caller did not provide one. */nextToolCallId: () => string;}-/** At most this many vents per operation scope; a topic-scoped fallback gets a looser cap. */-const VENT_LIMIT_PER_OPERATION = 1;-const VENT_LIMIT_PER_TOPIC = 3;+/** Minimal Redis surface the vent ledger needs (ioredis-compatible). */+export interface VentRedisClient {+ eval: (script: string, numKeys: number, ...args: (number | string)[]) => Promise<unknown>;+}-const validCategories = new Set<VentCategory>(VENT_CATEGORIES);-const validSeverities = new Set<VentSeverity>(VENT_SEVERITIES);+const VENT_LEDGER_TTL_SECONDS = 3 * 24 * 60 * 60;++// Check-and-add in one round trip so parallel tool calls of one step cannot+// both slip under the cap.+const ADMIT_SCRIPT = `+if redis.call('SISMEMBER', KEYS[1], ARGV[1]) == 1 then return 'duplicate' end+if redis.call('SCARD', KEYS[1]) >= tonumber(ARGV[2]) then return 'rate_limited' end+redis.call('SADD', KEYS[1], ARGV[1])+redis.call('EXPIRE', KEYS[1], ARGV[3])+return 'accepted'+`;++/**+ * Redis-backed ledger. Consecutive steps of one server run may execute on+ * different instances, so a per-process count cannot hold the per-run cap.+ * Falls back to an in-memory ledger when Redis errors, so a vent never fails+ * the tool call. Accepted admissions are mirrored into that fallback; a vent+ * admitted only by the fallback is not replayed into Redis once it recovers,+ * which can let at most one extra vent through a flapping Redis.+ */+export const createRedisVentLedger = (+ redis: VentRedisClient,+ fallback: VentLedger = createMemoryVentLedger(),+): VentLedger => ({+ admit: async (params) => {+ try {+ const result = await redis.eval(+ ADMIT_SCRIPT,+ 1,+ `vent:ledger:${params.scopeKey}`,+ createHash('sha256').update(params.fingerprint).digest('hex'),+ params.limit,+ VENT_LEDGER_TTL_SECONDS,+ );+ if (result === 'accepted' || result === 'duplicate' || result === 'rate_limited') {+ // Mirror admissions so a Redis outage later in the run still sees them.+ if (result === 'accepted') await fallback.admit(params);+ return result;+ }+ } catch (error) {+ console.error('[vent] Redis ledger failed, falling back to memory:', error);+ }-const getScope = (input: VentRecordInput) =>- input.operationId- ? ({ id: input.operationId, key: `operation:${input.operationId}`, type: 'operation' } as const)- : ({ id: input.topicId, key: `topic:${input.topicId}`, type: 'topic' } as const);+ return fallback.admit(params);+ },+});const buildVentId = (params: {agentId: string;- scopeId: string;- scopeType: string;+ scopeKey: string;toolCallId: string;userId: string;-}) =>- `vent:${params.userId}:${params.agentId}:${params.scopeType}:${params.scopeId}:${params.toolCallId}`;+}) => `vent:${params.userId}:${params.agentId}:${params.scopeKey}:${params.toolCallId}`;/**- * Creates a pure vent recording service.+ * Creates a vent recording service.** Use when:* - The LobeAgent server runtime needs a DI-friendly vent boundary- * - Tests need deterministic tool-call ids and rate-limit state+ * - Tests need deterministic tool-call ids and ledger state** Expects:* - The durable record is the persisted vent tool-call message itself- * - The service instance owns only in-memory fast-loop rate limiting+ * - The ledger owns the per-run cap and same-content dedupe** Returns:* - A service that accepts valid vents and never mutates user-facing resources*/export const createVentService = (deps: VentServiceDependencies): VentRuntimeService => {- const recordedCounts = new Map<string, number>();+ const ledger = deps.ledger ?? createMemoryVentLedger();return {recordVent: async (input): Promise<VentResult> => {- if (!validCategories.has(input.input.category)) {- return { recorded: false, reason: 'invalid_category' };- }-- if (!validSeverities.has(input.input.severity)) {- return { recorded: false, reason: 'invalid_severity' };- }-- const scope = getScope(input);- const limit = scope.type === 'operation' ? VENT_LIMIT_PER_OPERATION : VENT_LIMIT_PER_TOPIC;- const rateLimitKey = `${input.userId}:${input.agentId}:${scope.key}`;- const recordedCount = recordedCounts.get(rateLimitKey) ?? 0;-- if (recordedCount >= limit) {- return { recorded: false, reason: 'rate_limited' };- }-- const toolCallId = input.toolCallId ?? deps.nextToolCallId();- const ventId = buildVentId({- agentId: input.agentId,- scopeId: scope.id,- scopeType: scope.type,- toolCallId,- userId: input.userId,+ const invalid = validateVentParams(input.input);+ if (invalid) return { recorded: false, reason: invalid };++ const scope = getVentScope(input)!;+ const admission = await ledger.admit({+ fingerprint: getVentFingerprint(input.input),+ limit: scope.limit,+ scopeKey: `${input.userId}:${input.agentId}:${scope.key}`,});- recordedCounts.set(rateLimitKey, recordedCount + 1);-- return { recorded: true, ventId };+ if (admission !== 'accepted') return { recorded: false, reason: admission };++ return {+ recorded: true,+ ventId: buildVentId({+ agentId: input.agentId,+ scopeKey: scope.key,+ toolCallId: input.toolCallId ?? deps.nextToolCallId(),+ userId: input.userId,+ }),+ };},};};--/**- * Renders the tool-result text the calling LLM reads after a vent attempt.- *- * The persisted state stays structured; this string only needs to tell the- * model whether the report landed and that no user-facing follow-up is owed.- */-export const formatVentResultContent = (state: VentState): string => {- if (state.recorded) {- const label = [state.severity, state.category].filter(Boolean).join(' ');- return [- `Vent recorded${label ? ` (${label})` : ''}${state.ventId ? `, id ${state.ventId}` : ''}.`,- 'The friction report has been filed for the platform team. No user-facing action is needed β continue your task.',- ].join(' ');- }-- switch (state.reason) {- case 'rate_limited': {- return 'Vent not recorded: the vent limit for this scope is already used. Do not retry; continue your task.';- }- case 'invalid_category': {- return `Vent not recorded: unknown category. Valid categories: ${VENT_CATEGORIES.join(', ')}.`;- }- case 'invalid_severity': {- return `Vent not recorded: unknown severity. Valid severities: ${VENT_SEVERITIES.join(', ')}.`;- }- case 'missing_context': {- return 'Vent not recorded: agent or topic context is missing in this run. Continue your task.';- }- default: {- return 'Vent not recorded. Continue your task.';- }- }-};diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts b/packages/builtin-tool-lobe-agent/src/client/executor/index.tsindex 4f88d5ba4d8..cacf79f6d01 100644--- a/packages/builtin-tool-lobe-agent/src/client/executor/index.ts+++ b/packages/builtin-tool-lobe-agent/src/client/executor/index.ts@@ -35,9 +35,18 @@ import type {UpdatePlanParams,UpdateTodosParams,VentParams,+ VentRejectionReason,VentState,} from '../../types';-import { LobeAgentApiName, VENT_CATEGORIES, VENT_SEVERITIES } from '../../types';+import { LobeAgentApiName } from '../../types';+import {+ createMemoryVentLedger,+ formatVentResultContent,+ getVentFingerprint,+ getVentScope,+ validateVentParams,+ type VentLedger,+} from '../../vent';import { getTodosFromContext } from './planTodoHelper';import { resolveClientMediaPayloadItems } from './resolveMediaUris';@@ -164,6 +173,10 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {// becomes the tool result and this runtime is only the fallback executor.private interactionRuntime = new UserInteractionExecutionRuntime();+ // A client run executes in this tab, so an in-memory ledger sees every vent+ // of the run.+ private ventLedger: VentLedger = createMemoryVentLedger();+// ==================== Ask User Question ====================askUserQuestion = (params: AskUserQuestionArgs): Promise<BuiltinToolResult> =>@@ -190,42 +203,48 @@ class LobeAgentExecutor extends BaseExecutor<typeof LobeAgentApiName> {/*** Privately flag platform friction. The report's durable record is the- * persisted tool-call message itself; this just validates the input and- * surfaces a settled state for the inspector.+ * persisted tool-call message itself; this validates the input, admits at+ * most one distinct vent per run, and surfaces a settled state for the+ * inspector.*/vent = async (params: VentParams, ctx: BuiltinToolContext): Promise<BuiltinToolResult> => {- if (!VENT_CATEGORIES.includes(params?.category)) {- const message = 'vent requires a valid category.';+ const invalid = validateVentParams(params);+ if (invalid === 'invalid_category' || invalid === 'invalid_severity') {+ const state: VentState = { recorded: false, reason: invalid };+ const message = formatVentResultContent(state);return {content: message,error: { message, type: 'InvalidArguments' },- state: { recorded: false, reason: 'invalid_category' } satisfies VentState,+ state,success: false,};}- if (!VENT_SEVERITIES.includes(params?.severity)) {- const message = 'vent requires a valid severity.';- return {- content: message,- error: { message, type: 'InvalidArguments' },- state: { recorded: false, reason: 'invalid_severity' } satisfies VentState,- success: false,- };+ // `operationId` is the per-tool-call operation on the client; the run is+ // the root operation.+ const scope = getVentScope({+ operationId: ctx.rootOperationId ?? ctx.operationId,+ topicId: ctx.topicId,+ });+ let admission: VentRejectionReason | 'accepted' = invalid ?? 'accepted';+ if (!invalid && scope) {+ admission = await this.ventLedger.admit({+ fingerprint: getVentFingerprint(params),+ limit: scope.limit,+ scopeKey: scope.key,+ });}-- const ventId = ctx.toolCallId ? `vent:${ctx.toolCallId}` : null;-- return {- content: 'Flagged platform friction for the builders.',- state: {- category: params.category,- recorded: true,- severity: params.severity,- ventId,- } satisfies VentState,- success: true,+ const recorded = admission === 'accepted';++ const state: VentState = {+ category: params.category,+ reason: admission === 'accepted' ? null : admission,+ recorded,+ severity: params.severity,+ ventId: recorded && ctx.toolCallId ? `vent:${ctx.toolCallId}` : null,};++ return { content: formatVentResultContent(state), state, success: true };};// ==================== Media Analysis ====================diff --git a/packages/builtin-tool-lobe-agent/src/client/executor/vent.test.ts b/packages/builtin-tool-lobe-agent/src/client/executor/vent.test.tsnew file mode 100644index 00000000000..505d684cd9f--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/client/executor/vent.test.ts@@ -0,0 +1,90 @@+import type { BuiltinToolContext } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import type { VentParams } from '../../types';+import { lobeAgentExecutor } from './index';++vi.mock('@/services/notebook', () => ({ notebookService: {} }));+vi.mock('@/store/notebook', () => ({ useNotebookStore: { getState: () => ({}) } }));++const vent = (overrides: Partial<VentParams> = {}): VentParams => ({+ category: 'other',+ details: 'Output the SVG timing diagram directly',+ severity: 'low',+ summary: 'Stop',+ ...overrides,+});++let callSeq = 0;+const createContext = (rootOperationId: string): BuiltinToolContext => {+ callSeq += 1;+ // Each client tool call runs under its own child operation; the run is the root.+ return {+ messageId: `tool-msg-${callSeq}`,+ operationId: `op_tool_${callSeq}`,+ rootOperationId,+ toolCallId: `call_${callSeq}`,+ topicId: 'tpc_1',+ };+};++describe('lobeAgentExecutor.vent', () => {+ // A client run once called vent 133 times in a row to "stop the tool loop":+ // every call was recorded and answered with the same success line, so the+ // model never learned the call did nothing.+ it('records only the first vent of a run, whatever each tool call operation is', async () => {+ const results = [];+ for (let i = 0; i < 5; i += 1) {+ results.push(+ await lobeAgentExecutor.vent(vent({ summary: `Stop ${i}` }), createContext('op_run_a')),+ );+ }++ expect(results.map((r) => r.state?.recorded)).toEqual([true, false, false, false, false]);+ expect(results[1].state).toMatchObject({ reason: 'rate_limited', ventId: null });+ expect(results[1].content).toContain('Do not call vent again in this run');+ expect(results[1].content).toContain('does not stop, end, or reset anything');+ });++ it('flags a repeated report as a duplicate', async () => {+ await lobeAgentExecutor.vent(vent(), createContext('op_run_b'));+ const repeat = await lobeAgentExecutor.vent(+ vent({ details: ' output the SVG timing diagram directly ', summary: 'STOP' }),+ createContext('op_run_b'),+ );++ expect(repeat.state).toMatchObject({ reason: 'duplicate', recorded: false });+ expect(repeat.content).toContain('same report was already filed');+ });++ it('rejects an empty vent without spending the run allowance', async () => {+ const empty = await lobeAgentExecutor.vent(+ vent({ details: ' ', summary: '' }),+ createContext('op_run_c'),+ );+ const real = await lobeAgentExecutor.vent(vent(), createContext('op_run_c'));++ expect(empty.state).toMatchObject({ reason: 'empty_content', recorded: false });+ expect(empty.content).toContain('summary and details are empty');+ expect(real.state?.recorded).toBe(true);+ });++ it('gives each run its own allowance', async () => {+ const first = await lobeAgentExecutor.vent(vent(), createContext('op_run_d'));+ const second = await lobeAgentExecutor.vent(vent(), createContext('op_run_e'));++ expect(first.state?.recorded).toBe(true);+ expect(second.state?.recorded).toBe(true);+ expect(first.content).toContain('It does not end your turn');+ });++ it('still reports an unknown category as invalid arguments', async () => {+ const result = await lobeAgentExecutor.vent(+ vent({ category: 'nope' as never }),+ createContext('op_run_f'),+ );++ expect(result.success).toBe(false);+ expect(result.state).toEqual({ reason: 'invalid_category', recorded: false });+ });+});diff --git a/packages/builtin-tool-lobe-agent/src/index.ts b/packages/builtin-tool-lobe-agent/src/index.tsindex 4c1566244be..04c874b864d 100644--- a/packages/builtin-tool-lobe-agent/src/index.ts+++ b/packages/builtin-tool-lobe-agent/src/index.ts@@ -6,3 +6,4 @@ export * from './resolveManifest';export * from './subAgentReference';export * from './systemRole';export * from './types';+export * from './vent';diff --git a/packages/builtin-tool-lobe-agent/src/manifest.test.ts b/packages/builtin-tool-lobe-agent/src/manifest.test.tsindex 29982f945a3..ea3ca3d9368 100644--- a/packages/builtin-tool-lobe-agent/src/manifest.test.ts+++ b/packages/builtin-tool-lobe-agent/src/manifest.test.ts@@ -73,7 +73,16 @@ describe('LobeAgentManifest', () => {'toolName','evidenceRefs',]);- expect(ventApi!.description).toContain('at most one vent per task');+ expect(ventApi!.description).toContain('at most one vent per run');expect(LobeAgentManifest.systemRole).toContain('<vent>');});++ // A run once called vent 133 times as a way to "stop the tool loop".+ it('tells the model that vent is not a way to stop or end a loop', () => {+ const ventApi = LobeAgentManifest.api.find((api) => api.name === LobeAgentApiName.vent);++ expect(ventApi!.description).toContain('It never stops a tool loop or ends your turn');+ expect(LobeAgentManifest.systemRole).toContain('`vent` is never a control action');+ expect(LobeAgentManifest.systemRole).toContain('do not call it again');+ });});diff --git a/packages/builtin-tool-lobe-agent/src/manifest.ts b/packages/builtin-tool-lobe-agent/src/manifest.tsindex d2a130e3fcd..df3355c087f 100644--- a/packages/builtin-tool-lobe-agent/src/manifest.ts+++ b/packages/builtin-tool-lobe-agent/src/manifest.ts@@ -274,7 +274,7 @@ export const LobeAgentManifest: BuiltinToolManifest = {},{description:- 'Privately report friction in your own working conditions to the platform builders when you are genuinely blocked β a missing tool, a parameter/schema mismatch, conflicting or wrong docs, anomalous platform behavior, or an environment limit causing repeated failure. Not user-facing; it only records the report and does not fix anything. Use sparingly: at most one vent per task, only for the single worst blocker.',+ 'Privately report friction in your own working conditions to the platform builders when you are genuinely blocked β a missing tool, a parameter/schema mismatch, conflicting or wrong docs, anomalous platform behavior, or an environment limit causing repeated failure. Not user-facing; it only records the report and does not fix anything. Use sparingly: at most one vent per run, only for the single worst blocker. It never stops a tool loop or ends your turn β to stop, just reply to the user; repeated or empty vents are rejected.',name: LobeAgentApiName.vent,parameters: {additionalProperties: false,diff --git a/packages/builtin-tool-lobe-agent/src/systemRole.ts b/packages/builtin-tool-lobe-agent/src/systemRole.tsindex 69cbbfea80b..2ef608389c6 100644--- a/packages/builtin-tool-lobe-agent/src/systemRole.ts+++ b/packages/builtin-tool-lobe-agent/src/systemRole.ts@@ -242,7 +242,8 @@ const ventSection = `- It is NOT shown to the user, is NOT an answer, apology, or progress update, and does NOT fix anything by itself. Recording a vent never changes what you do next β continue the task normally after venting.- Be reluctant, not eager. Most tasks run fine and need no vent. Vent only when you are *genuinely blocked or clearly frustrated* by the platform itself β typically after the friction has actually cost you (a failed tool call, a retry that hit the same wall, a doc that contradicted reality).-- Emit at most ONE vent per task, only for the single worst blocker. Do not vent about your own mistakes, a hard user request, normal model limitations, or things you simply chose not to do. Never put secrets or sensitive user data in a vent.+- Emit at most ONE vent per run, only for the single worst blocker. Do not vent about your own mistakes, a hard user request, normal model limitations, or things you simply chose not to do. Never put secrets or sensitive user data in a vent.+- \`vent\` is never a control action: it does not stop a tool loop, end your turn, cancel anything, or reset state. If you want to stop calling tools, simply reply to the user in plain text without a tool call. The runtime records only the first vent of a run and rejects repeats and empty reports β when a vent comes back "not recorded", do not call it again.- **category**: missing_tool (no tool could do what was needed) Β· schema_mismatch (params/schema disagreed with docs or behavior) Β· doc_conflict (docs/instructions wrong, contradictory, or missing) Β· platform_bug (a surface errored or behaved anomalously, not your input) Β· env_limitation (sandbox/network/timeout/resource limit caused repeated failure) Β· other.- **severity**: high = could not complete, medium = forced a costly workaround, low = friction but recovered. **details**: what you tried, expected, what happened, and why it blocked you β specific enough to reproduce or fix.</vent>diff --git a/packages/builtin-tool-lobe-agent/src/types.ts b/packages/builtin-tool-lobe-agent/src/types.tsindex fe158d6dfd7..988274ad8b4 100644--- a/packages/builtin-tool-lobe-agent/src/types.ts+++ b/packages/builtin-tool-lobe-agent/src/types.ts@@ -92,7 +92,8 @@ export interface VentParams {toolName?: string;}-export type VentRejectionReason = 'invalid_category' | 'invalid_severity' | 'rate_limited';+export type VentRejectionReason =+ 'duplicate' | 'empty_content' | 'invalid_category' | 'invalid_severity' | 'rate_limited';export type VentStateReason = VentRejectionReason | 'missing_context' | 'runtime_error' | null;diff --git a/packages/builtin-tool-lobe-agent/src/vent.test.ts b/packages/builtin-tool-lobe-agent/src/vent.test.tsnew file mode 100644index 00000000000..3b3fbc2c2f2--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/vent.test.ts@@ -0,0 +1,71 @@+import { describe, expect, it } from 'vitest';++import {+ createMemoryVentLedger,+ getVentFingerprint,+ getVentScope,+ validateVentParams,+ VENT_LIMIT_PER_OPERATION,+ VENT_LIMIT_PER_TOPIC,+} from './vent';++describe('getVentScope', () => {+ it('prefers the run over the topic', () => {+ expect(getVentScope({ operationId: 'op-1', topicId: 'tpc-1' })).toEqual({+ key: 'operation:op-1',+ limit: VENT_LIMIT_PER_OPERATION,+ });+ expect(getVentScope({ topicId: 'tpc-1' })).toEqual({+ key: 'topic:tpc-1',+ limit: VENT_LIMIT_PER_TOPIC,+ });+ expect(getVentScope({})).toBeUndefined();+ });+});++describe('getVentFingerprint', () => {+ it('ignores case and whitespace differences', () => {+ expect(getVentFingerprint({ details: ' a b ', summary: 'Stop' })).toBe(+ getVentFingerprint({ details: 'A b', summary: 'stop ' }),+ );+ expect(getVentFingerprint({ details: 'a', summary: 'Stop' })).not.toBe(+ getVentFingerprint({ details: 'a', summary: 'Stop loop' }),+ );+ });+});++describe('validateVentParams', () => {+ it('rejects empty content after enum checks', () => {+ const base = { category: 'other', details: '', severity: 'low', summary: ' ' } as const;++ expect(validateVentParams(base)).toBe('empty_content');+ expect(validateVentParams({ ...base, category: 'x' as never })).toBe('invalid_category');+ expect(validateVentParams({ ...base, severity: 'x' as never })).toBe('invalid_severity');+ expect(validateVentParams({ ...base, details: 'tool 500s' })).toBeUndefined();+ });+});++describe('createMemoryVentLedger', () => {+ it('admits up to the limit and reports repeats as duplicates', () => {+ const ledger = createMemoryVentLedger();+ const admit = (fingerprint: string) => ledger.admit({ fingerprint, limit: 2, scopeKey: 's' });++ expect(admit('a')).toBe('accepted');+ expect(admit('a')).toBe('duplicate');+ expect(admit('b')).toBe('accepted');+ expect(admit('c')).toBe('rate_limited');+ expect(ledger.admit({ fingerprint: 'c', limit: 2, scopeKey: 'other' })).toBe('accepted');+ });++ it('evicts the least recently used scope past its capacity', () => {+ const ledger = createMemoryVentLedger({ maxScopes: 2 });+ const admit = (scopeKey: string) => ledger.admit({ fingerprint: 'a', limit: 1, scopeKey });++ admit('s1');+ admit('s2');+ admit('s3');++ expect(admit('s1')).toBe('accepted');+ expect(admit('s3')).toBe('duplicate');+ });+});diff --git a/packages/builtin-tool-lobe-agent/src/vent.ts b/packages/builtin-tool-lobe-agent/src/vent.tsnew file mode 100644index 00000000000..e18e4696e1e--- /dev/null+++ b/packages/builtin-tool-lobe-agent/src/vent.ts@@ -0,0 +1,133 @@+import {+ VENT_CATEGORIES,+ VENT_SEVERITIES,+ type VentParams,+ type VentRejectionReason,+ type VentState,+} from './types';++/** At most this many vents per run; a topic-scoped fallback gets a looser cap. */+export const VENT_LIMIT_PER_OPERATION = 1;+export const VENT_LIMIT_PER_TOPIC = 3;++/** Outcome of asking a ledger to admit one vent into its scope. */+export type VentAdmission = 'accepted' | 'duplicate' | 'rate_limited';++export interface VentAdmitParams {+ /** Normalized content of the vent, see {@link getVentFingerprint}. */+ fingerprint: string;+ /** Maximum number of vents the scope may admit. */+ limit: number;+ /** Run (or topic fallback) the vent is counted against. */+ scopeKey: string;+}++/**+ * Remembers which vents a scope already admitted, so a run cannot turn `vent`+ * into a loop. Client runs keep it in memory; the server backs it with Redis+ * because consecutive steps of one run may land on different instances.+ */+export interface VentLedger {+ admit: (params: VentAdmitParams) => Promise<VentAdmission> | VentAdmission;+}++export interface VentScope {+ key: string;+ limit: number;+}++/** Scope a vent counts against: the run when known, else the topic. */+export const getVentScope = (ids: {+ operationId?: string | null;+ topicId?: string | null;+}): VentScope | undefined => {+ if (ids.operationId)+ return { key: `operation:${ids.operationId}`, limit: VENT_LIMIT_PER_OPERATION };+ if (ids.topicId) return { key: `topic:${ids.topicId}`, limit: VENT_LIMIT_PER_TOPIC };+};++const normalizeText = (value: unknown) =>+ typeof value === 'string' ? value.trim().replaceAll(/\s+/g, ' ').toLowerCase() : '';++/** Content identity of a vent: same summary + details means the same report. */+export const getVentFingerprint = (params: Pick<VentParams, 'details' | 'summary'>) =>+ `${normalizeText(params.summary)}\n${normalizeText(params.details)}`;++/** Rejects a vent before it reaches any ledger; `undefined` means well-formed. */+export const validateVentParams = (+ params: Partial<VentParams> | undefined,+): VentRejectionReason | undefined => {+ if (!VENT_CATEGORIES.includes(params?.category as never)) return 'invalid_category';+ if (!VENT_SEVERITIES.includes(params?.severity as never)) return 'invalid_severity';+ if (!normalizeText(params?.summary) && !normalizeText(params?.details)) return 'empty_content';+};++/**+ * In-memory ledger. Admission is synchronous, so parallel tool calls in one+ * step cannot both slip under the cap. Oldest scopes are evicted past+ * `maxScopes` to keep long-lived processes bounded.+ */+export const createMemoryVentLedger = ({ maxScopes = 1000 } = {}): VentLedger => {+ const scopes = new Map<string, Set<string>>();++ return {+ admit: ({ fingerprint, limit, scopeKey }) => {+ const admitted = scopes.get(scopeKey) ?? new Set<string>();++ if (admitted.has(fingerprint)) return 'duplicate';+ if (admitted.size >= limit) return 'rate_limited';++ admitted.add(fingerprint);+ scopes.delete(scopeKey);+ scopes.set(scopeKey, admitted);++ if (scopes.size > maxScopes) scopes.delete(scopes.keys().next().value!);++ return 'accepted';+ },+ };+};++const STOP_VENTING =+ 'Do not call vent again in this run. vent does not stop, end, or reset anything β to finish, reply to the user directly; to make progress, call the tool you actually need.';++/**+ * Renders the tool-result text the calling LLM reads after a vent attempt.+ *+ * The persisted state stays structured; this string must make clear that the+ * report changes nothing about the run, and that a rejected vent must not be+ * retried.+ */+export const formatVentResultContent = (state: VentState): string => {+ if (state.recorded) {+ const label = [state.severity, state.category].filter(Boolean).join(' ');+ return [+ `Vent recorded${label ? ` (${label})` : ''}${state.ventId ? `, id ${state.ventId}` : ''}.`,+ 'The friction report has been filed for the platform team. It does not end your turn or change anything β continue your task, and do not vent again in this run.',+ ].join(' ');+ }++ switch (state.reason) {+ case 'rate_limited': {+ return `Vent not recorded: this run already filed its vent. ${STOP_VENTING}`;+ }+ case 'duplicate': {+ return `Vent not recorded: the same report was already filed in this run. ${STOP_VENTING}`;+ }+ case 'empty_content': {+ return `Vent not recorded: summary and details are empty. A vent is only for a concrete platform problem you can describe. ${STOP_VENTING}`;+ }+ case 'invalid_category': {+ return `Vent not recorded: unknown category. Valid categories: ${VENT_CATEGORIES.join(', ')}.`;+ }+ case 'invalid_severity': {+ return `Vent not recorded: unknown severity. Valid severities: ${VENT_SEVERITIES.join(', ')}.`;+ }+ case 'missing_context': {+ return 'Vent not recorded: agent or topic context is missing in this run. Continue your task.';+ }+ default: {+ return 'Vent not recorded. Continue your task.';+ }+ }+};