a722f576ac
repl.ask_ai now drives broker.chat_stream and pumps each delta into renderer.assistant_delta(delta) as it arrives. renderer.assistant_flush is called when the stream ends to add a trailing newline if missing. The full reassembled response is then handed to executor.extract_cmd_lines for the CMD: confirm-and-execute path (unchanged from Phase 0). renderer.assistant() is kept for non-streaming callers (none in tree right now, but cheap to keep around). assistant_delta/flush share no state with assistant(); they use a module-local stream_buf that tracks the in-progress streamed block. Q12 deferred: incremental CMD: highlighting (cursor-positioning re- render on flush) is not implemented in Phase 1 — deltas emit raw. The §6 CMD: marker is still extractable on the reassembled string post- stream, which is what executor cares about. Renderer's bold+cyan treatment for CMD: lines stays available via M.assistant(). Broker error / SSE-framed api-error path still pops the user turn and restores ctx.pending_exec_output. Order: assistant_flush always runs (even on error) so the cursor lands on a fresh line before the broker- error status renders. Live verification: `Count one to ten` against hossenfelder fast streams deltas through to stdout incrementally; CMD: extraction works on the reassembled string; confirm gate intact. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
186 lines
6.7 KiB
Lua
186 lines
6.7 KiB
Lua
-- repl.lua — readline loop, input dispatch, prompt rendering.
|
|
-- Wires ffi/readline + router + executor + broker + context + renderer.
|
|
-- See docs/PHASE0.md §5 (dispatch), §9 (prompt + readline).
|
|
|
|
local rl = require("ffi.readline")
|
|
local router = require("router")
|
|
local executor = require("executor")
|
|
local broker = require("broker")
|
|
local renderer = require("renderer")
|
|
local Context = require("context")
|
|
|
|
local M = {}
|
|
|
|
local HELP = [[
|
|
Meta commands (Phase 0):
|
|
:quit / :q exit aish
|
|
:clear clear screen (history kept)
|
|
:reset clear in-memory conversation history
|
|
:model <name> switch active model
|
|
:models list configured models (* = active)
|
|
:history show conversation turns
|
|
:exec <cmd> force shell execution
|
|
:ask <text> force AI query
|
|
:help this message
|
|
]]
|
|
|
|
function M.run(config)
|
|
assert(config and config.models, "repl.run: config.models required")
|
|
local active_name = config.default_model or next(config.models)
|
|
local active_cfg = config.models[active_name]
|
|
if not active_cfg then
|
|
error("aish: default_model '" .. tostring(active_name)
|
|
.. "' not found in config.models")
|
|
end
|
|
|
|
local ctx = Context.new(config.context or {})
|
|
|
|
local function prompt()
|
|
return ("[aish:%s]> "):format(active_name)
|
|
end
|
|
|
|
local function status_evictions(n)
|
|
if n and n > 0 then
|
|
renderer.status(("oldest %d turns evicted"):format(n))
|
|
end
|
|
end
|
|
|
|
-- Run a shell command, framing output and (per config.shell.capture_output)
|
|
-- buffering it for the NEXT user turn — context.append_exec_output keeps
|
|
-- a [exec output] block pending until ask_ai flushes it via append_user.
|
|
-- Direct user-role injection violated chat-template alternation (mistral-
|
|
-- nemo's Jinja rejects user/user back-to-back); see PHASE0.md §6.
|
|
local function run_shell(cmd)
|
|
local chd, err = executor.maybe_chdir(cmd)
|
|
if chd ~= nil then
|
|
if chd then
|
|
local pwd = io.popen("pwd"):read("*l") or "?"
|
|
renderer.status("cwd -> " .. pwd)
|
|
else
|
|
renderer.status("cd: " .. tostring(err))
|
|
end
|
|
return
|
|
end
|
|
local out, code = executor.exec(cmd)
|
|
renderer.exec_output(out, code)
|
|
if config.shell and config.shell.capture_output then
|
|
ctx:append_exec_output(out)
|
|
end
|
|
end
|
|
|
|
-- Send user text to the active model, render the response token-by-token
|
|
-- via broker.chat_stream, and (per §6 + config.shell.confirm_cmd) optionally
|
|
-- execute extracted CMD: lines on the reassembled full text.
|
|
local function ask_ai(text)
|
|
local prev_pending = ctx.pending_exec_output
|
|
ctx:append_user(text) -- flushes any pending [exec output] as prefix
|
|
|
|
local parts = {}
|
|
local ok, err = broker.chat_stream(active_cfg, ctx:to_messages(),
|
|
function(delta)
|
|
parts[#parts + 1] = delta
|
|
renderer.assistant_delta(delta)
|
|
end)
|
|
renderer.assistant_flush()
|
|
|
|
if not ok then
|
|
renderer.status("broker error: " .. tostring(err))
|
|
table.remove(ctx.turns) -- back out the merged user turn
|
|
ctx.pending_exec_output = prev_pending -- restore buffered exec output
|
|
return
|
|
end
|
|
local resp = table.concat(parts)
|
|
ctx:append({ role = "assistant", content = resp })
|
|
status_evictions(ctx:enforce_budget())
|
|
|
|
for _, cmd in ipairs(executor.extract_cmd_lines(resp)) do
|
|
local doit
|
|
if config.shell and config.shell.confirm_cmd then
|
|
local ans = rl.readline(("execute '%s'? [y/N] "):format(cmd)) or ""
|
|
doit = (ans:lower():sub(1, 1) == "y")
|
|
else
|
|
doit = true
|
|
end
|
|
if doit then run_shell(cmd) end
|
|
end
|
|
end
|
|
|
|
-- Meta dispatch table.
|
|
local meta = {
|
|
quit = function() os.exit(0) end,
|
|
q = function() os.exit(0) end,
|
|
clear = function() io.write("\27[H\27[2J"); io.flush() end,
|
|
reset = function()
|
|
ctx:reset(); renderer.status("context reset")
|
|
end,
|
|
model = function(args)
|
|
local name = args:match("^%s*(%S+)")
|
|
if not name or not config.models[name] then
|
|
renderer.status("usage: :model <name>; not found: " .. tostring(name))
|
|
return
|
|
end
|
|
active_name, active_cfg = name, config.models[name]
|
|
renderer.status("model -> " .. name)
|
|
end,
|
|
models = function()
|
|
renderer.status(("models (active: %s):"):format(active_name))
|
|
for name, cfg in pairs(config.models) do
|
|
local mark = (name == active_name) and "*" or " "
|
|
io.write((" %s %-8s %s @ %s\n"):format(
|
|
mark, name, cfg.model or "?", cfg.endpoint or "?"))
|
|
end
|
|
end,
|
|
history = function()
|
|
if #ctx.turns == 0 then
|
|
renderer.status("(empty)"); return
|
|
end
|
|
for i, t in ipairs(ctx.turns) do
|
|
io.write(("[%d] %s: %s\n"):format(
|
|
i, t.role, t.content:gsub("\n", " ")))
|
|
end
|
|
end,
|
|
exec = function(args)
|
|
args = (args or ""):match("^%s*(.-)%s*$")
|
|
if args == "" then renderer.status("usage: :exec <cmd>"); return end
|
|
run_shell(args)
|
|
end,
|
|
ask = function(args)
|
|
args = (args or ""):match("^%s*(.-)%s*$")
|
|
if args == "" then renderer.status("usage: :ask <text>"); return end
|
|
ask_ai(args)
|
|
end,
|
|
help = function() io.write(HELP) end,
|
|
}
|
|
|
|
-- Main loop.
|
|
while true do
|
|
local line = rl.readline(prompt())
|
|
if line == nil then -- EOF (Ctrl-D on empty line)
|
|
io.write("\n"); break
|
|
end
|
|
if line:gsub("%s", "") == "" then
|
|
-- empty / whitespace-only: skip silently
|
|
else
|
|
rl.add_history(line)
|
|
local kind, payload = router.classify(line, config)
|
|
if kind == "meta" then
|
|
local name, rest = payload:match("^(%S+)%s*(.*)$")
|
|
local handler = name and meta[name]
|
|
if handler then
|
|
handler(rest or "")
|
|
else
|
|
renderer.status("unknown meta command: :" .. tostring(name))
|
|
end
|
|
elseif kind == "shell" then
|
|
run_shell(payload)
|
|
else -- "ai"
|
|
ask_ai(payload)
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
-- Phase 0 module export. Meta-command list shown above lives in HELP and
|
|
-- is implemented inline in run().
|
|
return M
|