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.

✨ feat(server): sign agent trace snapshots for the trace CLI (#18796)

Arvin Xua06b4e2672ff
diff --git a/apps/server/src/routers/lambda/agentTrace.test.ts b/apps/server/src/routers/lambda/agentTrace.test.ts
new file mode 100644
index 00000000000..9624a1c04b4
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentTrace.test.ts
@@ -0,0 +1,101 @@
+// @vitest-environment node
+import type { TRPCError } from '@trpc/server';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { createCallerFactory } from '@/libs/trpc/lambda';
+import { type AuthContext, createContextInner } from '@/libs/trpc/lambda/context';
+
+import { agentTraceRouter } from './agentTrace';
+
+const mockServerDB = vi.hoisted(() => ({}));
+const mocks = vi.hoisted(() => ({
+ createPreSignedUrlForPreview: vi.fn(),
+ findById: vi.fn(),
+ listByTopic: vi.fn(),
+}));
+
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn().mockResolvedValue(mockServerDB),
+}));
+
+vi.mock('@/database/models/agentOperation', () => ({
+ AgentOperationModel: vi.fn().mockImplementation(() => ({
+ findById: mocks.findById,
+ listByTopic: mocks.listByTopic,
+ })),
+}));
+
+vi.mock('@/server/modules/S3', () => ({
+ FileS3: vi.fn().mockImplementation(() => ({
+ createPreSignedUrlForPreview: mocks.createPreSignedUrlForPreview,
+ })),
+}));
+
+const createCaller = createCallerFactory(agentTraceRouter);
+
+const TRACE_KEY = 'agent-traces/agt_a/tpc_b/op_1_agt_a_tpc_b_c.json.zst';
+
+describe('agentTraceRouter', () => {
+ let ctx: AuthContext;
+ let router: ReturnType<typeof createCaller>;
+
+ beforeEach(async () => {
+ vi.clearAllMocks();
+ ctx = await createContextInner({ userId: 'user-1', workspaceId: 'workspace-1' });
+ router = createCaller(ctx);
+ });
+
+ describe('getSnapshotUrl', () => {
+ it('signs the key recorded on the operation', async () => {
+ mocks.findById.mockResolvedValue({ id: 'op-1', traceS3Key: TRACE_KEY });
+ mocks.createPreSignedUrlForPreview.mockResolvedValue('https://s3.example.com/obj?sig=abc');
+
+ await expect(router.getSnapshotUrl({ operationId: 'op-1' })).resolves.toEqual({
+ data: {
+ key: TRACE_KEY,
+ operationId: 'op-1',
+ url: 'https://s3.example.com/obj?sig=abc',
+ },
+ success: true,
+ });
+ expect(mocks.createPreSignedUrlForPreview).toHaveBeenCalledWith(TRACE_KEY);
+ });
+
+ it('refuses an operation the caller cannot see, without reaching storage', async () => {
+ // findById is ownership-scoped, so somebody else's operation reads as
+ // absent β€” a leaked operation id must not become a readable trace.
+ mocks.findById.mockResolvedValue(null);
+
+ await expect(router.getSnapshotUrl({ operationId: 'op-foreign' })).rejects.toThrow(
+ expect.objectContaining({ code: 'NOT_FOUND' }) as TRPCError,
+ );
+ expect(mocks.createPreSignedUrlForPreview).not.toHaveBeenCalled();
+ });
+
+ it('says the run recorded no trace instead of signing an empty key', async () => {
+ mocks.findById.mockResolvedValue({ id: 'op-1', traceS3Key: null });
+
+ await expect(router.getSnapshotUrl({ operationId: 'op-1' })).rejects.toThrow(
+ /No trace was recorded/,
+ );
+ expect(mocks.createPreSignedUrlForPreview).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('listOperations', () => {
+ it('reports trace availability without exposing the storage key', async () => {
+ mocks.listByTopic.mockResolvedValue([
+ { id: 'op-1', status: 'done', traceS3Key: TRACE_KEY },
+ { id: 'op-2', status: 'error', traceS3Key: null },
+ ]);
+
+ const result = await router.listOperations({ topicId: 'tpc_b' });
+
+ expect(result.data).toEqual([
+ { hasTrace: true, id: 'op-1', status: 'done' },
+ { hasTrace: false, id: 'op-2', status: 'error' },
+ ]);
+ expect(mocks.listByTopic).toHaveBeenCalledWith('tpc_b', 20);
+ });
+ });
+});
diff --git a/apps/server/src/routers/lambda/agentTrace.ts b/apps/server/src/routers/lambda/agentTrace.ts
new file mode 100644
index 00000000000..7be3f17cfc7
--- /dev/null
+++ b/apps/server/src/routers/lambda/agentTrace.ts
@@ -0,0 +1,106 @@
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { wsCompatProcedure } from '@/business/server/trpc-middlewares/workspaceAuth';
+import { AgentOperationModel } from '@/database/models/agentOperation';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { FileS3 } from '@/server/modules/S3';
+
+/**
+ * Read-only access to the agent execution snapshots uploaded by
+ * `S3SnapshotStore`. Exists so `lh trace` can inspect a production run with
+ * nothing but a LobeHub login: the two things that previously had to be done
+ * by hand β€” mapping a topic id to an operation id (a SQL query) and reaching
+ * the bucket (a per-deployment `TRACING_BASE_URL` pointing at a public
+ * domain) β€” both happen here, behind the caller's own ownership scope.
+ */
+const agentTraceProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ return opts.next({
+ ctx: {
+ agentOperationModel: new AgentOperationModel(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ ),
+ },
+ });
+});
+
+export const agentTraceRouter = router({
+ /**
+ * Pre-signed GET for one operation's snapshot object.
+ *
+ * The snapshot itself is deliberately NOT returned through TRPC: it is a
+ * zstd blob that decompresses 8-9x (see `S3SnapshotStore`), and pushing it
+ * through superjson would serialize the whole thing twice on the server.
+ * The client downloads and decompresses it directly instead.
+ */
+ getSnapshotUrl: agentTraceProcedure
+ .input(z.object({ operationId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ try {
+ // Ownership-scoped: an operation belonging to someone else reads as
+ // absent rather than forbidden, so this can't be used to probe ids.
+ const operation = await ctx.agentOperationModel.findById(input.operationId);
+ if (!operation) {
+ throw new TRPCError({ code: 'NOT_FOUND', message: 'Operation not found' });
+ }
+
+ if (!operation.traceS3Key) {
+ throw new TRPCError({
+ code: 'NOT_FOUND',
+ message:
+ 'No trace was recorded for this operation (trace_s3_key is empty). ' +
+ 'Snapshot upload may have been disabled when it ran.',
+ });
+ }
+
+ const url = await new FileS3().createPreSignedUrlForPreview(operation.traceS3Key);
+
+ return {
+ data: {
+ key: operation.traceS3Key,
+ operationId: operation.id,
+ url,
+ },
+ success: true as const,
+ };
+ } catch (error) {
+ if (error instanceof TRPCError) throw error;
+ console.error('[agentTrace:getSnapshotUrl]', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to sign the trace snapshot URL',
+ });
+ }
+ }),
+
+ /** Operations recorded for a topic, newest first. */
+ listOperations: agentTraceProcedure
+ .input(z.object({ limit: z.number().min(1).max(100).default(20), topicId: z.string() }))
+ .query(async ({ input, ctx }) => {
+ try {
+ const operations = await ctx.agentOperationModel.listByTopic(input.topicId, input.limit);
+
+ return {
+ // The key itself is an internal storage detail; callers only need to
+ // know whether there is a snapshot to fetch.
+ data: operations.map(({ traceS3Key, ...operation }) => ({
+ ...operation,
+ hasTrace: Boolean(traceS3Key),
+ })),
+ success: true as const,
+ };
+ } catch (error) {
+ console.error('[agentTrace:listOperations]', error);
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: 'Failed to list operations',
+ });
+ }
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 21e1be578c9..6d2670c6051 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -32,6 +32,7 @@ import { agentNotifyRouter } from './agentNotify';
import { agentQuotaRouter } from './agentQuota';
import { agentSignalRouter } from './agentSignal';
import { agentSkillsRouter } from './agentSkills';
+import { agentTraceRouter } from './agentTrace';
import { aiAgentRouter } from './aiAgent';
import { aiChatRouter } from './aiChat';
import { aiModelRouter } from './aiModel';
@@ -108,6 +109,7 @@ export const lambdaRouter = router({
agentEvalExternal: agentEvalExternalRouter,
agentLabel: agentLabelRouter,
agentSkills: agentSkillsRouter,
+ agentTrace: agentTraceRouter,
expertise: expertiseRouter,
agentSignal: agentSignalRouter,
changelog: changelogRouter,
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index 3e2ae38e47f..6ba3f7b425b 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -181,6 +181,11 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
agentQuota: rw('agent:read', null),
agentSignal: rw('agent:read', 'agent:write'),
agentSkills: rw('agent:read', 'agent:write'),
+ // a trace snapshot is the whole inside of a run β€” system role, injected user
+ // memory, tool results β€” and `getSnapshotUrl` hands back a presigned URL that
+ // needs no further auth, so a restricted key holding one would read past its
+ // own scope. Same call as `llmGenerationTracing`.
+ agentTrace: 'blocked',
aiAgent: rw('agent:read', 'agent:write'),
aiChat: { any: 'model:invoke' },
aiModel: rw('model:read', 'model:write'),
diff --git a/packages/database/src/models/__tests__/agentOperation.test.ts b/packages/database/src/models/__tests__/agentOperation.test.ts
index b0cfb628669..b872699fd51 100644
--- a/packages/database/src/models/__tests__/agentOperation.test.ts
+++ b/packages/database/src/models/__tests__/agentOperation.test.ts
@@ -5,7 +5,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { matchesAgentInterventionContinuationProvenance } from '@/business/server/agent-run/agentInterventionIdentity';
import { getTestDB } from '../../core/getTestDB';
-import { agentOperations, users } from '../../schemas';
+import { agentOperations, topics, users } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { AgentOperationModel } from '../agentOperation';
@@ -563,4 +563,79 @@ describe('AgentOperationModel', () => {
expect(tree.map((op) => op.id)).toEqual(['lonely']);
});
});
+
+ describe('listByTopic', () => {
+ beforeEach(async () => {
+ await serverDB.insert(topics).values([
+ { id: 'tpc-a', userId },
+ { id: 'tpc-b', userId },
+ { id: 'tpc-foreign', userId: otherUserId },
+ ]);
+ });
+
+ it('returns the topic operations newest first, owner-scoped', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+
+ await serverDB.insert(agentOperations).values([
+ {
+ createdAt: new Date('2026-01-01'),
+ id: 'op-old',
+ status: 'done',
+ topicId: 'tpc-a',
+ userId,
+ },
+ {
+ createdAt: new Date('2026-01-03'),
+ id: 'op-new',
+ status: 'done',
+ topicId: 'tpc-a',
+ userId,
+ },
+ // Another topic's op must not leak in.
+ { id: 'op-other-topic', status: 'done', topicId: 'tpc-b', userId },
+ // Another user's op on the same topic must not leak in.
+ { id: 'op-foreign', status: 'done', topicId: 'tpc-a', userId: otherUserId },
+ ]);
+
+ const rows = await model.listByTopic('tpc-a');
+ expect(rows.map((row) => row.id)).toEqual(['op-new', 'op-old']);
+ });
+
+ it('reports whether a trace was recorded so callers can tell it apart from a failed fetch', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+
+ await serverDB.insert(agentOperations).values([
+ {
+ id: 'op-with-trace',
+ status: 'done',
+ topicId: 'tpc-a',
+ traceS3Key: 'agent-traces/agt_x/tpc-a/op-with-trace.json.zst',
+ userId,
+ },
+ { id: 'op-without-trace', status: 'done', topicId: 'tpc-a', userId },
+ ]);
+
+ const byId = Object.fromEntries(
+ (await model.listByTopic('tpc-a')).map((row) => [row.id, row.traceS3Key]),
+ );
+ expect(byId['op-with-trace']).toBe('agent-traces/agt_x/tpc-a/op-with-trace.json.zst');
+ expect(byId['op-without-trace']).toBeNull();
+ });
+
+ it('honours the limit', async () => {
+ const model = new AgentOperationModel(serverDB, userId);
+
+ await serverDB.insert(agentOperations).values(
+ Array.from({ length: 5 }, (_, index) => ({
+ createdAt: new Date(2026, 0, index + 1),
+ id: `op-${index}`,
+ status: 'done' as const,
+ topicId: 'tpc-a',
+ userId,
+ })),
+ );
+
+ expect((await model.listByTopic('tpc-a', 2)).map((row) => row.id)).toEqual(['op-4', 'op-3']);
+ });
+ });
});
diff --git a/packages/database/src/models/agentOperation.ts b/packages/database/src/models/agentOperation.ts
index 27a8f44e867..75d982af071 100644
--- a/packages/database/src/models/agentOperation.ts
+++ b/packages/database/src/models/agentOperation.ts
@@ -405,6 +405,35 @@ export class AgentOperationModel {
return row ?? null;
}
+ /**
+ * Operations recorded for one topic, newest first β€” the lookup that turns a
+ * topic id (what a user actually has on hand) into the operation ids their
+ * traces are keyed by. `traceS3Key` rides along so callers can tell "no
+ * snapshot was recorded" apart from "snapshot exists but the fetch failed".
+ */
+ async listByTopic(topicId: string, limit = 20) {
+ return this.db
+ .select({
+ agentId: agentOperations.agentId,
+ createdAt: agentOperations.createdAt,
+ id: agentOperations.id,
+ model: agentOperations.model,
+ parentOperationId: agentOperations.parentOperationId,
+ provider: agentOperations.provider,
+ startedAt: agentOperations.startedAt,
+ status: agentOperations.status,
+ stepCount: agentOperations.stepCount,
+ totalCost: agentOperations.totalCost,
+ totalTokens: agentOperations.totalTokens,
+ traceS3Key: agentOperations.traceS3Key,
+ trigger: agentOperations.trigger,
+ })
+ .from(agentOperations)
+ .where(and(eq(agentOperations.topicId, topicId), this.ownership()))
+ .orderBy(sql`${agentOperations.createdAt} desc`)
+ .limit(limit);
+ }
+
/**
* Total USD cost of every operation bound to a task β€” the goal outer loop's
* budget meter. Only root (task-bound) operations carry `taskId`, and each