-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm.lua
More file actions
executable file
·489 lines (433 loc) · 13.1 KB
/
Copy pathllm.lua
File metadata and controls
executable file
·489 lines (433 loc) · 13.1 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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/env lua
-- LLM Play Mode
-- Allows LLMs to interact with the game programmatically
--
-- Usage:
-- lua llm.lua --action "look" [--save savefile.sav] [--game zork1]
-- lua llm.lua --action "take sword" --save game.sav
-- lua llm.lua --new-game --save game.sav (start new game and save initial state)
--
-- Output: JSON with game response and state info
local runtime = require 'zilscript.runtime'
-- Parse command line arguments
local args = {}
local i = 1
while i <= #arg do
local a = arg[i]
if a == "--action" or a == "-a" then
i = i + 1
args.action = arg[i]
elseif a == "--save" or a == "-s" then
i = i + 1
args.savefile = arg[i]
elseif a == "--game" or a == "-g" then
i = i + 1
args.game = arg[i]
elseif a == "--new-game" then
args.new_game = true
elseif a == "--help" or a == "-h" then
args.help = true
end
i = i + 1
end
if args.help then
io.write([[
LLM Play Mode - Interact with ZIL games programmatically
Usage:
lua llm.lua --action "command" [options]
lua llm.lua --new-game [options]
Options:
--action, -a "cmd" Execute this command and exit
--save, -s file Restore from this memory dump file and keep action history in file.actions
--game, -g name Game to play (default: zork1)
--new-game Start a new game (even if save file exists)
--help, -h Show this help
Output: JSON with fields:
- ok: boolean (success)
- output: string (game response text)
- room: string (current room name, if available)
- savefile: string (path to saved state)
- historyfile: string (path to the action backlog)
- error: string (error message, if failed)
Examples:
lua llm.lua --new-game --save zork1.sav
lua llm.lua --action "look" --save zork1.sav
lua llm.lua --action "take lamp" --save zork1.sav
lua llm.lua --action "go north" --save zork1.sav
]])
os.exit(0)
end
-- Game configurations
local GAMES = {
zork1 = {
modules = {
"infocom.zork1.globals",
"infocom.zork1.clock",
"infocom.zork1.parser",
"infocom.zork1.verbs",
"infocom.zork1.actions",
"infocom.zork1.syntax",
"infocom.zork1.dungeon",
"infocom.zork1.main",
}
},
lurkinghorror = {
modules = {"infocom.lurkinghorror.h1"}
},
spellbreaker = {
modules = {"infocom.spellbreaker.z6"}
}
}
local game_name = args.game or "zork1"
local game_config = GAMES[game_name]
if not game_config then
io.write(string.format('{"ok":false,"error":"Unknown game: %s. Available: %s"}\n',
game_name, table.concat(table.keys(GAMES or {}), ", ")))
os.exit(1)
end
-- Capture output function
local captured_output = {}
local function capture_print(...)
local parts = {}
for i = 1, select("#", ...) do
parts[i] = tostring(select(i, ...))
end
table.insert(captured_output, table.concat(parts, "\t"))
end
local function capture_io_write(...)
for i = 1, select("#", ...) do
local s = tostring(select(i, ...))
table.insert(captured_output, s)
end
end
local function flush_capture()
local result = table.concat(captured_output)
captured_output = {}
return result
end
-- Override io_write and io_flush in the game environment
-- to capture output instead of printing to terminal
local function setup_capture(env)
-- Store original functions
local original_io_write = _G.io_write
local original_io_flush = _G.io_flush
-- Override globally for the game environment
_G.io_write = function(...)
capture_io_write(...)
end
_G.io_flush = function()
return flush_capture()
end
return function()
-- Restore function
_G.io_write = original_io_write
_G.io_flush = original_io_flush
end
end
-- Create game environment
local env = runtime.create_game_env()
-- Load bootstrap
if not runtime.init(env) then
io.write('{"ok":false,"error":"Failed to initialize ZIL runtime"}\n')
os.exit(1)
end
-- Install ZIL support
env.require('zilscript')
-- Load game modules
if not runtime.load_modules(env, game_config.modules, {silent = true}) then
io.write('{"ok":false,"error":"Failed to load game modules"}\n')
os.exit(1)
end
-- Create game coroutine
local game = runtime.create_game(env, true)
-- Helper to escape strings for JSON
local function json_escape(s)
if not s then return "null" end
s = s:gsub('\\', '\\\\')
s = s:gsub('"', '\\"')
s = s:gsub('\n', '\\n')
s = s:gsub('\r', '\\r')
s = s:gsub('\t', '\\t')
-- Remove ANSI escape codes
s = s:gsub('\27%[[0-9;]*m', '')
return '"' .. s .. '"'
end
local function json_unescape(s)
s = s:gsub('\\n', '\n')
s = s:gsub('\\r', '\r')
s = s:gsub('\\t', '\t')
s = s:gsub('\\"', '"')
s = s:gsub('\\\\', '\\')
return s
end
local function current_working_dir()
local pipe = io.popen("pwd", "r")
if not pipe then
return nil
end
local path = pipe:read("*l")
pipe:close()
return path
end
local function normalize_path(path)
if not path or path == "" then
return path
end
if path:sub(1, 1) == "/" then
return path
end
local cwd = current_working_dir()
if not cwd or cwd == "" then
return path
end
return cwd .. "/" .. path
end
local restore
local function write_error_and_exit(message)
restore()
message = tostring(message):gsub('\27%[[0-9;]*m', '')
io.write(string.format('{"ok":false,"error":%s}\n', json_escape(message)))
os.exit(1)
end
-- Helper to get current room name
local function get_room_name(env)
local ok, result = pcall(function()
local here = rawget(_G, "HERE") or rawget(env, "HERE")
if here and type(here) == "number" then
-- Try to get the DESC property
local pqdesc = rawget(_G, "PQDESC") or rawget(env, "PQDESC")
if pqdesc then
local desc = env.GETP and env.GETP(here, pqdesc)
if desc and type(desc) == "number" then
return env.mem and env.mem:string(desc)
elseif type(desc) == "string" then
return desc
end
end
end
return nil
end)
return ok and result or nil
end
-- Main logic
restore = setup_capture(env)
local savefile = normalize_path(args.savefile or "savefile.sav")
local historyfile = savefile .. ".actions"
local game_started = false
local resumed_from_dump = false
local resumed_from_history = false
local function file_exists(path, mode)
local file = io.open(path, mode or "r")
if not file then
return false
end
file:close()
return true
end
local function read_action_history(path)
local actions = {}
local file = io.open(path, "r")
if not file then
return actions
end
for line in file:lines() do
if line ~= "" then
local entry = { action = line }
local encoded_time, encoded_game, encoded_action = line:match('^%{"time":(%d+),"game":"(.*)","action":"(.*)"%}$')
if encoded_action then
entry = {
time = tonumber(encoded_time),
game = json_unescape(encoded_game),
action = json_unescape(encoded_action),
}
else
local legacy_time, legacy_action = line:match('^%{"time":(%d+),"action":"(.*)"%}$')
if legacy_action then
entry = {
time = tonumber(legacy_time),
action = json_unescape(legacy_action),
}
end
end
actions[#actions + 1] = entry
end
end
file:close()
return actions
end
local function reset_action_history(path)
local file, err = io.open(path, "w")
if not file then
return false, err
end
file:close()
return true
end
local function append_action_history(path, action)
local file, err = io.open(path, "a")
if not file then
return false, err
end
file:write(string.format('{"time":%d,"game":%s,"action":%s}\n', os.time(), json_escape(game_name), json_escape(action)))
file:close()
return true
end
local function start_game()
local output = game:start()
if resumed_from_dump then
_G._LLM_RESTORED = nil
end
game_started = true
return output
end
local function resume_action(action)
local ok, result = pcall(function()
return game:resume(action)
end)
if not ok then
error(tostring(result))
end
if type(result) == "string" then
return result
elseif type(result) == "table" and result.status then
return string.format("[%s] %s", result.status, result.message or "")
end
return ""
end
local function replay_action_history(path)
local actions = read_action_history(path)
if #actions == 0 then
return false
end
for _, entry in ipairs(actions) do
if entry.game and entry.game ~= game_name then
error(string.format("History file belongs to game '%s', not '%s'", entry.game, game_name))
end
end
start_game()
for _, entry in ipairs(actions) do
resume_action(entry.action)
end
return true
end
if not args.new_game then
if file_exists(savefile, "rb") then
local ok, restore_err = pcall(function()
env.RESTORE(savefile)
end)
if ok then
_G._LLM_RESTORED = true
resumed_from_dump = true
else
_G._LLM_RESTORED = nil
end
end
if not resumed_from_dump and file_exists(historyfile, "r") then
local ok, replayed_or_err = pcall(replay_action_history, historyfile)
if not ok then
write_error_and_exit(replayed_or_err)
end
resumed_from_history = replayed_or_err and true or false
end
end
-- Helper to execute an action and get output
local function execute_action(action)
if not game_started then
start_game()
end
return resume_action(action)
end
-- If we have an action, execute it
if args.action then
local ok, output = pcall(execute_action, args.action)
if not ok then
write_error_and_exit(output)
end
-- Get room name
local room = get_room_name(env)
-- Save game state
local save_err = nil
local history_err = nil
local ok, err = pcall(function()
env.SAVE(savefile)
end)
if not ok then
save_err = tostring(err)
end
local history_ok, history_write_err = append_action_history(historyfile, args.action)
if not history_ok then
history_err = tostring(history_write_err)
end
restore()
-- Output JSON
local response = {
ok = true,
output = output,
room = room,
savefile = savefile,
historyfile = historyfile,
restored = resumed_from_dump or resumed_from_history,
}
if save_err then
response.save_error = save_err
end
if history_err then
response.history_error = history_err
end
-- Simple JSON serialization
io.write("{")
io.write('"ok":' .. tostring(response.ok) .. ',')
io.write('"output":' .. json_escape(response.output) .. ',')
io.write('"room":' .. json_escape(response.room) .. ',')
io.write('"savefile":' .. json_escape(response.savefile) .. ',')
io.write('"historyfile":' .. json_escape(response.historyfile) .. ',')
io.write('"restored":' .. tostring(response.restored))
if response.save_error then
io.write(',"save_error":' .. json_escape(response.save_error))
end
if response.history_error then
io.write(',"history_error":' .. json_escape(response.history_error))
end
io.write("}\n")
elseif args.new_game then
-- Start a new game and get initial output
local ok, result = pcall(start_game)
if not ok then
write_error_and_exit(result)
end
local output = ""
if type(result) == "string" then
output = result
end
local room = get_room_name(env)
local history_err = nil
local history_ok, history_reset_err = reset_action_history(historyfile)
if not history_ok then
history_err = tostring(history_reset_err)
end
-- Save initial state as a raw memory dump. The action history remains available as a backlog and fallback path.
local save_err = nil
local ok, err = pcall(function()
env.SAVE(savefile)
end)
if not ok then
save_err = tostring(err)
end
restore()
io.write("{")
io.write('"ok":true,')
io.write('"output":' .. json_escape(output) .. ',')
io.write('"room":' .. json_escape(room) .. ',')
io.write('"savefile":' .. json_escape(savefile) .. ',')
io.write('"historyfile":' .. json_escape(historyfile) .. ',')
io.write('"new_game":true')
if save_err then
io.write(',"save_error":' .. json_escape(save_err))
end
if history_err then
io.write(',"history_error":' .. json_escape(history_err))
end
io.write("}\n")
else
write_error_and_exit("No action specified. Use --action or --new-game")
end