π€― 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-runtime): propagate originating request client ip/ua into run metadata (#17266)
YuTengjingac274c869098
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.mdindex 2f7a562dd2e..079d35fe698 100644--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md@@ -1531,3 +1531,29 @@ ingest-report <dir> --subject topic:<id> β¦` β and verify attachment in the D"β₯1500 ε + Python code" requirement produced a 3.5k-char deliverable) β a contradictory-criteriafixture still fails verification, but not for the reason you scripted; assert on the verifier'srecorded rationale, not on your intended contradiction.++### E35. A listening port is NOT the product under test β another project's dev server can own it++- **Situation**: `.env` says `PORT=<n>`, something answers on `<n>`, and a prior session recorded+ "dev server running on `<n>`" β so the run plans a mere restart.+- **Doesn't work**: trusting liveness (an HTTP response, an open socket) as identity. A sibling+ project's dev server started on the same port responds happily; every request then exercises the+ wrong codebase, and hook/DB assertions fail in ways that read as product bugs.+- **Works**: fingerprint the app before using it: `ps -o command= -p <pid>` of the listener shows the+ repo path in the `next dev`/`node` command line, and an unauthenticated `GET /` redirect is a+ cheap signature (this repo's better-auth redirects to `/signin`; a Clerk app redirects to+ `/login` with `x-clerk-*` headers). If it is the wrong app, free the port and start the right+ server β and re-verify with the same fingerprint after boot.++### C13. better-auth email-verification cannot be completed from the outside β treat real-mail paths as blocked++- **Situation**: an assertion requires a REAL email-verification event (e.g. a hook that only fires+ on better-auth verification routes), and the test inbox does not exist.+- **Doesn't work**: recovering the token from the database. The `/verify-email` link token is a+ signed JWT that is never stored; the email-otp OTP did not appear in the `verifications` table+ either (only unrelated OIDC rows), and the send endpoint returns `{"success":true}` regardless.+ Flipping `email_verified` in the DB is a fixture, not a verification β route-gated hooks+ correctly ignore it (which is itself a useful negative check).+- **Works**: mark the case `blocked` and cover the path with unit tests, or run the flow with a+ real receivable mailbox (staging/prod smoke). Use the DB flip only to unblock downstream+ fixtures, and assert it does NOT produce the event as a bonus authenticity check.diff --git a/.agents/skills/drizzle/SKILL.md b/.agents/skills/drizzle/SKILL.mdindex 808728f345b..601cb88ae89 100644--- a/.agents/skills/drizzle/SKILL.md+++ b/.agents/skills/drizzle/SKILL.md@@ -205,6 +205,14 @@ metadata: jsonb('metadata').$type<UserSignupLogMetadata>(),metadata: jsonb('metadata').$type<Record<string, unknown>>(),```+A loosely-typed JSONB column is often a symptom of a deeper problem: the column+was reserved speculatively ("for future extension") and nothing actually writes+it. Don't add `metadata` / `extra` JSONB columns for hypothetical future needs β+a column earns its place only when a concrete writer ships alongside it. When+review finds such a column, the fix is to **delete the column**, not to invent+an interface for data that doesn't exist; add a properly-typed column once the+real requirement arrives.+### Indexes```typescriptdiff --git a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.tsindex 8032d9f56fe..b7ada46d7a8 100644--- a/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/ServerLLMTransport.ts@@ -288,8 +288,13 @@ export class ServerLLMTransport implements LLMTransport {operationLogId,provider: input.provider,resolved,+ // Carry the originating request's client IP / user agent from the run's+ // state.metadata into the attempt so the LLM-call metadata can surface them+ // for auditing and spend attribution.+ clientIp: input.state.metadata?.clientIp,topicId: input.state.metadata?.topicId,trigger: input.state.metadata?.trigger,+ userAgent: input.state.metadata?.userAgent,});try {diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.tsindex fff0247ef08..35d839929bf 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.test.ts@@ -42,6 +42,7 @@ const resolved = {const createAttempt = (runCallbacks: (options: ChatMethodOptions) => Promise<void>,blobStore?: BlobStore,+ attemptOverrides?: { clientIp?: string; userAgent?: string },) => {const publishStreamChunk = vi.fn().mockResolvedValue('event-1');const streamManager = {@@ -84,6 +85,7 @@ const createAttempt = (resolved,topicId: 'topic-1',trigger: 'user',+ ...attemptOverrides,});return { attempt, chat, events, onFirstChunk, publishStreamChunk };@@ -153,6 +155,45 @@ describe('ServerCallLlmAttempt', () => {);});+ it('forwards clientIp / userAgent into the chat call metadata when provided', async () => {+ const { attempt, chat } = createAttempt(+ async ({ callback }) => {+ await callback?.onText?.('Answer');+ await callback?.onCompletion?.({ text: '', usage: { totalOutputTokens: 1 } });+ },+ undefined,+ { clientIp: '203.0.113.7', userAgent: 'Mozilla/5.0 (Test)' },+ );++ await attempt.execute();++ expect(chat).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ metadata: expect.objectContaining({+ clientIp: '203.0.113.7',+ operationId: 'operation-1',+ topicId: 'topic-1',+ trigger: 'user',+ userAgent: 'Mozilla/5.0 (Test)',+ }),+ }),+ );+ });++ it('leaves clientIp / userAgent metadata undefined when not provided', async () => {+ const { attempt, chat } = createAttempt(async ({ callback }) => {+ await callback?.onText?.('Answer');+ await callback?.onCompletion?.({ text: '', usage: { totalOutputTokens: 1 } });+ });++ await attempt.execute();++ const metadata = chat.mock.calls[0][1]!.metadata as Record<string, unknown>;+ expect(metadata.clientIp).toBeUndefined();+ expect(metadata.userAgent).toBeUndefined();+ });+it('keeps partial output and usage readable after a stream error', async () => {const { attempt } = createAttempt(async ({ callback }) => {await callback?.onText?.('Partial answer');diff --git a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.tsindex 45a1bb27ad1..6ed1ff5a4c5 100644--- a/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts+++ b/apps/server/src/modules/AgentRuntime/adapters/serverCallLlmAttempt.ts@@ -28,6 +28,8 @@ interface CreateServerCallLlmAttemptInput {attempt: number;blobStore?: BlobStore;chatPayload: ChatStreamPayload;+ /** Client IP of the originating request, forwarded into the LLM-call metadata for auditing and spend attribution. */+ clientIp?: string;ctx: RuntimeExecutorContext;events: AgentEvent[];maxAttempts: number;@@ -40,6 +42,8 @@ interface CreateServerCallLlmAttemptInput {resolved: ServerCallLlmTooling['resolved'];topicId?: string;trigger?: unknown;+ /** User agent of the originating request, forwarded into the LLM-call metadata for auditing and spend attribution. */+ userAgent?: string;}const createStreamExecutionError = (errorData: unknown) => {@@ -61,6 +65,7 @@ export class ServerCallLlmAttempt {private answerSalvagedFromReasoning = false;private readonly attempt: number;private readonly chatPayload: ChatStreamPayload;+ private readonly clientIp?: string;private readonly ctx: RuntimeExecutorContext;private finishReason?: string;private grounding: GroundingSearch | null = null;@@ -80,12 +85,14 @@ export class ServerCallLlmAttempt {private toolsCalling: ChatToolPayload[] = [];private readonly topicId?: string;private readonly trigger?: unknown;+ private readonly userAgent?: string;private usage?: ModelUsage;constructor({attempt,blobStore,chatPayload,+ clientIp,ctx,events,maxAttempts,@@ -98,9 +105,11 @@ export class ServerCallLlmAttempt {resolved,topicId,trigger,+ userAgent,}: CreateServerCallLlmAttemptInput) {this.attempt = attempt;this.chatPayload = chatPayload;+ this.clientIp = clientIp;this.ctx = ctx;this.maxAttempts = maxAttempts;this.messageCount = messageCount;@@ -118,6 +127,7 @@ export class ServerCallLlmAttempt {});this.topicId = topicId;this.trigger = trigger;+ this.userAgent = userAgent;}async execute(): Promise<void> {@@ -217,9 +227,11 @@ export class ServerCallLlmAttempt {},},metadata: {+ clientIp: this.clientIp,operationId: this.ctx.operationId,topicId: this.topicId,trigger: this.trigger,+ userAgent: this.userAgent,},user: this.ctx.userId,});diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 94f4f832ef3..9289d36f015 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -770,6 +770,11 @@ export const aiAgentRouter = router({agentId,appContext,autoStart,+ // Propagate the originating request's client IP / user agent into the run+ // so downstream LLM-call metadata can carry them for auditing and spend+ // attribution. These are server-derived from the tRPC context and are+ // intentionally not part of the client-passable input schema.+ clientIp: ctx.clientIp ?? undefined,deviceId,existingMessageIds,fileIds,@@ -784,6 +789,7 @@ export const aiAgentRouter = router({selectedToolIds,slug,trigger: trigger ?? RequestTrigger.Chat,+ userAgent: ctx.userAgent ?? undefined,userInterventionConfig,});} catch (error: any) {diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 49ee27b9771..5bf2e8a2c6f 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -342,6 +342,12 @@ export interface OperationCreationParams {* read on the completion path to project receipts.*/agentSignal?: AgentSignalOperationMarker;+ /**+ * Client IP of the originating request. Spread onto `state.metadata.clientIp`+ * so downstream LLM-call metadata can carry it for auditing and spend+ * attribution.+ */+ clientIp?: string;defaultTaskAssigneeAgentId?: string;documentId?: string | null;groupId?: string | null;@@ -373,6 +379,12 @@ export interface OperationCreationParams {threadId?: string | null;topicId?: string | null;trigger?: string;+ /**+ * User agent of the originating request. Spread onto+ * `state.metadata.userAgent` so downstream LLM-call metadata can carry it for+ * auditing and spend attribution.+ */+ userAgent?: string;};autoStart?: boolean;/**diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.tsindex df346dbc0c7..cc1812a78d4 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.headlessDefault.test.ts@@ -163,6 +163,34 @@ describe('AiAgentService.execAgent - headless approval default', () => {expect(callArgs.userInterventionConfig).toEqual({ approvalMode: 'manual' });});+ it('forwards clientIp / userAgent into the createOperation appContext when provided', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ clientIp: '203.0.113.7',+ prompt: 'Hello',+ userAgent: 'Mozilla/5.0 (Test)',+ });++ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ const callArgs = mockCreateOperation.mock.calls[0][0];+ expect(callArgs.appContext).toMatchObject({+ clientIp: '203.0.113.7',+ userAgent: 'Mozilla/5.0 (Test)',+ });+ });++ it('leaves clientIp / userAgent undefined in the createOperation appContext when not provided', async () => {+ await service.execAgent({+ agentId: 'agent-1',+ prompt: 'Hello',+ });++ expect(mockCreateOperation).toHaveBeenCalledTimes(1);+ const { appContext } = mockCreateOperation.mock.calls[0][0];+ expect(appContext.clientIp).toBeUndefined();+ expect(appContext.userAgent).toBeUndefined();+ });+it('should respect explicit allow-list approval mode with allowList', async () => {const config = { allowList: ['tool-a', 'tool-b'], approvalMode: 'allow-list' as const };diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.tsindex 1ec28dd53a7..a44dfbac945 100644--- a/apps/server/src/services/aiAgent/index.ts+++ b/apps/server/src/services/aiAgent/index.ts@@ -1100,6 +1100,8 @@ export class AiAgentService {appContext,autoStart = true,botContext,+ clientIp,+ userAgent,deviceId: requestedDeviceId,botPlatformContext,discordContext,@@ -3888,6 +3890,12 @@ export class AiAgentService {// context (state.metadata.agentId) targets the reviewed agent; ordinary// runs (no marker) fall back to the resolved executing agent.agentId: appContext?.agentSignal?.agentId ?? resolvedAgentId,+ // Propagate the originating request's client IP / user agent into+ // state.metadata (via the `...appContext` spread in createOperation) so+ // downstream LLM-call metadata can carry them for auditing and spend+ // attribution.+ clientIp,+ userAgent,// When scope === 'agent_builder', agentId stays as the builder builtin so// message ownership and queryUiMessages remain correct. editingAgentId// carries the actual editing target separately; only the AgentBuilder serverdiff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.tsindex 572e8a2a757..8a26935fa36 100644--- a/packages/types/src/agentExecution/index.ts+++ b/packages/types/src/agentExecution/index.ts@@ -145,6 +145,13 @@ export interface ExecAgentParams {appContext?: ExecAgentAppContext;/** Whether to auto-start execution after creating operation (default: true) */autoStart?: boolean;+ /**+ * Client IP of the originating request, captured server-side for run+ * attribution. Propagated into the run's `state.metadata` and downstream+ * LLM-call metadata for auditing and spend attribution. Never client-passable+ * input β derived from the request context.+ */+ clientIp?: string;/** Explicit device ID to bind to the topic and activate for this run */deviceId?: string;/** Optional existing message IDs to include in context */@@ -173,6 +180,13 @@ export interface ExecAgentParams {provider?: string;/** The agent slug to run (either agentId or slug is required) */slug?: string;+ /**+ * User agent of the originating request, captured server-side for run+ * attribution. Propagated into the run's `state.metadata` and downstream+ * LLM-call metadata for auditing and spend attribution. Never client-passable+ * input β derived from the request context.+ */+ userAgent?: string;}/**