🤯 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(hetero): let a long-running hetero run renew its operation token (#19548)
Arvin Xu4565c140d6f4
diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.refreshHeteroOperationToken.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.refreshHeteroOperationToken.test.tsnew file mode 100644index 00000000000..29826da645c--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.refreshHeteroOperationToken.test.ts@@ -0,0 +1,107 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type * as InternalJwtModule from '@/libs/trpc/utils/internalJwt';+import type * as OperationPrincipalModule from '@/server/services/heterogeneousAgent/operationPrincipal';+import { HeteroOperationPrincipalError } from '@/server/services/heterogeneousAgent/operationPrincipal';++import { aiAgentRouter } from '../aiAgent';++const { resolvePrincipal, signOperationToken } = vi.hoisted(() => ({+ resolvePrincipal: vi.fn(),+ signOperationToken: vi.fn(),+}));++vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return {};+ }),+}));+vi.mock('@/libs/trpc/utils/internalJwt', async (importOriginal) => ({+ ...(await importOriginal<typeof InternalJwtModule>()),+ signHeteroOperationJWT: signOperationToken,+}));+vi.mock('@/server/services/heterogeneousAgent/operationPrincipal', async (importOriginal) => ({+ ...(await importOriginal<typeof OperationPrincipalModule>()),+ resolveActiveHeteroOperationPrincipal: resolvePrincipal,+}));++const operationClaims = {+ aud: 'urn:lobehub:hetero-operation',+ capabilities: ['hetero:ingest', 'hetero:finish', 'hetero:intervention:read'],+ exp: 1_789_327_443,+ iat: 1_789_313_043,+ iss: 'urn:lobehub:internal',+ jti: 'jti-1',+ operation_id: 'op-1',+ purpose: 'hetero-operation',+ sub: 'user-1',+ workspace_id: 'workspace-1',+};++const caller = (oidcAuth: Record<string, unknown>) =>+ aiAgentRouter.createCaller({+ jwtPayload: { userId: oidcAuth.sub },+ oidcAuth,+ userId: oidcAuth.sub,+ } as any);++beforeEach(() => {+ vi.clearAllMocks();+ resolvePrincipal.mockResolvedValue({ operationId: 'op-1', userId: 'user-1' });+ signOperationToken.mockResolvedValue('renewed-token');+});++/**+ * Regression: a Goal Task ran past the four hours its operation token was+ * signed for, and there was no way to get another. Every ingest after that was+ * rejected, so the run's output and completion never reached the server.+ */+describe('aiAgentRouter.refreshHeteroOperationToken', () => {+ it('re-mints a token with the same scope for a running operation', async () => {+ await expect(+ caller(operationClaims).refreshHeteroOperationToken({ operationId: 'op-1' }),+ ).resolves.toEqual({ jwt: 'renewed-token' });++ expect(resolvePrincipal).toHaveBeenCalledWith(+ expect.objectContaining({ capability: 'hetero:ingest', operationId: 'op-1' }),+ );+ expect(signOperationToken).toHaveBeenCalledWith({+ capabilities: operationClaims.capabilities,+ model: undefined,+ operationId: 'op-1',+ providerId: undefined,+ userId: 'user-1',+ workspaceId: 'workspace-1',+ });+ });++ it('refuses to renew once the operation has ended', async () => {+ resolvePrincipal.mockRejectedValue(+ new HeteroOperationPrincipalError('Operation has already ended', 409),+ );++ await expect(+ caller(operationClaims).refreshHeteroOperationToken({ operationId: 'op-1' }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ expect(signOperationToken).not.toHaveBeenCalled();+ });++ it('refuses a token scoped to a different operation', async () => {+ resolvePrincipal.mockRejectedValue(+ new HeteroOperationPrincipalError('Operation token does not grant this request', 403),+ );++ await expect(+ caller(operationClaims).refreshHeteroOperationToken({ operationId: 'op-2' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(signOperationToken).not.toHaveBeenCalled();+ });++ it('never turns a user session into an operation token', async () => {+ await expect(+ caller({ sub: 'user-1' }).refreshHeteroOperationToken({ operationId: 'op-1' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ expect(signOperationToken).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex aba981bec50..7327e0a19b2 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -3119,6 +3119,42 @@ export const aiAgentRouter = router({}}),+ /**+ * Re-mint the operation token a long `lh hetero exec` run authenticates with.+ *+ * The token is signed for four hours, and a Goal Task can run far longer. Past+ * the expiry every heteroIngest is rejected, the run's heartbeats stop renewing+ * its lease, and the operation is reclaimed as abandoned while the agent is still+ * working. The producer calls this before expiry. The replacement carries the+ * same claims, and is issued only while the operation is still running under a+ * principal that is still authorized — so renewal never outlives revocation.+ */+ refreshHeteroOperationToken: heteroAgentProcedure+ .input(z.object({ operationId: z.string().min(1) }))+ .mutation(async ({ input, ctx }) => {+ // A user session has its own refresh flow, and a legacy token carries no+ // operation claims to copy, so only the narrow operation token renews here.+ if (ctx.heteroAuthKind !== 'operation' || !ctx.heteroOperation) {+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only an operation token can be renewed',+ });+ }+ await authorizeOperationCallback(ctx, input.operationId, 'hetero:ingest');++ const claims = ctx.heteroOperation;+ const jwt = await signHeteroOperationJWT({+ capabilities: claims.capabilities,+ model: claims.model,+ operationId: claims.operation_id,+ providerId: claims.provider_id,+ userId: claims.sub,+ workspaceId: claims.workspace_id,+ });++ return { jwt };+ }),+/*** Terminal handshake from a `lh hetero exec` producer: signals process exit* and carries the run's high-level outcome. Always emits a final