Skip to content

An open-source, faster Devin alternative

TypeScript

Bind a findings document when launching a CVE swarm (?security=1)

Mohamed Habib via Computer4050d8d72465
diff --git a/web/src/managed-agents/Detail.tsx b/web/src/managed-agents/Detail.tsx
index 2e8fc4f1..e393a9e6 100644
--- a/web/src/managed-agents/Detail.tsx
+++ b/web/src/managed-agents/Detail.tsx
@@ -70,6 +70,7 @@ import {
type ManagedAgentSessionSummary,
type ManagedAgentSummary,
type ManagedProjectOverview,
+ type ManagedSessionMemoryBindingInput,
} from './api'
import { ManagedAgentChatTransport } from './chat-transport'
import { useLiveSessionEvents } from './use-live-session-events'
@@ -112,6 +113,7 @@ import { AgentMarkdown } from './AgentMarkdown'
import { projectAgentPreviewReady } from './preview-state'
import {
projectCloneCommand,
+ templateFirstRunMemory,
templateFirstRunPrompt,
} from './template-continuation'
@@ -274,6 +276,7 @@ function PlaygroundChat({
session,
events,
initialPrompt,
+ initialMemory,
onInitialPromptConsumed,
onSessionFinished,
}: {
@@ -282,6 +285,7 @@ function PlaygroundChat({
session?: ManagedAgentSession
events: ManagedAgentEvent[]
initialPrompt?: string
+ initialMemory?: Record<string, ManagedSessionMemoryBindingInput>
onInitialPromptConsumed?: () => void
onSessionFinished?: (sessionId: string) => void
}) {
@@ -301,14 +305,19 @@ function PlaygroundChat({
() => historicalMessages(session, events),
[events, session],
)
+ // Bindings are fixed when the session is created, so capture them once; the
+ // security launch clears its navigation state right after the first send.
+ const [memoryBinding] = useState(() => initialMemory)
const transport = useMemo(
() =>
new ManagedAgentChatTransport(
agentId,
startingSessionId,
setLiveSessionId,
+ {},
+ memoryBinding,
),
- [agentId, startingSessionId],
+ [agentId, startingSessionId, memoryBinding],
)
const debugEvents = useQuery({
queryKey: ['managed-agent-session-events', liveSessionId],
@@ -679,6 +688,7 @@ export default function ManagedAgentDetail({
const playgroundAlias = previewAlias ?? environment
const requestedPlaygroundId = playgroundSessionIdFromSearch(location.search)
const firstRunPrompt = templateFirstRunPrompt(location.state)
+ const firstRunMemory = templateFirstRunMemory(location.state)
const [newSessionKey, setNewSessionKey] = useState(() => crypto.randomUUID())
const [adoptedPlaygroundId, setAdoptedPlaygroundId] = useState<string>()
const projectId = project?.project.id
@@ -1270,6 +1280,7 @@ export default function ManagedAgentDetail({
selectedPlaygroundEvents.data ?? EMPTY_MANAGED_AGENT_EVENTS
}
initialPrompt={firstRunPrompt}
+ initialMemory={firstRunMemory}
onInitialPromptConsumed={() => {
void navigate(
{ pathname: location.pathname, search: location.search },
diff --git a/web/src/managed-agents/api.ts b/web/src/managed-agents/api.ts
index 0c4eb7e1..6ecede71 100644
--- a/web/src/managed-agents/api.ts
+++ b/web/src/managed-agents/api.ts
@@ -2565,6 +2565,13 @@ async function waitForAgentEvent(
}
}
+/** One memory binding on session creation; see `POST /managed-agents/sessions`. */
+export type ManagedSessionMemoryBindingInput = {
+ scope: 'document' | 'collection'
+ id?: string
+ access?: 'read' | 'read-write'
+}
+
export async function runManagedAgent(
agentId: string,
input: string,
@@ -2572,13 +2579,19 @@ export async function runManagedAgent(
options: {
onSession?: (sessionId: string) => void
signal?: AbortSignal
+ memory?: Record<string, ManagedSessionMemoryBindingInput>
} = {},
) {
+ const hasMemory = options.memory && Object.keys(options.memory).length > 0
const created = await apiFetch(
'/managed-agents/sessions',
{
method: 'POST',
- body: JSON.stringify({ agentId, source: 'playground' }),
+ body: JSON.stringify({
+ agentId,
+ source: 'playground',
+ ...(hasMemory ? { memory: options.memory } : {}),
+ }),
signal: options.signal,
},
sessionCreateSchema,
diff --git a/web/src/managed-agents/chat-transport.ts b/web/src/managed-agents/chat-transport.ts
index cfff94d7..1213d145 100644
--- a/web/src/managed-agents/chat-transport.ts
+++ b/web/src/managed-agents/chat-transport.ts
@@ -3,6 +3,7 @@ import {
continueManagedAgentSession,
runManagedAgent,
type ManagedAgentEvent,
+ type ManagedSessionMemoryBindingInput,
} from './api'
import { UIMessageChunkPacer, type ChunkPacerOptions } from './chunk-pacer'
@@ -38,6 +39,10 @@ export class ManagedAgentChatTransport implements ChatTransport<UIMessage> {
sessionId: string | undefined,
private readonly onSession: (sessionId: string) => void,
private readonly pacing: ChunkPacerOptions | false = {},
+ // Memory bindings for the session this transport creates on its first send.
+ // Bindings are fixed at creation, so they apply only when there is no
+ // sessionId yet; continuing a session ignores them.
+ private readonly memory?: Record<string, ManagedSessionMemoryBindingInput>,
) {
this.sessionId = sessionId
}
@@ -163,6 +168,7 @@ export class ManagedAgentChatTransport implements ChatTransport<UIMessage> {
)
: runManagedAgent(this.agentId, input, onEvent, {
signal: abortSignal,
+ memory: this.memory,
onSession: (sessionId) => {
this.sessionId = sessionId
this.onSession(sessionId)
diff --git a/web/src/managed-agents/security/SecurityOnboarding.tsx b/web/src/managed-agents/security/SecurityOnboarding.tsx
index 3f4e0f96..4a08468b 100644
--- a/web/src/managed-agents/security/SecurityOnboarding.tsx
+++ b/web/src/managed-agents/security/SecurityOnboarding.tsx
@@ -24,6 +24,7 @@ import { notifyError } from '@/lib/errors'
import {
addManagedGitHubConnection,
attachManagedGitHub,
+ createManagedMemoryDocument,
createManagedTemplateInstallation,
finalizeManagedTemplateInstallation,
getManagedGitHubConnections,
@@ -39,6 +40,7 @@ import {
composeLaunchPrompt,
DEFAULT_SWARM_MODEL,
SCAN_DECLARATION,
+ SECURITY_FINDINGS_RESOURCE,
SECURITY_SWARM_TEMPLATE_REPOSITORY,
SEED_CVES,
type SwarmPayload,
@@ -155,13 +157,41 @@ export default function SecurityOnboarding() {
onError: (error) => notifyError("Couldn't deploy the CVE Swarm.", error),
})
- function launch(payload: SwarmPayload) {
- const prompt = composeLaunchPrompt(payload)
- if (!deployed) return
- void navigate(templatePlaygroundPath(deployed), {
- state: { templateFirstRunPrompt: prompt },
- })
- }
+ // Launch binds a per-run findings document to the session it starts. The
+ // document must exist before the session, so a binding to a missing document
+ // fails admission; we PUT it first, then navigate with the binding in state
+ // for the playground to create the session with.
+ const launch = useMutation({
+ mutationFn: async (payload: SwarmPayload) => {
+ if (!deployed) throw new Error('Deploy the swarm before launching.')
+ const runId = `run-${crypto.randomUUID()}`
+ await createManagedMemoryDocument({
+ projectId: deployed.projectId,
+ resource: SECURITY_FINDINGS_RESOURCE,
+ environment: 'default',
+ id: runId,
+ title: `CVE swarm ${runId}`,
+ text: '{}',
+ })
+ return { prompt: composeLaunchPrompt(payload), runId }
+ },
+ onSuccess: ({ prompt, runId }) => {
+ if (!deployed) return
+ void navigate(templatePlaygroundPath(deployed), {
+ state: {
+ templateFirstRunPrompt: prompt,
+ templateFirstRunMemory: {
+ [SECURITY_FINDINGS_RESOURCE]: {
+ scope: 'document',
+ id: runId,
+ access: 'read-write',
+ },
+ },
+ },
+ })
+ },
+ onError: (error) => notifyError("Couldn't start the swarm.", error),
+ })
return (
<div className="mx-auto max-w-3xl px-4 py-10">
@@ -260,7 +290,11 @@ export default function SecurityOnboarding() {
title="Launch swarm from payload"
done={false}
>
- <PayloadBuilder canLaunch={!!deployed} onLaunch={launch} />
+ <PayloadBuilder
+ canLaunch={!!deployed}
+ launching={launch.isPending}
+ onLaunch={(payload) => launch.mutate(payload)}
+ />
</StepCard>
</div>
</div>
@@ -357,9 +391,11 @@ function StepCard({
function PayloadBuilder({
canLaunch,
+ launching,
onLaunch,
}: {
canLaunch: boolean
+ launching: boolean
onLaunch: (payload: SwarmPayload) => void
}) {
const [target, setTarget] = useState('')
@@ -520,10 +556,10 @@ function PayloadBuilder({
<div className="flex items-center gap-3">
<Button
- disabled={!ready || !canLaunch}
+ disabled={!ready || !canLaunch || launching}
onClick={() => onLaunch(payload)}
>
- <Radar />
+ {launching ? <Loader2 className="animate-spin" /> : <Radar />}
Launch swarm
</Button>
<Button
diff --git a/web/src/managed-agents/security/catalog.ts b/web/src/managed-agents/security/catalog.ts
index 25582de9..4445ae12 100644
--- a/web/src/managed-agents/security/catalog.ts
+++ b/web/src/managed-agents/security/catalog.ts
@@ -11,6 +11,11 @@ export const SECURITY_SWARM_TEMPLATE_REPOSITORY =
// Default model for the swarm. GLM via the org's model-access connection.
export const DEFAULT_SWARM_MODEL = 'GLM-5.3'
+// The document-memory resource the swarm writes its verdicts to. Must match the
+// `defineMemory` id in the template (agents/cve-swarm/memory/findings.ts); the
+// launch binds a per-run document under it so the run can persist findings.
+export const SECURITY_FINDINGS_RESOURCE = 'cve-findings'
+
// The attestation the operator must accept before a scan can launch. Recorded
// with the run; the scan stays passive in code regardless.
export const SCAN_DECLARATION =
@@ -98,8 +103,8 @@ export function composeLaunchPrompt(payload: SwarmPayload): string {
`Model: ${payload.model}`,
'',
payload.target
- ? 'Run scan_surface on the target to fingerprint it passively, then prove_reachability across the repository × CVE matrix, then report_findings once.'
- : 'Run prove_reachability across the repository × CVE matrix, then report_findings once.',
+ ? 'Run scan_surface on the target to fingerprint it passively, then prove reachability across the repository × CVE matrix by reading each clone, then save the findings once with memory_save.'
+ : 'Prove reachability across the repository × CVE matrix by reading each clone, then save the findings once with memory_save.',
'For any EXPOSED verdict, open_fix_pull_request (dependency-only, single pin). Honor PUBLISH_ENABLED — dry run unless it is enabled.',
].filter((line): line is string => line !== null)
return lines.join('\n')
diff --git a/web/src/managed-agents/template-continuation.ts b/web/src/managed-agents/template-continuation.ts
index 66e8e3a0..ecfc20e1 100644
--- a/web/src/managed-agents/template-continuation.ts
+++ b/web/src/managed-agents/template-continuation.ts
@@ -31,3 +31,36 @@ export function templateFirstRunPrompt(state: unknown): string | undefined {
const prompt = (state as Record<string, unknown>).templateFirstRunPrompt
return typeof prompt === 'string' && prompt.trim() ? prompt : undefined
}
+
+type MemoryBinding = {
+ scope: 'document' | 'collection'
+ id?: string
+ access?: 'read' | 'read-write'
+}
+
+/**
+ * Memory bindings a template launch asks the first playground session to be
+ * created with (navigation state, keyed by resource id). The CVE swarm launch
+ * binds its findings document here so the run can persist its verdicts; without
+ * a binding the agent's `useMemory` hook fails admission.
+ */
+export function templateFirstRunMemory(
+ state: unknown,
+): Record<string, MemoryBinding> | undefined {
+ if (!state || typeof state !== 'object') return undefined
+ const memory = (state as Record<string, unknown>).templateFirstRunMemory
+ if (!memory || typeof memory !== 'object') return undefined
+ const entries: Array<[string, MemoryBinding]> = []
+ for (const [resource, binding] of Object.entries(
+ memory as Record<string, unknown>,
+ )) {
+ if (!binding || typeof binding !== 'object') continue
+ const { scope, id, access } = binding as Record<string, unknown>
+ if (scope !== 'document' && scope !== 'collection') continue
+ const entry: MemoryBinding = { scope }
+ if (typeof id === 'string') entry.id = id
+ if (access === 'read' || access === 'read-write') entry.access = access
+ entries.push([resource, entry])
+ }
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined
+}