-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcluade.lua
More file actions
executable file
·326 lines (296 loc) · 10.7 KB
/
Copy pathcluade.lua
File metadata and controls
executable file
·326 lines (296 loc) · 10.7 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
#!/usr/bin/env lua
-- cluade -- a minimal coding agent for OpenWRT / constrained Linux
-- The full path cluade was invoked as. For a symlink (e.g. /usr/local/bin/cluade)
-- this is the LINK's path, not the real file -- so resolve it before deriving the
-- module dir, otherwise `require` looks in the symlink's directory and fails.
local src = debug.getinfo(1, "S").source:match("^@(.*)$") or "cluade.lua"
local script_dir
do
local sh_quote = "'" .. src:gsub("'", "'\\''") .. "'"
local f = io.popen("readlink -f " .. sh_quote .. " 2>/dev/null")
local real = f and f:read("*l")
if f then f:close() end
if real and #real > 0 then
script_dir = real:match("^(.*)/[^/]*$") or "." -- dir of the resolved file
else
script_dir = src:match("^(.*)/[^/]*$") or "." -- fallback: as-invoked dir
end
end
if script_dir:sub(1, 1) ~= "/" then
local f = io.popen("pwd")
script_dir = f:read("*l") .. "/" .. script_dir
f:close()
end
package.path = script_dir .. "/?.lua;" .. script_dir .. "/?/init.lua;" .. package.path
-- How to re-invoke cluade itself (interpreter + entry script), used to spawn
-- subagents as child processes. arg[-1] is the interpreter that launched us.
local self_cmd
do
local interp = (arg and arg[-1]) or "lua5.1"
local q = function(s) return "'" .. s:gsub("'", "'\\''") .. "'" end
self_cmd = q(interp) .. " " .. q(script_dir .. "/cluade.lua")
end
local json = require("vendor.json")
local Store = require("store")
local Agent = require("agent")
local c = require("colors")
local lineedit = require("lineedit")
local function handle_command(line, config, sessions_dir, session)
if line == "/help" then
print(c.dim("Commands: /help /exit /sessions /resume <id> /new /model <name>"))
return "continue"
elseif line == "/exit" then
print(c.cyan("Exiting..."))
return "exit"
elseif line == "/sessions" then
local sessions = Store.list_sessions(sessions_dir)
if #sessions == 0 then
print(c.dim("No sessions found."))
else
for _, s in ipairs(sessions) do
print(string.format("%s %s %d msgs %s", s.id, s.created, s.messages, s.cwd))
end
end
return "continue"
elseif line:match("^/resume%s+(.+)$") then
local id = line:match("^/resume%s+(.+)$")
local ok, loaded = pcall(function() return Store.load_session(sessions_dir, id) end)
if not ok or not loaded then
print(c.red("Session '" .. id .. "' not found."))
else
session.id = loaded.id
session.messages = loaded.messages or {}
session.cwd = loaded.cwd or session.cwd
print(c.cyan("Resumed session " .. id))
end
return "continue"
elseif line == "/new" then
local new_s = Store.new_session_data(session.cwd or ".")
Store.save_session(sessions_dir, new_s.id, new_s)
session.id = new_s.id
session.messages = {}
session.cwd = new_s.cwd
print(c.cyan("New session: " .. new_s.id))
return "continue"
elseif line:match("^/model%s+(.+)$") then
local model = line:match("^/model%s+(.+)$")
config.model = model
print(c.cyan("Model set to: " .. model))
return "continue"
end
return nil
end
local function print_help()
print([[
cluade — minimal coding agent for constrained Linux environments
Usage: cluade [options] [prompt]
Options:
-m, --model MODEL LLM model name (default: deepseek-v4-pro)
--base-url URL API base URL (default: https://api.deepseek.com/v1)
--api-key KEY API key (or set OPENAI_API_KEY env var)
-c, --continue Resume the most recent session
-r, --resume ID Resume a specific session by ID
--list-sessions List saved sessions
-y, --yes Auto-approve all permission prompts
--init Initialize a config file
--show-tools-json Debug: print raw response body + decoded tool_calls + compact view
--subagent Unattended child mode: only the final answer to stdout,
no session traces, catastrophic commands hard-denied
--plan With --subagent: read-only toolset (no write/edit/bash)
--quiet Only the final answer to stdout; progress to stderr
--no-session Do not persist a session
-h, --help Show this help
Examples:
cluade "write a hello world script"
cluade -c
cluade --base-url http://localhost:11434/v1 -m llama3 "explain this code"
cluade --init
]])
end
local function parse_args(argv)
local args = { cwd = os.getenv("PWD") or "." }
local i = 1
while i <= #argv do
local a = argv[i]
if a == "-h" or a == "--help" then
print_help()
os.exit(0)
elseif a == "-m" or a == "--model" then
i = i + 1; args.model = argv[i]
elseif a == "--base-url" then
i = i + 1; args.base_url = argv[i]
elseif a == "--api-key" then
i = i + 1; args.api_key = argv[i]
elseif a == "-c" or a == "--continue" then
args.continue_session = true
elseif a == "-r" or a == "--resume" then
i = i + 1; args.resume = argv[i]
elseif a == "--list-sessions" then
args.list_sessions = true
elseif a == "-y" or a == "--yes" then
args.yes = true
elseif a == "--init" then
args.init = true
elseif a == "--show-tools-json" then
args.show_tools_json = true
elseif a == "--subagent" then
args.subagent = true
elseif a == "--plan" then
args.plan = true
elseif a == "--quiet" then
args.quiet = true
elseif a == "--no-session" then
args.no_session = true
elseif a:sub(1, 1) ~= "-" then
args.prompt = (args.prompt and args.prompt .. " " or "") .. a
end
i = i + 1
end
return args
end
local function deep_copy(t)
if type(t) ~= "table" then return t end
local copy = {}
for k, v in pairs(t) do copy[k] = deep_copy(v) end
return copy
end
-- === main ===
local args = parse_args(arg)
local home = os.getenv("HOME") or os.getenv("USERPROFILE") or "/tmp"
local config = Store.load_config(args.cwd)
if args.model then config.model = args.model end
if args.base_url then config.base_url = args.base_url end
if args.api_key then config.api_key = args.api_key end
if args.show_tools_json then config.show_tools_json = true end
-- --subagent is the preset for an unattended child agent: quiet output (final
-- answer to stdout, progress to stderr), no session traces, dangercheck-as-deny.
-- --quiet / --no-session are also usable on their own; --plan makes a subagent
-- read-only.
if args.subagent then config.subagent = true; config.quiet = true; config.ephemeral = true end
if args.plan then config.plan = true end
if args.quiet then config.quiet = true end
if args.no_session then config.ephemeral = true end
require("tools").set_self_cmd(self_cmd)
if args.init then
local config_dir = os.getenv("HOME") .. "/.cluade"
os.execute('mkdir -p "' .. config_dir .. '" 2>/dev/null')
local f = io.open(config_dir .. "/config.json", "w")
f:write(json.encode({
base_url = config.base_url,
model = config.model,
api_key = config.api_key,
max_steps = 100,
max_tokens = 131072,
request_timeout = 600,
permissions = { bash = "allow", remote_bash = "ask", write = "allow" },
}) .. "\n")
f:close()
print("written " .. config_dir .. "/config.json")
os.exit(0)
end
local sessions_dir = home .. "/.cluade/sessions"
config.sessions_dir = sessions_dir
if args.list_sessions then
local sessions = Store.list_sessions(sessions_dir)
if #sessions == 0 then
print("No sessions found.")
else
for _, s in ipairs(sessions) do
print(string.format("%s %s %d msgs %s", s.id, s.created, s.messages, s.cwd))
end
end
os.exit(0)
end
local session
if args.continue_session then
local last_id = Store.get_last_session_id(home)
if not last_id then
print("No previous session to continue.")
os.exit(1)
end
local ok, err = pcall(function() session = Store.load_session(sessions_dir, last_id) end)
if not ok then
print("Failed to load session " .. last_id .. ": " .. tostring(err))
os.exit(1)
end
print("continuing session " .. last_id)
elseif args.resume then
local id = args.resume:gsub("%.json$", "")
local ok, err = pcall(function() session = Store.load_session(sessions_dir, id) end)
if not ok or not session then
print("Failed to load session " .. id .. ": " .. tostring(err or session))
os.exit(1)
end
print("resumed session " .. args.resume)
else
session = Store.new_session_data(args.cwd)
if not config.ephemeral then
Store.save_session(sessions_dir, session.id, session)
end
end
-- An ephemeral (--subagent / --no-session) run leaves no trace: no session file
-- and no update to the "last session" pointer.
if not config.ephemeral then
Store.set_last_session_id(home, session.id)
end
local agent = Agent:init(config, args.cwd)
if args.yes then
local tools = require("tools")
tools.set_permissions({ bash = "allow", remote_bash = "allow", write = "allow" })
end
if args.prompt then
agent:run(session, args.prompt)
-- In quiet mode, stdout must carry only the subagent's answer -- no summary.
if not config.quiet then
local used = session.total_tokens or 0
local ctx = session.context_tokens or 0
local context_limit = config.context_limit or 200000
local pct = math.floor(ctx / context_limit * 100 * 10) / 10
print(c.dim(string.format("-- %s - %d tokens - %.1f%% context",
config.model or "?", used, pct)))
end
else
print(c.cyan("cluade session " .. session.id .. " -- " .. (config.model or "?")))
print(c.dim("Type /help for commands, Ctrl+D to exit"))
local function restore_term()
os.execute("stty icanon echo 2>/dev/null")
end
local interactive = lineedit.init()
if not interactive then
print(c.dim("stdin is not a terminal -- line editing disabled"))
else
os.execute("stty -icanon -echo 2>/dev/null")
end
local ok, err = pcall(function()
while true do
local line = lineedit.readline(c.cyan("> "))
if not line then
print()
return
end
if #line > 0 then
lineedit.add_history(line)
if line:sub(1, 1) == "/" then
local status = handle_command(line, config, sessions_dir, session)
if status == "exit" then return end
else
local t0 = os.time()
agent:run(session, line)
local elapsed = os.time() - t0
local used = session.total_tokens or 0
local ctx = session.context_tokens or 0
local context_limit = config.context_limit or 200000
local pct = math.floor(ctx / context_limit * 100 * 10) / 10
print(c.dim(string.format("-- %s - %d tokens - %.1f%% context - %ds",
config.model or "?", used, pct, elapsed)))
end
end
end
end)
if interactive then
restore_term()
end
if not ok and err then
print(c.red("Error: " .. tostring(err)))
end
end