-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCommandHandler.R
More file actions
356 lines (319 loc) · 9.43 KB
/
CommandHandler.R
File metadata and controls
356 lines (319 loc) · 9.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
source("MessageTranscoder.R")
# load the commands
CommandHandler <- R6Class(
"CommandHandler",
public = list(
config = NULL,
commands = NULL,
commandList = NULL,
commandNames = NULL,
workingDir = "",
commandFiles = NULL,
commandEncoding = NULL,
transcoders = list(),
initialize = function(config) {
self$config <- config
self$workingDir <- paste0(
config$runtimeDirPrefix,"/",
config$aiName
)
self$commandEncoding = config$commandEncoding
self$commandNames <- config$commands
self$commandFiles <- paste0(self$commandNames,".cmd.R")
# create directory if necessary
if(!dir.exists(self$workingDir)) {
dir.create(self$workingDir)
}
# clean the directory if asked to in the config
if(config$cleanWorkingDir==T) {
for(f in list.files(self$workingDir)) {
file.remove(paste0(self$workingDir,"/",f))
}
}
# copy the base commands into the runtime dir
for(fn in self$commandFiles) {
fromFN <- paste0("commands/",fn)
toFN <- self$workingDir
file.copy(fromFN,toFN,overwrite=T)
}
# load the commmands
self$loadCommands()
# load the command transcoders
self$loadTranscoders()
},
loadCommands = function() {
self$commands <- lapply(self$commandNames,function(cmdName) {
fn <- paste0(cmdName,".cmd.R")
source(paste0(self$workingDir,"/",fn))
file_content <- get(paste0("command_",cmdName))
sc <- list()
sc[[cmdName]] <- file_content
get(paste0("command_",cmdName))
})
names(self$commands) <- self$commandNames
self$commandList <- lapply(self$commands,function(cmd) {
cmd$usage
})
},
loadTranscoders = function() {
for(fn in list.files("transcoders")) {
# source file
source(paste0("transcoders/",fn))
# initialize
constructor <- paste0(gsub("\\.R","",fn),"$new()")
trans <- eval(str2expression(constructor))
self$transcoders[[trans$name]] <- trans
}
},
# determines if a message is valid or not
# returns a list because we might want to
# add additional things in here in the future
validate = function(msg,agent) {
notValid <- list(isValid=F,setFrom=F)
isValid <- list(isValid=T,setFrom=F)
if(is.null(msg)) {
notValid$error <- "Null command"
return(notValid)
}
if(is.null(msg$action)) {
notValid$error <- "Missing action param"
return(notValid)
}
# check action exists
actionExists <- msg$action %in% self$commandNames
if(!actionExists) {
notValid$error <- paste0("Invalid action: \"",msg$action,"\"")
return(notValid)
}
# check that the parameters defined for this
# action are provided
actionCmd <- self$commands[[msg$action]]
paramsProvided <- names(msg)
paramsRequired <- names(actionCmd$usage)
paramsRequired <- paramsRequired[paramsRequired!="comment"]
errorMsg <- NULL
for(param in names(paramsRequired)) {
if(!param %in% paramsProvided) {
errorMsg <- paste0(errorMsg,"parameter \"",param,"\" missing ")
}
}
if(!is.null(errorMsg)) {
notValid$error <- errorMsg
return(notValid)
}
# check that the message has a "from" field
# this isn't mandatory because we can fill
# this in here (only an agent wouldn't set it)
if(is.null(msg$from)) {
# we passed msg by value so we can't change
# it so we add a flag to isValid so in
# the event the rest of the validation
# passes, we can check it in commandhandler
# messy, should make msg an object
isValid$setFrom <- T
}
# check src and destination for chat msg
if(msg$action=="chat") {
# the src id should match the sending agent
# unless it's me h0 as I can impersonate
if(msg$from!=agent$id & agent$id!="h0") {
notValid$error <- paste0("impersonation: from id: \"",msg$from,"\" does not match sending agent id: \"",agent$id,"\"")
return(notValid)
}
# check separately if someone is trying
# to chat with the controller
if(msg$to=="C0") {
notValid$error <- "You cannot \"chat\" with C0, only send normal commands"
return(notValid)
}
# finally check the "to" agent exists
validToIDs <- names(agentManager$agents)
if(! msg$to %in% validToIDs) {
notValid$error <- paste0("to: \"",msg$to,"\" does not exist.")
return(notValid)
}
}
isValid
},
# this receives an encoded message from any agent
# and must attempt to decode the message and
# properly handle it
handleCommand = function(rawMsg,agent,validate=T) {
# attempt to decode the message
cmdDecoded <- self$decodeCommand(rawMsg)
# if we cannot decode
if(!cmdDecoded$success) {
# gpt3.5 often sends poorly formatted
# messages that do not decode
# we try and figure out who the message
# was supposed to goto, should be a
# record of it in the agent's messages
cmdDecoded <- list(msg=list(
from=agent$id,
to=agent$lastChatPartner,
action="chat",
msg=rawMsg
))
}
# attempt to validate the command
if(validate) {
msgValidation <- self$validate(cmdDecoded$msg,agent)
# check if we need to set from field,
# should probably make a MSG an object
# so that validate can do this itself
if(msgValidation$setFrom) {
cmdDecoded$msg$from <- agent$id
}
} else {
msgValidation <- list(isValid=T)
}
# if the message is not valid
if(!msgValidation$isValid) {
response <- list(
action="error",
error=msgValidation$error
)
print("invalid message:")
# we can still print invalid commands
# as they are already parsed by the
# transcoder
#self$printMsg(cmdDecoded)
# send the "error" action to be executed
return(self$execute(response,agent))
}
# if the AI is trying to chat to us, we
# don't want to ask permission for that
#self$printMsg(cmdDecoded$msg)
#print("You may need to press enter to see prompt if not shown below")
# do not as for permission if in continous mode
if(config$continuous) {
# execute the message
return(self$execute(cmdDecoded$msg,agent))
}
permission <- agentManager$primaryHuman$askPermission(cmdDecoded)
if(permission$choice=="c") {
return(self$execute(cmdDecoded$msg,agent))
} else if(permission$choice=="q") {
response <- list(
action="exit"
)
return(self$execute(response,agent))
} else if(permission$choice=="i") {
# respond the interaction
response <- list(
action="interaction",
msg=permission$msg
)
return(self$execute(response,agent))
}
},
execute = function(cmdMsg,agent) {
self$printMsg(cmdMsg)
# if we are asked to exit, do so
if(cmdMsg$action=="exit") {
return()
}
# check if command was an "error" response
if(cmdMsg$action=="error") {
response <- list(
from="C0",
to=agent$id,
action="chat",
msg=cmdMsg$error
)
# send token count if enabled
if(config$trackTokens) {
response$tokens_used <- agent$tokensUsed
}
#encResponse <- commandHandler$encodeCommand(
# response
#)
return(self$execute(response,agent))
#return(commandHandler$handleCommand(encResponse,agent,validate=F))
}
if(cmdMsg$action=="interaction") {
response <- list(
from="h0",
to=agent$id,
action="chat",
msg=cmdMsg$msg
)
# send token count if enabled
if(config$trackTokens) {
response$tokens_used <- agent$tokensUsed
}
return(self$execute(response,agent))
}
# call the command
validate <- T
r <- self$commands[[cmdMsg$action]]$f(cmdMsg)
# if a null response was obtained do nothing
# this is used by commands that themselves
# call the commandHandler to return a msg
if(is.null(r)) {
return()
}
# if our request was not a chat request
# we need to wrap the response in a chat
# request so it gets routed correctly
if(cmdMsg$action!="chat") {
res <- list(
from="C0",
to=agent$id,
action="chat",
msg=r
)
# send token count if enabled
if(config$trackTokens) {
res$tokens_used <- agent$tokensUsed
}
response <- commandHandler$encodeCommand(res)
# do not "validate" own commands
validate <- F
} else {
# chat just take the response
response <- r
}
# send token count if enabled
#if(config$trackTokens) {
# response$tokens_used <- agent$tokensUsed
#}
commandHandler$handleCommand(response,agent,validate)
},
getANSIColor = function(colorNum) {
sprintf("\033[38;5;%dm", colorNum)
},
printField = function(name,value,color) {
cat(color,name,' : ',commandHandler$encodeCommand(value),'\033[0m\n',sep="")
},
printMsg = function(msg) {
commentColor <- "\033[38;5;93m"
paramColor <- "\033[38;5;42m"
actionColor <- "\033[38;5;214m"
# create a default
cmd <- self$commands[[msg$action]]
if("printMsg" %in% names(cmd)) {
# print method override
cmd$printMsg(msg)
} else {
# default print method
self$printField("action",msg$action,actionColor)
paramNames <- names(msg)[!names(msg) %in% c("action","comment")]
# print params
for(p in paramNames) {
self$printField(p,msg[[p]],paramColor)
}
self$printField("comment",msg$comment,commentColor)
}
flush.console()
},
# encodes a command in the specified command format
encodeCommand = function(msg,fmt=self$commandEncoding) {
self$transcoders[[fmt]]$encode(msg)
},
# encodes a command in the specified command format
decodeCommand = function(msg,fmt=self$commandEncoding) {
self$transcoders[[fmt]]$decode(msg)
}
)
)