Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-ai

Source of release 0.4.1

0.4.1 / src / config.luc

## AI configuration: for each mode, which provider and model answer it and the
## system prompt that steers it; plus how to reach each provider. The schema is
## validated up front, like the editor's other settings, and holds no network
## logic — credentials are stored, not resolved here, so a key is read from the
## environment only when a request is actually made.
from luce_config.toml import Table

## Configuration that does not match the declared AI schema.
pub let invalid: ErrorCode = ErrorCode.package(310)

## The providers a mode may name. Kept small on purpose; adding a provider is a
## deliberate change, not an open set.
pub func known_provider(name: str) -> bool:
    return name == "openrouter" or name == "claude_code"

## The built-in system prompt for a mode, used when the user leaves `system` blank. Each
## states the task plainly so the model answers directly rather than exploring with tools.
pub func default_system(name: str) -> str:
    if name == "spellcheck":
        return "You fix spelling and grammar in the document open in a live editor. First call read_selection to see whether the user selected text and which lines it covers; if nothing is selected, call read_document to see the whole numbered text. To correct the WHOLE document, prefer calling set_document ONCE with the entire corrected text — reliable and free of line-number mistakes. For a selected excerpt, edit only its lines with replace_lines. Fix ONLY spelling and grammar — preserve wording, meaning, code, formatting, and the number of lines. When done, reply with one short sentence summarising what changed."
    if name == "write":
        return "You edit the document open in a live editor to carry out the user's request. First call read_selection to see any selected text and the lines it covers, or read_document for the whole numbered text. To rewrite the whole document or a large part, call set_document ONCE with the full new text (reliable, no line-number arithmetic). For a small, targeted change, use replace_lines, insert_lines or delete_lines — each returns the updated numbered document, so always use the latest line numbers. If there is a selection, change only what it covers. When done, reply with one short sentence summarising what you did."
    if name == "ask":
        return "You are a concise coding assistant inside the luced editor. Answer the user's question about their project. Use the read_document, read_file, list_dir and find_text tools to inspect code when it helps, then give a direct, focused answer. Do not edit anything."
    if name == "inline":
        return "You complete code at the cursor. Reply with ONLY the code to insert — no explanation, no code fences. Do not call any tools."
    return ""

## One mode's settings: its provider (default openrouter), the model that answers
## it, and the system prompt prepended to each request. `model` is the provider's
## own id and may contain slashes (an OpenRouter id like "deepseek/deepseek-chat").
pub class Mode:
    pub let provider: str
    pub let model: str
    pub let system: str

    pub func init(self, provider: str = "openrouter", model: str = "", system: str = ""):
        self.provider = provider
        self.model = model
        self.system = system

    pub func chosen(self) -> bool:
        return self.model != ""

## How to reach one provider. A credential may be a literal `api_key` or the name
## of an environment variable in `key_env`; `command` names a local CLI provider.
pub class Provider:
    pub let name: str
    pub let api_key: str
    pub let key_env: str
    pub let base_url: str
    pub let command: str

    pub func init(self, name: str, api_key: str = "", key_env: str = "", base_url: str = "", command: str = ""):
        self.name = name
        self.api_key = api_key
        self.key_env = key_env
        self.base_url = base_url
        self.command = command

    ## Whether some credential source is declared. Whether it actually resolves
    ## (an environment variable being set, a command being on PATH) is a runtime
    ## question answered when a request is made, not here.
    pub func configured(self) -> bool:
        return self.api_key != "" or self.key_env != "" or self.command != ""

## The AI settings: a mode per role and the known providers' details.
pub class AiConfig:
    pub let ask: Mode
    pub let write: Mode
    pub let spellcheck: Mode
    pub let inline: Mode
    pub let openrouter: Provider
    pub let claude_code: Provider

    pub func init(self, source: str = "") -> unit!:
        let table = Table(source)
        table.check_within([
            "ask.provider", "ask.model", "ask.system",
            "write.provider", "write.model", "write.system",
            "spellcheck.provider", "spellcheck.model", "spellcheck.system",
            "inline.provider", "inline.model", "inline.system",
            "openrouter.api_key", "openrouter.key_env", "openrouter.base_url",
            "claude_code.command", "claude_code.model"], [])
        self.ask = read_mode(table, "ask")
        self.write = read_mode(table, "write")
        self.spellcheck = read_mode(table, "spellcheck")
        self.inline = read_mode(table, "inline")
        self.openrouter = Provider("openrouter",
            api_key = table.string("openrouter.api_key", ""),
            key_env = table.string("openrouter.key_env", ""),
            base_url = table.string("openrouter.base_url", "https://openrouter.ai/api/v1"))
        self.claude_code = Provider("claude_code",
            command = table.string("claude_code.command", "claude"),
            key_env = "")
        for name in ["ask", "write", "spellcheck", "inline"]:
            let picked = self.mode(name)
            if picked.chosen() and not known_provider(picked.provider):
                error(invalid, "Unknown provider in " + name + ".provider = \"" + picked.provider + "\"; use openrouter or claude_code")

    ## The settings for one mode ("ask", "write", "spellcheck", "inline"); an empty
    ## Mode for any other name. When the configured system prompt is blank, a sensible
    ## default is supplied so the model does the task instead of wandering through tools.
    pub func mode(self, name: str) -> Mode:
        let picked = self.mode_config(name)
        if picked.system != "":
            return picked
        return Mode(provider = picked.provider, model = picked.model, system = default_system(name))

    func mode_config(self, name: str) -> Mode:
        if name == "ask":
            return self.ask
        if name == "write":
            return self.write
        if name == "spellcheck":
            return self.spellcheck
        if name == "inline":
            return self.inline
        return Mode()

    pub func provider(self, name: str) -> Provider?:
        let which = self.mode(name).provider
        if which == "openrouter":
            return self.openrouter
        if which == "claude_code":
            return self.claude_code
        return none

    ## A mode is ready when it names a model and that model's provider has a
    ## declared credential. It still may fail at request time if the key is unset.
    pub func ready(self, name: str) -> bool:
        if not self.mode(name).chosen():
            return false
        let provider = self.provider(name) else return false
        return provider.configured()

func read_mode(table: Table, name: str) -> Mode!:
    return Mode(table.string(name + ".provider", "openrouter"), table.string(name + ".model", ""), table.string(name + ".system", ""))

## The starter `ai.toml`, created once and never rewritten. It carries no key: a
## fresh install has every mode unset and points OpenRouter at an env variable.
pub func defaults() -> str:
    return "# luced AI configuration. Keep this file private; it can hold API keys.\n# Each mode has a provider, a model id, and an optional system prompt.\n# Providers are openrouter and claude_code; model is that provider's own id.\n\n[ask]\nprovider = \"openrouter\"\nmodel = \"\"\nsystem = \"\"\n\n[write]\nprovider = \"openrouter\"\nmodel = \"\"\nsystem = \"\"\n\n[spellcheck]\nprovider = \"openrouter\"\nmodel = \"\"\nsystem = \"\"\n\n[inline]\nprovider = \"openrouter\"\nmodel = \"\"\nsystem = \"\"\n\n[openrouter]\n# Set api_key here, or leave it empty and export the key_env variable.\napi_key = \"\"\nkey_env = \"OPENROUTER_API_KEY\"\nbase_url = \"https://openrouter.ai/api/v1\"\n\n[claude_code]\ncommand = \"claude\"\n"

test "ai config parses modes, prompts and providers":
    let config = AiConfig(defaults())
    assert(config.ask.provider == "openrouter" and config.ask.model == "" and not config.ready("ask"))
    assert(config.openrouter.key_env == "OPENROUTER_API_KEY" and config.openrouter.configured())
    assert(config.claude_code.command == "claude" and config.claude_code.configured())
    let filled = AiConfig("[ask]\nmodel = \"deepseek/deepseek-v4.1-flash\"\nsystem = \"You are terse.\"\n[inline]\nprovider = \"claude_code\"\nmodel = \"sonnet\"\n[openrouter]\napi_key = \"sk-test\"\n")
    assert(filled.ask.provider == "openrouter" and filled.ask.model == "deepseek/deepseek-v4.1-flash")
    assert(filled.ask.system == "You are terse." and filled.ready("ask"))
    assert(filled.inline.provider == "claude_code" and filled.ready("inline"))

test "ai config rejects unknown providers and stray keys":
    var refused = false
    _ = AiConfig("[ask]\nprovider = \"mistral\"\nmodel = \"large\"\n") catch failure:
        refused = failure.code == invalid
        recover AiConfig()
    assert(refused)
    var stray = false
    _ = AiConfig("[openrouter]\ntoken = \"x\"\n") catch failure:
        stray = true
        recover AiConfig()
    assert(stray)