1- import { Agent , AgentContext , Connection } from 'agents' ;
1+ import { Agent , AgentContext , Connection , ConnectionContext } from 'agents' ;
22import {
33 Blueprint ,
44 PhaseConceptGenerationSchemaType ,
@@ -12,7 +12,7 @@ import { GitHubExportResult } from '../../services/github/types';
1212import { CodeGenState , CurrentDevState , MAX_PHASES } from './state' ;
1313import { AllIssues , AgentSummary , AgentInitArgs , PhaseExecutionResult , UserContext } from './types' ;
1414import { PREVIEW_EXPIRED_ERROR , WebSocketMessageResponses } from '../constants' ;
15- import { broadcastToConnections , handleWebSocketClose , handleWebSocketMessage } from './websocket' ;
15+ import { broadcastToConnections , handleWebSocketClose , handleWebSocketMessage , sendToConnection } from './websocket' ;
1616import { createObjectLogger , StructuredLogger } from '../../logger' ;
1717import { ProjectSetupAssistant } from '../assistants/projectsetup' ;
1818import { UserConversationProcessor , RenderToolCall } from '../operations/UserConversationProcessor' ;
@@ -82,6 +82,7 @@ export class SimpleCodeGeneratorAgent extends Agent<Env, CodeGenState> {
8282 protected deploymentManager ! : DeploymentManager ;
8383
8484 private previewUrlCache : string = '' ;
85+ private templateDetailsCache : TemplateDetails | null = null ;
8586
8687 // In-memory storage for user-uploaded images (not persisted in DO state)
8788 private pendingUserImages : ProcessedImageAttachment [ ] = [ ]
@@ -131,7 +132,7 @@ export class SimpleCodeGeneratorAgent extends Agent<Env, CodeGenState> {
131132 generatedFilesMap : { } ,
132133 agentMode : 'deterministic' ,
133134 sandboxInstanceId : undefined ,
134- templateDetails : { } as TemplateDetails ,
135+ templateName : '' ,
135136 commandsHistory : [ ] ,
136137 lastPackageJson : '' ,
137138 pendingUserInputs : [ ] ,
@@ -160,7 +161,7 @@ export class SimpleCodeGeneratorAgent extends Agent<Env, CodeGenState> {
160161 ) ;
161162
162163 // Initialize FileManager
163- this . fileManager = new FileManager ( this . stateManager ) ;
164+ this . fileManager = new FileManager ( this . stateManager , ( ) => this . getTemplateDetails ( ) ) ;
164165
165166 // Initialize DeploymentManager first (manages sandbox client caching)
166167 // DeploymentManager will use its own getClient() override for caching
@@ -212,12 +213,14 @@ export class SimpleCodeGeneratorAgent extends Agent<Env, CodeGenState> {
212213 } )
213214
214215 const packageJson = templateInfo . templateDetails ?. allFiles [ 'package.json' ] ;
216+
217+ this . templateDetailsCache = templateInfo . templateDetails ;
215218
216219 this . setState ( {
217220 ...this . initialState ,
218221 query,
219222 blueprint,
220- templateDetails : templateInfo . templateDetails ,
223+ templateName : templateInfo . templateDetails . name ,
221224 sandboxInstanceId : undefined ,
222225 generatedPhases : [ ] ,
223226 commandsHistory : [ ] ,
@@ -253,7 +256,59 @@ export class SimpleCodeGeneratorAgent extends Agent<Env, CodeGenState> {
253256
254257 async isInitialized ( ) {
255258 return this . getAgentId ( ) ? true : false
256- }
259+ }
260+
261+ async onStart ( _props ?: Record < string , unknown > | undefined ) : Promise < void > {
262+ this . logger ( ) . info ( `Agent ${ this . getAgentId ( ) } session: ${ this . state . sessionId } onStart` ) ;
263+ // Ignore if agent not initialized
264+ if ( ! this . isInitialized ( ) ) {
265+ this . logger ( ) . info ( `Agent ${ this . getAgentId ( ) } session: ${ this . state . sessionId } not initialized, ignoring onStart` ) ;
266+ return ;
267+ }
268+ this . logger ( ) . info ( `Agent ${ this . getAgentId ( ) } session: ${ this . state . sessionId } onStart being processed` ) ;
269+ // Fill the template cache
270+ await this . ensureTemplateDetails ( ) ;
271+ this . logger ( ) . info ( `Agent ${ this . getAgentId ( ) } session: ${ this . state . sessionId } onStart processed successfully` ) ;
272+ }
273+
274+ onStateUpdate ( _state : CodeGenState , _source : "server" | Connection ) { }
275+
276+ setState ( state : CodeGenState ) : void {
277+ try {
278+ super . setState ( state ) ;
279+ } catch ( error ) {
280+ this . broadcastError ( "Error setting state" , error ) ;
281+ this . logger ( ) . error ( "State details:" , {
282+ originalState : JSON . stringify ( this . state , null , 2 ) ,
283+ newState : JSON . stringify ( state , null , 2 )
284+ } ) ;
285+ }
286+ }
287+
288+ onConnect ( connection : Connection , ctx : ConnectionContext ) {
289+ this . logger ( ) . info ( `Agent connected for agent ${ this . getAgentId ( ) } ` , { connection, ctx } ) ;
290+ sendToConnection ( connection , 'agent_connected' , {
291+ state : this . state ,
292+ templateDetails : this . getTemplateDetails ( )
293+ } ) ;
294+ }
295+
296+ async ensureTemplateDetails ( ) {
297+ if ( ! this . templateDetailsCache ) {
298+ this . logger ( ) . info ( `Template details being cached for template: ${ this . state . templateName } ` ) ;
299+ const results = await BaseSandboxService . getTemplateDetails ( this . state . templateName ) ;
300+ if ( ! results . success || ! results . templateDetails ) {
301+ throw new Error ( `Failed to get template details for template: ${ this . state . templateName } ` ) ;
302+ }
303+ this . templateDetailsCache = results . templateDetails ;
304+ this . logger ( ) . info ( `Template details for template: ${ this . state . templateName } cached successfully` ) ;
305+ }
306+ return this . templateDetailsCache ;
307+ }
308+
309+ private getTemplateDetails ( ) {
310+ return this . templateDetailsCache ! ;
311+ }
257312
258313 /*
259314 * Each DO has 10 gb of sqlite storage. However, the way agents sdk works, it stores the 'state' object of the agent as a single row
@@ -333,20 +388,6 @@ export class SimpleCodeGeneratorAgent extends Agent<Env, CodeGenState> {
333388 } ) ;
334389 this . logger ( ) . info ( `Agent initialized successfully for agent ${ this . state . inferenceContext . agentId } ` ) ;
335390 }
336-
337- onStateUpdate ( _state : CodeGenState , _source : "server" | Connection ) { }
338-
339- setState ( state : CodeGenState ) : void {
340- try {
341- super . setState ( state ) ;
342- } catch ( error ) {
343- this . broadcastError ( "Error setting state" , error ) ;
344- this . logger ( ) . error ( "State details:" , {
345- originalState : JSON . stringify ( this . state , null , 2 ) ,
346- newState : JSON . stringify ( state , null , 2 )
347- } ) ;
348- }
349- }
350391
351392 getPreviewUrlCache ( ) {
352393 return this . previewUrlCache ;
@@ -359,7 +400,7 @@ export class SimpleCodeGeneratorAgent extends Agent<Env, CodeGenState> {
359400 agentId : this . getAgentId ( ) ,
360401 query : this . state . query ,
361402 blueprint : this . state . blueprint ,
362- template : this . state . templateDetails ,
403+ template : this . getTemplateDetails ( ) ,
363404 inferenceContext : this . state . inferenceContext
364405 } ) ;
365406 }
0 commit comments