1
1
import express from "express" ;
2
2
import bodyParser from "body-parser" ;
3
3
import cors from "cors" ;
4
+ import path from "path" ;
5
+ import fs from "fs" ;
4
6
5
7
import {
6
8
type AgentRuntime ,
@@ -80,6 +82,16 @@ export function createApiRouter(
80
82
res . json ( { agents : agentsList } ) ;
81
83
} ) ;
82
84
85
+ router . get ( '/storage' , async ( req , res ) => {
86
+ try {
87
+ const uploadDir = path . join ( process . cwd ( ) , "data" , "characters" ) ;
88
+ const files = await fs . promises . readdir ( uploadDir ) ;
89
+ res . json ( { files } ) ;
90
+ } catch ( error ) {
91
+ res . status ( 500 ) . json ( { error : error . message } ) ;
92
+ }
93
+ } ) ;
94
+
83
95
router . get ( "/agents/:agentId" , ( req , res ) => {
84
96
const { agentId } = validateUUIDParams ( req . params , res ) ?? {
85
97
agentId : null ,
@@ -127,7 +139,7 @@ export function createApiRouter(
127
139
} ;
128
140
if ( ! agentId ) return ;
129
141
130
- const agent : AgentRuntime = agents . get ( agentId ) ;
142
+ let agent : AgentRuntime = agents . get ( agentId ) ;
131
143
132
144
// update character
133
145
if ( agent ) {
@@ -137,6 +149,9 @@ export function createApiRouter(
137
149
// if it has a different name, the agentId will change
138
150
}
139
151
152
+ // stores the json data before it is modified with added data
153
+ const characterJson = { ...req . body } ;
154
+
140
155
// load character from body
141
156
const character = req . body ;
142
157
try {
@@ -152,7 +167,7 @@ export function createApiRouter(
152
167
153
168
// start it up (and register it)
154
169
try {
155
- await directClient . startAgent ( character ) ;
170
+ agent = await directClient . startAgent ( character ) ;
156
171
elizaLogger . log ( `${ character . name } started` ) ;
157
172
} catch ( e ) {
158
173
elizaLogger . error ( `Error starting agent: ${ e } ` ) ;
@@ -162,6 +177,35 @@ export function createApiRouter(
162
177
} ) ;
163
178
return ;
164
179
}
180
+
181
+ if ( process . env . USE_CHARACTER_STORAGE === "true" ) {
182
+ try {
183
+ const filename = `${ agent . agentId } .json` ;
184
+ const uploadDir = path . join (
185
+ process . cwd ( ) ,
186
+ "data" ,
187
+ "characters"
188
+ ) ;
189
+ const filepath = path . join ( uploadDir , filename ) ;
190
+ await fs . promises . mkdir ( uploadDir , { recursive : true } ) ;
191
+ await fs . promises . writeFile (
192
+ filepath ,
193
+ JSON . stringify (
194
+ { ...characterJson , id : agent . agentId } ,
195
+ null ,
196
+ 2
197
+ )
198
+ ) ;
199
+ elizaLogger . info (
200
+ `Character stored successfully at ${ filepath } `
201
+ ) ;
202
+ } catch ( error ) {
203
+ elizaLogger . error (
204
+ `Failed to store character: ${ error . message } `
205
+ ) ;
206
+ }
207
+ }
208
+
165
209
res . json ( {
166
210
id : character . id ,
167
211
character : character ,
0 commit comments