Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import type {
ExecutionMetadata,
AddExecutionParams,
UpdateExecutionStatusParams,
LatestAssistantMessage,
} from '../session/types.js';
import type { ExecutionStatus } from '../core/execution.js';
import type { Result } from '../lib/result.js';
Expand Down Expand Up @@ -581,6 +582,13 @@ export class CloudAgentSession extends DurableObject {
return metadata || null;
}

async getLatestAssistantMessage(): Promise<LatestAssistantMessage | null> {
const sessionId = await this.requireSessionId();
const metadata = await this.getMetadata();
if (!metadata?.kiloSessionId) return null;
return this.eventQueries.getLatestAssistantMessage(sessionId, metadata.kiloSessionId);
}

/**
* Update session metadata with validation.
* Throws an error if validation fails.
Expand Down
150 changes: 148 additions & 2 deletions services/cloud-agent-next/src/router.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,12 @@ import type { TRPCContext, SessionId } from './types.js';
import type { CloudAgentSessionState } from './persistence/types.js';

type MockSessionStub = {
deleteSession: ReturnType<typeof vi.fn>;
markAsInterrupted: ReturnType<typeof vi.fn>;
deleteSession?: ReturnType<typeof vi.fn>;
markAsInterrupted?: ReturnType<typeof vi.fn>;
getMetadata?: ReturnType<typeof vi.fn>;
getActiveExecutionId?: ReturnType<typeof vi.fn>;
getExecution?: ReturnType<typeof vi.fn>;
getLatestAssistantMessage?: ReturnType<typeof vi.fn>;
};

type MockCAS = {
Expand Down Expand Up @@ -892,5 +896,147 @@ describe('router sessionId validation', () => {
});
});
});

describe('getLatestAssistantMessage procedure', () => {
let mockContext: TRPCContext;
let caller: ReturnType<typeof appRouter.createCaller>;
let cloudAgentSession: MockCAS;
let mockGetMetadata: ReturnType<typeof vi.fn>;
let mockGetLatestAssistantMessage: ReturnType<typeof vi.fn>;

beforeEach(() => {
vi.clearAllMocks();

mockGetMetadata = vi.fn();
mockGetLatestAssistantMessage = vi.fn();

mockContext = {
userId: 'test-user-123',
authToken: 'test-token',
botId: undefined,
request: {} as Request,
env: {
Sandbox: {} as TRPCContext['env']['Sandbox'],
SandboxSmall: {} as TRPCContext['env']['SandboxSmall'],
CLOUD_AGENT_SESSION: {
idFromName: vi.fn((id: string) => ({ id })),
get: vi.fn(() => ({
getMetadata: mockGetMetadata,
getLatestAssistantMessage: mockGetLatestAssistantMessage,
})),
} as unknown as TRPCContext['env']['CLOUD_AGENT_SESSION'],
SESSION_INGEST: {
fetch: vi.fn(),
} as unknown as TRPCContext['env']['SESSION_INGEST'],
R2_BUCKET: {} as TRPCContext['env']['R2_BUCKET'],
NEXTAUTH_SECRET: 'test-secret',
INTERNAL_API_SECRET_PROD: {
get: vi.fn().mockResolvedValue('test-secret'),
} as unknown as TRPCContext['env']['INTERNAL_API_SECRET_PROD'],
},
};
cloudAgentSession = mockContext.env.CLOUD_AGENT_SESSION as unknown as MockCAS;
caller = appRouter.createCaller(mockContext);
});

it('should return the latest assistant message for the owner', async () => {
const sessionId: SessionId = 'agent_55555555-5555-5555-5555-555555555555';
mockGetMetadata.mockResolvedValue({
version: 123456789,
sessionId,
userId: 'test-user-123',
timestamp: 123456789,
kiloSessionId: 'ses_00000000000000000000000001',
} satisfies CloudAgentSessionState);
mockGetLatestAssistantMessage.mockResolvedValue({
eventId: 12,
timestamp: 1700000000000,
info: {
id: 'msg_00000000000000000000000001',
role: 'assistant',
sessionID: 'ses_00000000000000000000000001',
},
parts: [
{
id: 'part_00000000000000000000000001',
messageID: 'msg_00000000000000000000000001',
type: 'text',
text: 'Done',
},
],
});

const result = await caller.getLatestAssistantMessage({ cloudAgentSessionId: sessionId });

expect(result).toEqual({
cloudAgentSessionId: sessionId,
message: {
eventId: 12,
timestamp: 1700000000000,
info: {
id: 'msg_00000000000000000000000001',
role: 'assistant',
sessionID: 'ses_00000000000000000000000001',
},
parts: [
{
id: 'part_00000000000000000000000001',
messageID: 'msg_00000000000000000000000001',
type: 'text',
text: 'Done',
},
],
},
});
expect(cloudAgentSession.idFromName).toHaveBeenCalledWith(`test-user-123:${sessionId}`);
expect(mockGetLatestAssistantMessage).toHaveBeenCalled();
});

it('should return null when the session has no assistant messages', async () => {
const sessionId: SessionId = 'agent_66666666-6666-6666-6666-666666666666';
mockGetMetadata.mockResolvedValue({
version: 123456789,
sessionId,
userId: 'test-user-123',
timestamp: 123456789,
kiloSessionId: 'ses_00000000000000000000000001',
} satisfies CloudAgentSessionState);
mockGetLatestAssistantMessage.mockResolvedValue(null);

await expect(
caller.getLatestAssistantMessage({ cloudAgentSessionId: sessionId })
).resolves.toEqual({
cloudAgentSessionId: sessionId,
message: null,
});
});

it('should return NOT_FOUND for a missing session', async () => {
const sessionId: SessionId = 'agent_77777777-7777-7777-7777-777777777777';
mockGetMetadata.mockResolvedValue(null);

await expect(
caller.getLatestAssistantMessage({ cloudAgentSessionId: sessionId })
).rejects.toThrow('Session not found');
expect(mockGetLatestAssistantMessage).not.toHaveBeenCalled();
});

it('should require authentication', async () => {
const unauthenticatedContext: TRPCContext = {
userId: undefined,
authToken: undefined,
botId: undefined,
env: mockContext.env,
} as unknown as TRPCContext;

const unauthenticatedCaller = appRouter.createCaller(unauthenticatedContext);

await expect(
unauthenticatedCaller.getLatestAssistantMessage({
cloudAgentSessionId: 'agent_12345678-1234-1234-1234-123456789abc',
})
).rejects.toThrow('Authentication required');
});
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ import {
import { cleanupWorkspace, getSessionWorkspacePath, getSessionHomePath } from '../../workspace.js';
import { withDORetry } from '../../utils/do-retry.js';
import { protectedProcedure, publicProcedure, internalApiProtectedProcedure } from '../auth.js';
import { sessionIdSchema, GetSessionInput, GetSessionOutput } from '../schemas.js';
import {
sessionIdSchema,
GetSessionInput,
GetSessionOutput,
GetLatestAssistantMessageInput,
GetLatestAssistantMessageOutput,
} from '../schemas.js';
import { computeExecutionHealth } from '../../core/execution.js';

/**
Expand Down Expand Up @@ -448,6 +454,43 @@ export function createSessionManagementHandlers() {
});
}),

getLatestAssistantMessage: protectedProcedure
.input(GetLatestAssistantMessageInput)
.output(GetLatestAssistantMessageOutput)
.query(async ({ input, ctx }) => {
return withLogTags({ source: 'getLatestAssistantMessage' }, async () => {
const sessionId = input.cloudAgentSessionId as SessionId;
const { userId, env } = ctx;

logger.setTags({ userId, sessionId });
logger.info('Fetching latest assistant message');

const doKey = `${userId}:${sessionId}`;
const getStub = () =>
env.CLOUD_AGENT_SESSION.get(env.CLOUD_AGENT_SESSION.idFromName(doKey));

const metadata = await withDORetry(getStub, s => s.getMetadata(), 'getMetadata');
if (!metadata) {
logger.info('Session not found');
throw new TRPCError({
code: 'NOT_FOUND',
message: 'Session not found',
});
}

const message = await withDORetry(
getStub,
s => s.getLatestAssistantMessage(),
'getLatestAssistantMessage'
);

return {
cloudAgentSessionId: sessionId,
message,
};
});
}),

/**
* Get all log files and running processes for a session's sandbox.
*
Expand Down
32 changes: 32 additions & 0 deletions services/cloud-agent-next/src/router/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,6 +407,38 @@ export const GetSessionOutput = z.object({

export type GetSessionResponse = z.infer<typeof GetSessionOutput>;

export const GetLatestAssistantMessageInput = z.object({
cloudAgentSessionId: sessionIdSchema.describe('Cloud-agent session ID to inspect'),
});

export const AssistantMessageInfoSchema = z
.object({
id: z.string().describe('Assistant message ID'),
role: z.literal('assistant'),
})
.passthrough();

export const AssistantMessagePartSchema = z
.object({
id: z.string().describe('Message part ID'),
messageID: z.string().describe('Parent message ID'),
})
.passthrough();

export const LatestAssistantMessageSchema = z.object({
eventId: z.number().describe('Stored event ID for the message.updated event'),
timestamp: z.number().describe('Stored event timestamp in milliseconds'),
info: AssistantMessageInfoSchema,
parts: z.array(AssistantMessagePartSchema),
});

export const GetLatestAssistantMessageOutput = z.object({
cloudAgentSessionId: sessionIdSchema,
message: LatestAssistantMessageSchema.nullable(),
});

export type GetLatestAssistantMessageResponse = z.infer<typeof GetLatestAssistantMessageOutput>;

/**
* Response schema for V2 execution endpoints.
* Returns acknowledgment when execution has started.
Expand Down
Loading
Loading