-
Notifications
You must be signed in to change notification settings - Fork 3.7k
feat(pi): add BYOK Exa search to Create PR #5924
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
BillLeoutsakosvl346
wants to merge
3
commits into
staging
Choose a base branch
from
feature/pi-exa
base: staging
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| name: Pi Search Staging Smoke | ||
|
|
||
| on: | ||
| workflow_dispatch: | ||
|
|
||
| permissions: | ||
| contents: read | ||
|
|
||
| jobs: | ||
| smoke: | ||
| name: Verify deployed Pi search boundary | ||
| runs-on: ubuntu-latest | ||
| environment: staging | ||
| steps: | ||
| - name: Checkout code | ||
| uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6 | ||
|
|
||
| - name: Setup Bun | ||
| uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 | ||
| with: | ||
| bun-version: 1.3.13 | ||
|
|
||
| - name: Install dependencies | ||
| run: bun install --frozen-lockfile | ||
|
|
||
| - name: Run remote Pi search smoke | ||
| env: | ||
| E2B_API_KEY: ${{ secrets.E2B_API_KEY }} | ||
| E2B_PI_TEMPLATE_ID: ${{ secrets.E2B_PI_TEMPLATE_ID }} | ||
| INTERNAL_API_SECRET: ${{ secrets.INTERNAL_API_SECRET }} | ||
| PI_EXA_BROKER_BASE_URL: ${{ vars.PI_EXA_BROKER_BASE_URL }} | ||
| PI_SEARCH_SMOKE_CAPABILITY: ${{ secrets.PI_SEARCH_SMOKE_CAPABILITY }} | ||
| run: bun run ./apps/sim/scripts/check-pi-sandbox-contract.ts --remote |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
apps/sim/app/api/cron/cleanup-pi-search-capabilities/route.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { createLogger } from '@sim/logger' | ||
| import { getErrorMessage } from '@sim/utils/errors' | ||
| import { generateShortId } from '@sim/utils/id' | ||
| import { type NextRequest, NextResponse } from 'next/server' | ||
| import { cleanupPiSearchCapabilitiesContract } from '@/lib/api/contracts/pi-search-cleanup' | ||
| import { parseRequest } from '@/lib/api/server' | ||
| import { verifyCronAuth } from '@/lib/auth/internal' | ||
| import { acquireLock, releaseLock } from '@/lib/core/config/redis' | ||
| import { withRouteHandler } from '@/lib/core/utils/with-route-handler' | ||
| import { cleanupExpiredPiSearchCapabilities } from '@/lib/pi/exa-search/capabilities' | ||
|
|
||
| const logger = createLogger('PiSearchCapabilityCleanup') | ||
| const LOCK_KEY = 'pi-search-capability-cleanup' | ||
| const LOCK_TTL_SECONDS = 120 | ||
| const BATCH_SIZE = 1_000 | ||
| const RETENTION_MS = 24 * 60 * 60 * 1000 | ||
|
|
||
| export const GET = withRouteHandler(async (request: NextRequest) => { | ||
| const authError = verifyCronAuth(request, 'Pi search capability cleanup') | ||
| if (authError) return authError | ||
| const parsed = await parseRequest(cleanupPiSearchCapabilitiesContract, request, {}) | ||
| if (!parsed.success) return parsed.response | ||
| const requestId = generateShortId() | ||
| if (!(await acquireLock(LOCK_KEY, requestId, LOCK_TTL_SECONDS))) { | ||
| return NextResponse.json({ success: true, skipped: true }, { status: 202 }) | ||
| } | ||
|
|
||
| try { | ||
| const deleted = await cleanupExpiredPiSearchCapabilities({ | ||
| batchSize: BATCH_SIZE, | ||
| retentionBefore: new Date(Date.now() - RETENTION_MS), | ||
| }) | ||
| return NextResponse.json({ success: true, deleted }) | ||
| } catch (error) { | ||
| const message = getErrorMessage(error, 'Capability cleanup failed') | ||
| logger.error('Pi search capability cleanup failed', { requestId, error: message }) | ||
| return NextResponse.json({ success: false, error: message }, { status: 500 }) | ||
| } finally { | ||
| await releaseLock(LOCK_KEY, requestId).catch(() => {}) | ||
| } | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,147 @@ | ||
| /** | ||
| * @vitest-environment node | ||
| */ | ||
|
|
||
| import { NextRequest } from 'next/server' | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { | ||
| mockAuthenticate, | ||
| mockReserve, | ||
| mockSettle, | ||
| mockRelease, | ||
| mockLeaseCurrent, | ||
| mockContainsSecret, | ||
| mockResolveByok, | ||
| mockExecuteSearch, | ||
| } = vi.hoisted(() => ({ | ||
| mockAuthenticate: vi.fn(), | ||
| mockReserve: vi.fn(), | ||
| mockSettle: vi.fn(), | ||
| mockRelease: vi.fn(), | ||
| mockLeaseCurrent: vi.fn(), | ||
| mockContainsSecret: vi.fn(), | ||
| mockResolveByok: vi.fn(), | ||
| mockExecuteSearch: vi.fn(), | ||
| })) | ||
|
|
||
| vi.mock('@/lib/pi/exa-search/capabilities', () => ({ | ||
| authenticatePiSearchCapability: mockAuthenticate, | ||
| reservePiSearchCall: mockReserve, | ||
| settlePiSearchCall: mockSettle, | ||
| releasePiSearchCall: mockRelease, | ||
| isPiSearchLeaseCurrent: mockLeaseCurrent, | ||
| queryContainsProtectedSecret: mockContainsSecret, | ||
| })) | ||
| vi.mock('@/lib/api-key/byok', () => ({ resolveBYOKKeyById: mockResolveByok })) | ||
| vi.mock('@/tools/exa/search-client', () => ({ executePiExaSearch: mockExecuteSearch })) | ||
|
|
||
| import { POST } from '@/app/api/internal/pi/exa-search/route' | ||
|
|
||
| function request(body: unknown, token = 'capability-token') { | ||
| return new NextRequest('http://localhost/api/internal/pi/exa-search', { | ||
| method: 'POST', | ||
| headers: { | ||
| authorization: `Bearer ${token}`, | ||
| 'content-type': 'application/json', | ||
| }, | ||
| body: JSON.stringify(body), | ||
| }) | ||
| } | ||
|
|
||
| describe('Pi Exa search broker', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| mockAuthenticate.mockResolvedValue({ | ||
| id: 'cap-1', | ||
| workspaceId: 'workspace-1', | ||
| providerKeyId: 'exa-key-id', | ||
| executionId: 'execution-1', | ||
| expiresAt: new Date(Date.now() + 60_000), | ||
| secretFingerprints: [], | ||
| }) | ||
| mockContainsSecret.mockReturnValue(false) | ||
| mockReserve.mockResolvedValue({ | ||
| capabilityId: 'cap-1', | ||
| token: 'lease', | ||
| generation: 1, | ||
| workspaceId: 'workspace-1', | ||
| executionId: 'execution-1', | ||
| expiresAt: new Date(Date.now() + 30_000), | ||
| }) | ||
| mockResolveByok.mockResolvedValue({ | ||
| status: 'found', | ||
| value: { apiKey: 'exa-user-key', isBYOK: true, keyId: 'exa-key-id' }, | ||
| }) | ||
| mockExecuteSearch.mockResolvedValue({ | ||
| results: [{ title: 'Docs', url: 'https://example.com', snippet: 'text' }], | ||
| }) | ||
| mockSettle.mockResolvedValue(true) | ||
| mockRelease.mockResolvedValue(true) | ||
| mockLeaseCurrent.mockResolvedValue(true) | ||
| }) | ||
|
|
||
| it('authenticates before accepting the request body', async () => { | ||
| mockAuthenticate.mockResolvedValue(null) | ||
| const response = await POST(request({ query: 'x'.repeat(10_000) }), {} as never) | ||
| expect(response.status).toBe(401) | ||
| expect(mockReserve).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('uses the workspace BYOK key and returns the bounded result', async () => { | ||
| const response = await POST(request({ query: 'latest docs', numResults: 3 }), {} as never) | ||
| expect(response.status).toBe(200) | ||
| expect(mockResolveByok).toHaveBeenCalledWith('workspace-1', 'exa', 'exa-key-id') | ||
| expect(mockExecuteSearch).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| apiKey: 'exa-user-key', | ||
| query: 'latest docs', | ||
| numResults: 3, | ||
| }) | ||
| ) | ||
| expect(await response.json()).toEqual({ | ||
| results: [{ title: 'Docs', url: 'https://example.com', snippet: 'text' }], | ||
| }) | ||
| }) | ||
|
|
||
| it('rejects protected query material before calling Exa', async () => { | ||
| mockContainsSecret.mockReturnValue(true) | ||
| const response = await POST(request({ query: 'leak this token' }), {} as never) | ||
| expect(response.status).toBe(400) | ||
| expect(mockReserve).not.toHaveBeenCalled() | ||
| expect(mockExecuteSearch).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('rejects fine-grained GitHub PAT patterns', async () => { | ||
| const response = await POST( | ||
| request({ query: 'search github_pat_abcdefghijklmnopqrstuvwxyz123456' }), | ||
| {} as never | ||
| ) | ||
| expect(response.status).toBe(400) | ||
| expect(mockReserve).not.toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('fails rather than falling back when workspace BYOK is missing', async () => { | ||
| mockResolveByok.mockResolvedValue({ status: 'missing' }) | ||
| const response = await POST(request({ query: 'latest docs' }), {} as never) | ||
| expect(response.status).toBe(412) | ||
| expect(mockExecuteSearch).not.toHaveBeenCalled() | ||
| expect(mockRelease).toHaveBeenCalled() | ||
| }) | ||
|
|
||
| it('rejects protected material returned by Exa before it reaches the agent', async () => { | ||
| mockExecuteSearch.mockResolvedValue({ | ||
| results: [ | ||
| { | ||
| title: 'leak', | ||
| url: 'https://example.com', | ||
| snippet: 'ghp_abcdefghijklmnopqrstuvwxyz123456', | ||
| }, | ||
| ], | ||
| }) | ||
| const response = await POST(request({ query: 'latest docs' }), {} as never) | ||
| expect(response.status).toBe(502) | ||
| expect(mockSettle).not.toHaveBeenCalled() | ||
| expect(mockRelease).toHaveBeenCalled() | ||
| }) | ||
| }) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.