dymokomi/luced
Source of release 0.4.1
0.4.1 / src / editor / application.luc
## Session construction composes configuration, commands, named views and the
## workspace. Interaction policy stays in those components, not the entry point.
from luce_ui.ui import Application, Font, Shortcut, Command
from interop import Connection
from editor.options import Options
from editor.actions import EditorActions
from editor.journal import Journal
from editor.syntax_switcher import SyntaxSwitcher
from editor.views import EditorView
from editor.configuration import Configuration
from configuration.store import Store
from configuration.settings import Settings
from configuration.theme import Appearance
from workspace.controller import Workspace
from workspace.explorer import Explorer
from workspace.editors import Editors
from language.grammars import GrammarSet
from commands.runner import Runner
from editor.ai_tools import AiTools
from luce_ai import agent
import workspace.paths as paths
from luce_std import files
## The tools the model may call, as JSON function schemas (the agent wraps them in an
## array). Read tools inspect the project; edit tools change the focused document and
## are undoable. AiTools executes them on the main thread.
let TOOLS_SCHEMA = "{\"type\":\"function\",\"function\":{\"name\":\"read_selection\",\"description\":\"Return the selected text and the 1-based line range it covers, or a note when nothing is selected.\",\"parameters\":{\"type\":\"object\",\"properties\":{}}}},{\"type\":\"function\",\"function\":{\"name\":\"read_document\",\"description\":\"Return the whole focused document with 1-based line numbers.\",\"parameters\":{\"type\":\"object\",\"properties\":{}}}},{\"type\":\"function\",\"function\":{\"name\":\"replace_lines\",\"description\":\"Replace lines first..last (inclusive, 1-based) with text, which may span several lines or be empty. One undoable edit; returns the updated numbered document.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"first\":{\"type\":\"integer\"},\"last\":{\"type\":\"integer\"},\"text\":{\"type\":\"string\"}},\"required\":[\"first\",\"last\",\"text\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"insert_lines\",\"description\":\"Insert text as new lines after line 'after' (0 = at the top).\",\"parameters\":{\"type\":\"object\",\"properties\":{\"after\":{\"type\":\"integer\"},\"text\":{\"type\":\"string\"}},\"required\":[\"after\",\"text\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"delete_lines\",\"description\":\"Delete lines first..last (inclusive, 1-based).\",\"parameters\":{\"type\":\"object\",\"properties\":{\"first\":{\"type\":\"integer\"},\"last\":{\"type\":\"integer\"}},\"required\":[\"first\",\"last\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"set_document\",\"description\":\"Replace the entire document with text (one undoable edit). Best for a full rewrite such as spellchecking the whole file, since it needs no line numbers.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"}},\"required\":[\"text\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"read_file\",\"description\":\"Read a UTF-8 text file from the project by path relative to the project root.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\"}},\"required\":[\"path\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"list_dir\",\"description\":\"List the entries of a directory, relative to the project root.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\"}},\"required\":[\"path\"]}}},{\"type\":\"function\",\"function\":{\"name\":\"find_text\",\"description\":\"Search the project for lines containing a substring.\",\"parameters\":{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\"}},\"required\":[\"query\"]}}}"
pub class Editor:
pub let app: Application
pub let workspace: Workspace
pub let runner: Runner
pub let view: EditorView
pub let configuration: Configuration
pub let actions: EditorActions
let options: Options
let connections: list[Connection]
let tools: AiTools
let switcher: SyntaxSwitcher
var ai_expecting: bool = false
var ai_waiting: bool = false
var ai_mode: str = "ask"
var ai_selection: str = ""
var ai_query: str = ""
var ai_turns: int = 0
var ai_log: str = ""
var heartbeat: int = 0
var beat: float = 0.5
pub func init(self, options: Options) -> unit!:
let store = Store(options.config_directory)
var warning = ""
let settings = Settings(store.read_settings()) catch failure:
warning = "settings.toml: " + failure.message
recover Settings()
let appearance = Appearance(store.read_theme()) catch failure:
warning += " theme.toml: " + failure.message
recover Appearance()
var family = settings.font_family
let font = Font(size = settings.font_size, family = family) catch failure:
warning += " Font: " + failure.message
family = ""
recover Font()
let absolute = files.canonical(options.location)
let is_file = files.metadata(absolute).kind == files.FileKind.regular
let explorer = Explorer(paths.parent(absolute) if is_file else absolute)
let grammars = GrammarSet(store.grammars_dir)
let switcher = SyntaxSwitcher(grammars)
let actions = EditorActions()
let journal = Journal(store.directory)
actions.files.set_journal(journal)
journal.record(("open file " if is_file else "open folder ") + absolute)
let view = EditorView(explorer, actions, font)
let app = Application(view.body, title = "luced", width = settings.width, height = settings.height, theme = appearance.theme)
let runner = Runner(view.output.output, options.luce if options.luce_override else settings.luce,
options.base if options.base_override else settings.base)
let divider = Command("", divider = true)
let editors = Editors(view.dock, view.output.body, font,
actions.editing.all + [divider, actions.save, divider, actions.fold, actions.fold_all, actions.unfold_all, divider, actions.ask_ai, actions.write_ai, actions.spellcheck_ai], switcher.menu_commands(), actions.editing, wrap = settings.word_wrap)
editors.set_color_editor(view.color)
view.dock.set_fraction(view.sidebar.body, 0.22)
let workspace = Workspace(app, explorer, view.sidebar.listing, view.sidebar.body, view.status, runner, editors, view.dialog, appearance.theme)
workspace.set_syntax(appearance.syntax)
workspace.set_grammars(grammars)
switcher.connect(workspace)
let configuration = Configuration(store, font, app, view.body.layout(), workspace, runner, options, family)
let tools = AiTools(workspace)
self.app = app
self.switcher = switcher
self.workspace = workspace
self.runner = runner
self.view = view
self.configuration = configuration
self.actions = actions
self.options = options
self.connections = []
self.tools = tools
self.connect()
app.set_commands(actions.all)
for (id, chord) in settings.shortcuts:
let shortcut = Shortcut.parse(chord) catch failure:
warning += f" shortcut {id}: {failure.message}"
continue
if let command = app.command(id):
command.set_shortcut(shortcut)
app.set_close_handler(workspace.can_close)
app.set_error_handler(workspace.report)
if is_file:
workspace.open(absolute)
if warning != "":
workspace.report(warning)
actions.update(workspace, runner.busy())
func connect(self) -> unit!:
for connection in self.actions.connect(self.workspace): self.connections.append(connection)
for connection in self.actions.files.connect(self.workspace, self.view.prompt): self.connections.append(connection)
self.connections.append(self.actions.palette.on_trigger(self.open_palette))
self.connections.append(self.actions.settings.on_trigger(self.configuration.edit_settings))
self.connections.append(self.actions.theme.on_trigger(self.configuration.edit_theme))
self.connections.append(self.actions.ai_settings.on_trigger(self.configuration.edit_ai))
self.connections.append(self.actions.ask_ai.on_trigger(self.ask_ai))
self.connections.append(self.actions.write_ai.on_trigger(self.write_ai))
self.connections.append(self.actions.spellcheck_ai.on_trigger(self.spellcheck_ai))
self.connections.append(self.view.prompt.on_submit(self.ai_submit))
self.connections.append(self.actions.reload.on_trigger(self.configuration.reload))
self.connections.append(self.actions.exit.on_trigger(self.workspace.request_exit))
self.connections.append(self.view.dialog.on_choose(self.workspace.close_choice))
self.connections.append(self.actions.next_pane.on_trigger(self.next_pane))
self.connections.append(self.actions.previous_pane.on_trigger(self.previous_pane))
self.connections.append(self.actions.focus_explorer.on_trigger(self.focus_explorer))
self.connections.append(self.actions.focus_editor.on_trigger(self.workspace.focus_editor))
self.connections.append(self.actions.focus_output.on_trigger(self.focus_output))
self.connections.append(self.actions.focus_left.on_trigger(self.focus_left))
self.connections.append(self.actions.focus_right.on_trigger(self.focus_right))
self.connections.append(self.actions.focus_up.on_trigger(self.focus_up))
self.connections.append(self.actions.focus_down.on_trigger(self.focus_down))
self.connections.append(self.view.sidebar.listing.on_activate(self.workspace.activate))
self.connections.append(self.view.sidebar.context.on_open(self.view.sidebar.refresh_menu))
self.connections.append(self.view.output.context.on_open(self.actions.output.update))
# The heartbeat pumps a running build's output and polls settings on disk; it
# paces itself fast while a command runs and slow when idle, so a quiet window
# barely wakes. A finished AI turn is delivered by ai_pump on its wake() instead.
self.heartbeat = self.app.after(self.beat, self.tick)
self.connections.append(self.app.on_frame(self.ai_pump))
func update_actions(self) -> unit!:
self.actions.update(self.workspace, self.runner.busy())
pub func open_palette(self) -> unit!:
self.update_actions()
self.view.palette.open()
pub func focus_explorer(self) -> unit!:
self.view.dock.select(self.view.sidebar.body)
pub func focus_output(self) -> unit!:
self.view.dock.select(self.view.output.body)
pub func next_pane(self) -> unit!:
self.view.dock.focus_next()
pub func previous_pane(self) -> unit!:
self.view.dock.focus_next(backwards = true)
pub func focus_left(self) -> unit!:
self.view.dock.focus_direction(-1.0, 0.0)
pub func focus_right(self) -> unit!:
self.view.dock.focus_direction(1.0, 0.0)
pub func focus_up(self) -> unit!:
self.view.dock.focus_direction(0.0, -1.0)
pub func focus_down(self) -> unit!:
self.view.dock.focus_direction(0.0, 1.0)
## Cmd+I: ask the "ask" model a question, with any selected text as context.
pub func ask_ai(self) -> unit!:
self.begin_mode("ask", true, "Ask AI", "Ask")
## Cmd+Shift+I: describe a change; the "write" model edits the document to make it.
pub func write_ai(self) -> unit!:
self.begin_mode("write", true, "Write — describe the change", "Write")
## Spellcheck the selection, or the whole document when nothing is selected.
pub func spellcheck_ai(self) -> unit!:
self.begin_mode("spellcheck", false, "", "")
## Start an AI mode. "ask"/"write" open a prompt first; "spellcheck" runs at once.
## The editing modes act on the selection when there is one, else the whole file.
func begin_mode(self, mode: str, needs_prompt: bool, title: str, accept: str) -> unit!:
let config = self.configuration.ai()
if not config.ready(mode):
self.workspace.report("The " + mode + " mode is not ready — set a model and key in Edit AI Settings")
return
if config.mode(mode).provider != "openrouter":
self.workspace.report("Only the openrouter provider is wired up so far")
return
if not self.workspace.has_document():
self.workspace.report("Open a file first for " + mode)
return
self.ai_mode = mode
self.ai_selection = self.selection_text()
if needs_prompt:
self.actions.files.reset_operation()
self.ai_expecting = true
self.view.prompt.open(title, accept = accept)
else:
self.launch("")
func ai_submit(self, text: str) -> unit!:
if not self.ai_expecting:
return
self.ai_expecting = false
self.launch(text)
func combine(self, instruction: str, selection: str) -> str:
if selection == "":
return instruction
if instruction == "":
return selection
return instruction + "\n\n----- selected text -----\n" + selection
## Build the user message for the mode: a question with selection context for "ask",
## or an edit task scoped to the selection (or the whole file) for the editing modes.
func compose(self, mode: str, instruction: str, selection: str) -> str:
if mode == "ask":
return self.combine(instruction, selection)
let request = instruction if instruction != "" else "Correct the spelling and grammar."
let hint = " There is a selection." if selection != "" else " There is no selection."
return request + "\n\n" + hint + " Call read_selection to see any selected text and the lines it covers, or read_document for the whole file, then edit accordingly."
## Start an agent conversation for the current mode and run its first turn. The
## model may call tools; advance() drives each following turn from the heartbeat.
func launch(self, instruction: str) -> unit!:
let cfg = self.configuration.ai()
let mode = cfg.mode(self.ai_mode)
agent.reset(mode.system, self.compose(self.ai_mode, instruction, self.ai_selection), TOOLS_SCHEMA)
self.ai_query = instruction
self.ai_turns = 0
if not agent.begin(cfg.openrouter.api_key, mode.model):
self.show_ai("An AI request is already running.")
return
self.ai_waiting = true
self.ai_log = mode.model + " · " + self.ai_mode + "\n"
self.ai_note("→ asking the model …")
self.view.dock.select(self.view.output.body)
## Append one transcript line to the Output pane, live, so each step is visible as it
## happens rather than all at once when the whole exchange finishes.
func ai_note(self, line: str) -> unit!:
self.ai_log += line + "\n"
self.view.output.output.set_text(self.ai_log)
self.view.output.output.set_selection(self.ai_log.length, self.ai_log.length)
## Parse a finished turn: show the final answer or an error, or execute the tools
## the model requested and start the next turn. Runs on the main thread, so a tool
## may read files and edit the focused document. Each step is logged as it happens.
func advance(self) -> unit!:
let code = agent.finish() catch failure:
self.ai_waiting = false
self.clear_ai_region()
self.ai_note("✗ error: " + failure.message)
return
if code != 1:
self.ai_waiting = false
self.clear_ai_region()
self.ai_note("✓ " + agent.reply())
return
self.ai_turns += 1
for i in self.tool_order(agent.tool_count()):
let name = agent.tool_name(i)
self.ai_note("• " + self.tool_summary(name, i))
self.mark_ai_region(name, i)
agent.add_tool_result(agent.tool_id(i), self.run_tool(name, i))
if self.ai_turns >= 8:
self.ai_waiting = false
self.clear_ai_region()
self.ai_note("✗ stopped after 8 tool rounds")
return
let cfg = self.configuration.ai()
if not agent.begin(cfg.openrouter.api_key, cfg.mode(self.ai_mode).model):
self.ai_waiting = false
self.clear_ai_region()
self.ai_note("✗ the request could not continue")
return
self.ai_note("→ asking the model …")
## Stripe the gutter of the lines the current tool touches, so the document shows
## what the AI is looking at or changing as it works.
func mark_ai_region(self, name: str, index: int) -> unit!:
let editor = self.workspace.current_editor() else return
if name == "read_selection":
editor.set_ai_lines(editor.selection_first_line(), editor.selection_last_line())
elif name == "replace_lines" or name == "delete_lines":
editor.set_ai_lines(self.line_arg(index, "first"), self.line_arg(index, "last"))
elif name == "insert_lines":
let after = self.line_arg(index, "after")
editor.set_ai_lines(after, after + 1)
func clear_ai_region(self) -> unit:
let editor = self.workspace.current_editor() else return
editor.clear_ai_lines()
## A short human description of a tool call, for the live transcript.
func tool_summary(self, name: str, index: int) -> str!:
if name == "read_selection":
return "reading the selection"
if name == "read_document":
return "reading the document"
if name == "set_document":
return "rewriting the document"
if name == "replace_lines":
return "editing lines " + str(self.line_arg(index, "first")) + "–" + str(self.line_arg(index, "last"))
if name == "insert_lines":
return "inserting after line " + str(self.line_arg(index, "after"))
if name == "delete_lines":
return "deleting lines " + str(self.line_arg(index, "first")) + "–" + str(self.line_arg(index, "last"))
if name == "read_file":
return "reading " + (agent.tool_arg(index, "path"))
if name == "list_dir":
return "listing " + (agent.tool_arg(index, "path"))
if name == "find_text":
return "searching \"" + (agent.tool_arg(index, "query")) + "\""
return name
func run_tool(self, name: str, index: int) -> str!:
if name == "read_selection":
return self.tools.read_selection()
if name == "read_document":
return self.tools.read_document()
if name == "replace_lines":
return self.tools.replace_lines(self.line_arg(index, "first"), self.line_arg(index, "last"), agent.tool_arg(index, "text"))
if name == "insert_lines":
return self.tools.insert_lines(self.line_arg(index, "after"), agent.tool_arg(index, "text"))
if name == "delete_lines":
return self.tools.delete_lines(self.line_arg(index, "first"), self.line_arg(index, "last"))
if name == "set_document":
return self.tools.set_document(agent.tool_arg(index, "text"))
if name == "read_file":
return self.tools.read_file(agent.tool_arg(index, "path"))
if name == "list_dir":
return self.tools.list_dir(agent.tool_arg(index, "path"))
if name == "find_text":
return self.tools.find_text(agent.tool_arg(index, "query"))
return "error: unknown tool " + name
## A tool's integer argument (line numbers arrive as JSON numbers), 0 if unparseable.
func line_arg(self, index: int, key: str) -> int!:
let value = agent.tool_arg(index, key)
return int(value) catch failure:
recover 0
## Order a turn's tool calls so line edits apply bottom-up (highest line first), which
## keeps several edits in one turn from shifting each other's line numbers. Non-edit
## tools keep their order and run first, since they don't move any lines.
func tool_order(self, count: int) -> list[int]!:
var order: list[int] = []
var edits: list[int] = []
var keys: list[int] = []
for i in 0..<count:
let name = agent.tool_name(i)
if name == "replace_lines" or name == "delete_lines":
edits.append(i)
keys.append(self.line_arg(i, "first"))
elif name == "insert_lines":
edits.append(i)
keys.append(self.line_arg(i, "after"))
else:
order.append(i)
while edits.length > 0:
var best = 0
for j in 1..<edits.length:
if keys[j] > keys[best]:
best = j
order.append(edits[best])
edits = edits[0..<best] + edits[best + 1..<edits.length]
keys = keys[0..<best] + keys[best + 1..<keys.length]
return order
func selection_text(self) -> str!:
let editor = self.workspace.current_editor() else return ""
return editor.selected_text()
func show_ai(self, text: str) -> unit!:
self.view.output.output.set_text(text)
self.view.output.output.set_selection(0, 0)
self.view.dock.select(self.view.output.body)
func tick(self) -> unit!:
self.workspace.frame(self.beat)
self.configuration.poll(self.beat)
self.update_actions()
self.beat = 0.03 if self.runner.busy() else 0.5
self.heartbeat = self.app.after(self.beat, self.tick)
## Runs on every loop wake (including a worker's wake() when an AI turn finishes),
## so a reply or the next tool round is delivered at once rather than on a poll.
func ai_pump(self, elapsed: float) -> unit!:
if self.ai_waiting and agent.done():
self.advance()
pub func run(self) -> unit!:
self.app.run(frame_limit = 12 if self.options.smoke else 0)
pub func close(self):
self.app.close()
self.app.cancel(self.heartbeat)
self.workspace.close()
for connection in self.connections: connection.disconnect()
self.connections.clear()
self.actions.editing.close()
self.actions.output.close()