From 666d4e880ec3944910747e010ec91c4ae730bcbe Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:44:58 -0500 Subject: [PATCH 01/16] fix(window): tell the desktop shell when the window has painted, so it opens without the 20 s fallback (0.15.2) The macOS shell builds the main window at alpha 0 and shows it when the page invokes app_ready, or after its fallback. v0.1.0 removed revealApp's invoke while the repo had no desktop shell and it was never put back, so every macOS launch waited the full 20 s fallback after the engine was up. revealApp now waits two frames twice, each also settling after 120 ms because WebKit may hold requestAnimationFrame in an alpha 0 window, then invokes app_ready in the desktop shell only. No DOM node or style is touched. Measured in the browser build with a stub shell: app_ready now arrives 0.36 to 2.7 s after navigation (Chromium at 4x CPU throttle, WebKit 0.41 to 0.94 s); before it never arrived. --- web/src/main.ts | 2 ++ web/src/ui/dom.ts | 20 ++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/web/src/main.ts b/web/src/main.ts index 4927417..c527246 100644 --- a/web/src/main.ts +++ b/web/src/main.ts @@ -1,5 +1,6 @@ import { createEngine } from "./engine"; import { mountApp } from "./ui/app"; +import { revealApp } from "./ui/dom"; const engine = createEngine({ fetch: (input, init) => fetch(input, init), @@ -9,3 +10,4 @@ const engine = createEngine({ mountApp(engine); engine.start(); +revealApp(); diff --git a/web/src/ui/dom.ts b/web/src/ui/dom.ts index 7266cf8..48a07f2 100644 --- a/web/src/ui/dom.ts +++ b/web/src/ui/dom.ts @@ -53,6 +53,26 @@ export function nextFrame(): Promise { return new Promise((resolve) => requestAnimationFrame(() => resolve())); } +const REVEAL_WAIT = 120; +let revealed = false; + +function twoFrames(): Promise { + return new Promise((done) => { + requestAnimationFrame(() => requestAnimationFrame(() => done())); + window.setTimeout(done, REVEAL_WAIT); + }); +} + +export function revealApp(): void { + if (revealed || !("__TAURI_INTERNALS__" in window)) return; + revealed = true; + void twoFrames() + .then(() => twoFrames()) + .then(() => import("@tauri-apps/api/core")) + .then((m) => m.invoke("app_ready")) + .catch(() => undefined); +} + export function delayedIndicator(show: () => void, hide: () => void, delay = 300, minVisible = 250): () => void { let shownAt = 0; const timer = setTimeout(() => { From 0ad37caa7de45bb7fedbd698f20bb336a2dafa0d Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:45:02 -0500 Subject: [PATCH 02/16] fix(desktop): show the main window after 6 s, not 20 s, if the page never says it has painted (0.15.2) The fallback in reveal.rs is the only thing that showed the macOS window in 0.15.1, because the page never invoked app_ready. With the invoke back it is a safety net only, so a future break of the invoke, or a page that cannot reach Tauri's IPC, costs at most 6 s after the engine is ready instead of 20 s. The window is built with the dark background, so a fallback reveal of a page still loading shows that colour, not white. SPLASH_MIN stays 2.6 s, shared with the other Form apps. --- src-tauri/src/reveal.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src-tauri/src/reveal.rs b/src-tauri/src/reveal.rs index 1e18b4c..6d14efc 100644 --- a/src-tauri/src/reveal.rs +++ b/src-tauri/src/reveal.rs @@ -7,7 +7,7 @@ use tauri::{Manager, Runtime, WebviewWindow}; pub const SPLASH_MIN: Duration = Duration::from_millis(2600); pub const BACKGROUND: tauri::window::Color = tauri::window::Color(10, 10, 10, 255); const BAR_FINISH: Duration = Duration::from_millis(220); -const FALLBACK: Duration = Duration::from_secs(20); +const FALLBACK: Duration = Duration::from_secs(6); static LAUNCH: OnceLock = OnceLock::new(); static REVEALED: AtomicBool = AtomicBool::new(false); From 30a45a2bc7bf7c9ca1648343c610e2ef741df7c0 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:46:19 -0500 Subject: [PATCH 03/16] feat(agent): live stream, window command bridge, jobs and owner approval for agents (0.15.2) A new agent module gives agents the same reach as the person at the window without weakening any scope. GET /api/live streams a change event after every successful write, so the open window can show an agent's work at once, and carries approval requests and window command runs to the window. /api/agent/routes lists every engine route an agent may call; /api/agent/call runs one through the full router with the caller's own credential and compacts the answer (lists cut to a limit and counted, binary output withheld). /api/agent/commands lists, describes and runs the window's command registry. Posting, cancelling, allocating, amending, confirming, deleting, period locks, invitations and the app lock wait for the owner's yes in the window; sign-in, tokens, terminals and claiming are refused. Slow work answers a job id to poll. --- internal/agent/call.go | 469 ++++++++++++++++++++++++++++++++++++++ internal/agent/hub.go | 107 +++++++++ internal/agent/jobs.go | 162 +++++++++++++ internal/agent/module.go | 368 ++++++++++++++++++++++++++++++ internal/server/server.go | 2 + 5 files changed, 1108 insertions(+) create mode 100644 internal/agent/call.go create mode 100644 internal/agent/hub.go create mode 100644 internal/agent/jobs.go create mode 100644 internal/agent/module.go diff --git a/internal/agent/call.go b/internal/agent/call.go new file mode 100644 index 0000000..6d8708c --- /dev/null +++ b/internal/agent/call.go @@ -0,0 +1,469 @@ +package agent + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "regexp" + "sort" + "strings" + "time" + + "github.com/nodemode-ai/formledger/internal/httpx" + "github.com/nodemode-ai/formledger/internal/policy" +) + +const ( + defaultLimit = 50 + maxLimit = 500 + textCap = 4000 +) + +var ( + blockedPrefixes = []string{"/api/auth/", "/api/setup", "/api/desktop/", "/api/account/claim", "/api/me/tokens", "/api/me/key-backed-up", "/api/terminal", "/api/agent", "/api/live"} + inviteAccept = regexp.MustCompile(`^/api/invites/[^/]+/accept$`) + blockedCommands = map[string]bool{"session.setup": true, "session.login": true, "session.unlock": true, "invite.accept": true, "account.claim": true} + riskyCommands = map[string]bool{"invites.create": true, "invites.revoke": true, "account.lock": true, "session.logout": true, "app.quit": true, "window.close": true, "app.reload": true} + riskyWords = []string{"post", "cancel", "delete", "allocate", "amend", "confirm", "lock", "unlock"} +) + +func blocked(path string) bool { + for _, p := range blockedPrefixes { + if strings.HasPrefix(path, p) { + return true + } + } + return inviteAccept.MatchString(path) +} + +func routeClass(method, path string) string { + if !httpx.IsUnsafe(method) { + return "" + } + if method == http.MethodDelete { + return "delete" + } + last := path[strings.LastIndex(path, "/")+1:] + for _, w := range riskyWords { + if last == w { + return w + } + } + switch { + case path == "/api/invites": + return "invite" + case path == "/api/account/lock": + return "app lock" + } + return "" +} + +func commandClass(c Command) string { + if riskyCommands[c.ID] { + return c.ID + } + parts := strings.FieldsFunc(c.ID, func(r rune) bool { return r == '.' || r == '-' }) + for _, p := range parts[min(1, len(parts)):] { + for _, w := range riskyWords { + if strings.EqualFold(p, w) { + return w + } + } + } + if c.Risky { + return c.ID + } + return "" +} + +func (m *module) routes(w http.ResponseWriter, r *http.Request, _ *policy.Principal) error { + type row struct { + Route string `json:"route"` + Approve string `json:"approval,omitempty"` + } + var out []row + text := strings.ToLower(r.URL.Query().Get("text")) + for _, pat := range m.router.Patterns() { + method, path, ok := strings.Cut(pat, " ") + if !ok || !strings.HasPrefix(path, "/api/") || blocked(path) { + continue + } + if text != "" && !strings.Contains(strings.ToLower(pat), text) { + continue + } + out = append(out, row{Route: pat, Approve: routeClass(method, path)}) + } + sort.Slice(out, func(i, j int) bool { + a, b := strings.SplitN(out[i].Route, " ", 2), strings.SplitN(out[j].Route, " ", 2) + if a[1] != b[1] { + return a[1] < b[1] + } + return a[0] < b[0] + }) + httpx.JSON(w, http.StatusOK, map[string]any{"routes": out, "count": len(out), + "note": "Call any route with POST /api/agent/call (MCP: ledger_call). Routes with an approval class wait for the owner's yes in the window. Docs: docs/ledger, docs/selling, docs/buying, docs/stock."}) + return nil +} + +type callIn struct { + Method string `json:"method"` + Path string `json:"path"` + Query map[string]string `json:"query"` + Body json.RawMessage `json:"body"` + Limit int `json:"limit"` + Wait float64 `json:"wait"` +} + +func (m *module) inner() http.Handler { + m.once.Do(func() { m.handler = m.router.Handler() }) + return m.handler +} + +func (m *module) call(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + var in callIn + if err := httpx.Decode(r, &in); err != nil { + return err + } + in.Method = strings.ToUpper(strings.TrimSpace(in.Method)) + if in.Method == "" { + in.Method = http.MethodGet + } + switch in.Method { + case http.MethodGet, http.MethodPost, http.MethodPatch, http.MethodPut, http.MethodDelete: + default: + return httpx.Fail(http.StatusBadRequest, "bad_method", "method must be GET, POST, PATCH, PUT or DELETE") + } + path := "/" + strings.TrimLeft(strings.TrimSpace(in.Path), "/") + if !strings.HasPrefix(path, "/api/") || strings.Contains(path, "..") || strings.ContainsAny(path, "?#") { + return httpx.Fail(http.StatusBadRequest, "bad_path", "path must be an /api/ route without a query string; pass query separately (see ledger_routes)") + } + if blocked(path) { + return httpx.Fail(http.StatusForbidden, "agent_blocked", "agents may not call "+path+": sign-in, tokens, terminals and claiming stay with the person at the window") + } + if p.ReadOnly && httpx.IsUnsafe(in.Method) { + return httpx.ErrReadOnly + } + limit := in.Limit + if limit <= 0 { + limit = defaultLimit + } + limit = min(limit, maxLimit) + q := make([]string, 0, len(in.Query)) + for k, v := range in.Query { + q = append(q, k+"="+urlEscape(v)) + } + sort.Strings(q) + target := path + if len(q) > 0 { + target += "?" + strings.Join(q, "&") + } + what := in.Method + " " + target + x := m.jobs.start(p.UserID, "call", what) + class := routeClass(in.Method, path) + auth, cookie, agentName, remote, host := r.Header.Get("Authorization"), r.Header.Values("Cookie"), "", r.RemoteAddr, r.Host + _, agentName = m.agentOf(r, p) + ctx := context.WithoutCancel(r.Context()) + go func() { + if class != "" { + if err := m.ask(r.WithContext(ctx), p, x, class, what, []string{describeBody(in.Body)}); err != nil { + m.jobs.finish(x, deniedOr(err), nil, err.Error()) + return + } + } + var body *bytes.Reader + if len(in.Body) > 0 && string(in.Body) != "null" { + body = bytes.NewReader(in.Body) + } else { + body = bytes.NewReader(nil) + } + req, err := http.NewRequestWithContext(ctx, in.Method, target, body) + if err != nil { + m.jobs.finish(x, "failed", nil, err.Error()) + return + } + if auth != "" { + req.Header.Set("Authorization", auth) + } + for _, c := range cookie { + req.Header.Add("Cookie", c) + } + req.Header.Set("Accept", "application/json") + if body.Len() > 0 { + req.Header.Set("Content-Type", "application/json") + } + req.Header.Set(AgentHeader, agentName) + req.RemoteAddr, req.Host = remote, host + rec := httptest.NewRecorder() + m.inner().ServeHTTP(rec, req) + res := compactResponse(rec, limit) + if rec.Code >= 400 { + m.jobs.finish(x, "failed", res, fmt.Sprintf("%s answered %d", what, rec.Code)) + return + } + m.jobs.finish(x, "done", res, "") + }() + j := m.jobs.wait(x, waitOf(r, in.Wait)) + if j.State == "failed" && j.Result != nil { + httpx.JSON(w, http.StatusOK, map[string]any{"job": j.ID, "state": j.State, "what": j.What, "error": j.Error, "result": j.Result}) + return nil + } + m.reply(w, j) + return nil +} + +func deniedOr(err error) string { + var api *httpx.APIError + if errors.As(err, &api) && (api.Code == "consent_denied" || api.Code == "consent_timeout" || api.Code == "consent_needs_window") { + return "denied" + } + return "failed" +} + +func describeBody(raw json.RawMessage) string { + s := strings.TrimSpace(string(raw)) + if s == "" || s == "null" { + return "No request body." + } + return "Body: " + clip(s, 400) +} + +func urlEscape(s string) string { + var b strings.Builder + for _, c := range []byte(s) { + if c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '-' || c == '_' || c == '.' || c == '~' { + b.WriteByte(c) + continue + } + fmt.Fprintf(&b, "%%%02X", c) + } + return b.String() +} + +func compactResponse(rec *httptest.ResponseRecorder, limit int) json.RawMessage { + ct := rec.Header().Get("Content-Type") + raw := rec.Body.Bytes() + out := map[string]any{"status": rec.Code} + switch { + case strings.Contains(ct, "json"): + var v any + if json.Unmarshal(raw, &v) == nil { + cut := map[string]int{} + out["data"] = compactValue(v, limit, "", cut) + if len(cut) > 0 { + out["truncated"] = cut + out["note"] = fmt.Sprintf("lists longer than %d were cut; the counts are their full lengths. Ask with a larger limit (up to %d), a filter or a cursor.", limit, maxLimit) + } + } + case strings.HasPrefix(ct, "text/"): + lines := strings.Split(string(raw), "\n") + keep := min(len(lines), limit+1) + text := strings.Join(lines[:keep], "\n") + out["contentType"], out["lines"], out["text"] = ct, len(lines), clip(text, textCap) + default: + out["contentType"], out["bytes"] = ct, len(raw) + out["note"] = "binary output is not sent to agents; save it with ./formledger cli print or export --out FILE" + } + b, _ := json.Marshal(out) + return b +} + +func compactRaw(raw json.RawMessage, limit int) json.RawMessage { + if len(raw) == 0 { + return nil + } + var v any + if json.Unmarshal(raw, &v) != nil { + return nil + } + cut := map[string]int{} + v = compactValue(v, limit, "", cut) + if len(cut) > 0 { + v = map[string]any{"data": v, "truncated": cut} + } + b, _ := json.Marshal(v) + return b +} + +func compactValue(v any, limit int, at string, cut map[string]int) any { + switch t := v.(type) { + case []any: + if len(t) > limit { + cut[strings.TrimPrefix(at, ".")+"[]"] = len(t) + t = t[:limit] + } + for i := range t { + t[i] = compactValue(t[i], limit, at, cut) + } + return t + case map[string]any: + for k, x := range t { + t[k] = compactValue(x, limit, at+"."+k, cut) + } + return t + case string: + return clip(t, textCap) + } + return v +} + +func (m *module) commandsOf(user string) []Command { + m.catMu.Lock() + defer m.catMu.Unlock() + return append([]Command(nil), m.catalogue[user]...) +} + +func (m *module) find(user, id string) (Command, bool) { + for _, c := range m.commandsOf(user) { + if c.ID == id { + return c, true + } + } + return Command{}, false +} + +func (m *module) near(user, id string) []string { + word := strings.ToLower(id[strings.LastIndexAny(id, ".-")+1:]) + var out []string + for _, c := range m.commandsOf(user) { + if word != "" && strings.Contains(strings.ToLower(c.ID), word) && len(out) < 5 { + out = append(out, c.ID) + } + } + return out +} + +func (m *module) noWindow(user string) error { + if m.hub.windows(user) > 0 { + return nil + } + return httpx.Fail(http.StatusConflict, "no_window", "no FormLedger window is open for this user: open the app (./formledger, or the desktop app) and sign in, then retry. Headless work goes through ledger_call.") +} + +func (m *module) listCommands(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + group := strings.ToLower(strings.TrimSpace(r.URL.Query().Get("group"))) + text := strings.Fields(strings.ToLower(r.URL.Query().Get("text"))) + type row struct { + ID string `json:"id"` + Label string `json:"label"` + Group string `json:"group"` + Args string `json:"args,omitempty"` + Approval string `json:"approval,omitempty"` + Off bool `json:"unavailable,omitempty"` + } + all := m.commandsOf(p.UserID) + groups := map[string]bool{} + var out []row + for _, c := range all { + if blockedCommands[c.ID] { + continue + } + groups[c.Group] = true + if group != "" && strings.ToLower(c.Group) != group { + continue + } + hay := strings.ToLower(c.ID + " " + c.Label + " " + c.Group + " " + c.Description) + ok := true + for _, t := range text { + ok = ok && strings.Contains(hay, t) + } + if !ok { + continue + } + names := make([]string, 0, len(c.Params)) + for k := range c.Params { + names = append(names, k) + } + sort.Strings(names) + out = append(out, row{ID: c.ID, Label: c.Label, Group: c.Group, Args: strings.Join(names, ","), Approval: commandClass(c), Off: c.Enabled != nil && !*c.Enabled}) + } + gl := make([]string, 0, len(groups)) + for g := range groups { + gl = append(gl, g) + } + sort.Strings(gl) + res := map[string]any{"size": len(all), "shown": len(out), "groups": gl, "windows": m.hub.windows(p.UserID), "commands": out} + if len(all) == 0 { + res["hint"] = "the catalogue is empty: open the FormLedger window and sign in; it sends its commands within a second" + } + httpx.JSON(w, http.StatusOK, res) + return nil +} + +func (m *module) describeCommand(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + id := r.PathValue("id") + c, ok := m.find(p.UserID, id) + if !ok || blockedCommands[id] { + return httpx.Fail(http.StatusNotFound, "no_command", "no command has the id "+id+nearText(m.near(p.UserID, id))) + } + out := map[string]any{"command": c} + if cl := commandClass(c); cl != "" { + out["approval"] = cl + } + httpx.JSON(w, http.StatusOK, out) + return nil +} + +func nearText(ids []string) string { + if len(ids) == 0 { + return "; search with app_commands" + } + return "; did you mean " + strings.Join(ids, ", ") + "?" +} + +func (m *module) runCommand(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + id := r.PathValue("id") + var in struct { + Params map[string]any `json:"params"` + Wait float64 `json:"wait"` + } + if r.ContentLength != 0 { + if err := httpx.Decode(r, &in); err != nil { + return err + } + } + if blockedCommands[id] { + return httpx.Fail(http.StatusForbidden, "agent_blocked", id+" handles a password or claims the books; it stays with the person at the window") + } + if err := m.noWindow(p.UserID); err != nil { + return err + } + c, ok := m.find(p.UserID, id) + if !ok { + return httpx.Fail(http.StatusNotFound, "no_command", "no command has the id "+id+nearText(m.near(p.UserID, id))) + } + if c.Mutates && p.ReadOnly { + return httpx.ErrReadOnly + } + if in.Params == nil { + in.Params = map[string]any{} + } + what := c.Label + " (" + id + ")" + x := m.jobs.start(p.UserID, "command", what) + class := commandClass(c) + ctx := context.WithoutCancel(r.Context()) + go func() { + if class != "" { + pj, _ := json.Marshal(in.Params) + if err := m.ask(r.WithContext(ctx), p, x, class, what, []string{"Arguments: " + clip(string(pj), 400)}); err != nil { + m.jobs.finish(x, deniedOr(err), nil, err.Error()) + return + } + } + if !m.hub.toNewestWindow(p.UserID, "command", map[string]any{"job": x.ID, "id": id, "params": in.Params}) { + m.jobs.finish(x, "failed", nil, "no FormLedger window took the command; open the app and retry") + return + } + select { + case <-x.done: + case <-time.After(windowWait): + m.jobs.finish(x, "failed", nil, "the window did not answer within two minutes") + case <-m.quit: + } + }() + m.reply(w, m.jobs.wait(x, waitOf(r, in.Wait))) + return nil +} diff --git a/internal/agent/hub.go b/internal/agent/hub.go new file mode 100644 index 0000000..fd72259 --- /dev/null +++ b/internal/agent/hub.go @@ -0,0 +1,107 @@ +package agent + +import ( + "encoding/json" + "sync" + "time" +) + +type event struct { + name string + data []byte +} + +type client struct { + user string + window bool + since time.Time + ch chan event +} + +type hub struct { + mu sync.Mutex + clients map[*client]struct{} +} + +func newHub() *hub { return &hub{clients: map[*client]struct{}{}} } + +func (h *hub) join(user string, window bool) *client { + c := &client{user: user, window: window, since: time.Now(), ch: make(chan event, 64)} + h.mu.Lock() + h.clients[c] = struct{}{} + h.mu.Unlock() + return c +} + +func (h *hub) leave(c *client) { + h.mu.Lock() + delete(h.clients, c) + h.mu.Unlock() +} + +func encode(name string, v any) event { + b, _ := json.Marshal(v) + return event{name: name, data: b} +} + +func (h *hub) broadcast(name string, v any) { + e := encode(name, v) + h.mu.Lock() + defer h.mu.Unlock() + for c := range h.clients { + select { + case c.ch <- e: + default: + } + } +} + +func (h *hub) toUser(user, name string, v any) int { + e := encode(name, v) + h.mu.Lock() + defer h.mu.Unlock() + n := 0 + for c := range h.clients { + if c.user != user || !c.window { + continue + } + select { + case c.ch <- e: + n++ + default: + } + } + return n +} + +func (h *hub) toNewestWindow(user, name string, v any) bool { + h.mu.Lock() + defer h.mu.Unlock() + var best *client + for c := range h.clients { + if c.user == user && c.window && (best == nil || c.since.After(best.since)) { + best = c + } + } + if best == nil { + return false + } + select { + case best.ch <- encode(name, v): + return true + default: + return false + } +} + +func (h *hub) windows(user string) int { + h.mu.Lock() + defer h.mu.Unlock() + n := 0 + for c := range h.clients { + if c.user == user && c.window { + n++ + } + } + return n +} diff --git a/internal/agent/jobs.go b/internal/agent/jobs.go new file mode 100644 index 0000000..b6489af --- /dev/null +++ b/internal/agent/jobs.go @@ -0,0 +1,162 @@ +package agent + +import ( + "encoding/json" + "sync" + "time" + + "github.com/nodemode-ai/formledger/internal/ids" +) + +const ( + jobKeep = 10 * time.Minute + consentWait = 2 * time.Minute + windowWait = 2 * time.Minute +) + +type job struct { + ID string `json:"job"` + Kind string `json:"kind"` + What string `json:"what"` + State string `json:"state"` + Result json.RawMessage `json:"result,omitempty"` + Error string `json:"error,omitempty"` + Started int64 `json:"started"` + Finished int64 `json:"finished,omitempty"` + user string + done chan struct{} +} + +type jobs struct { + mu sync.Mutex + byID map[string]*job +} + +func newJobs() *jobs { return &jobs{byID: map[string]*job{}} } + +func (j *jobs) start(user, kind, what string) *job { + x := &job{ID: "job_" + ids.New(), Kind: kind, What: what, State: "running", Started: time.Now().UnixMilli(), user: user, done: make(chan struct{})} + j.mu.Lock() + defer j.mu.Unlock() + for id, old := range j.byID { + if old.Finished > 0 && time.Since(time.UnixMilli(old.Finished)) > jobKeep { + delete(j.byID, id) + } + } + j.byID[x.ID] = x + return x +} + +func (j *jobs) get(id, user string) *job { + j.mu.Lock() + defer j.mu.Unlock() + x := j.byID[id] + if x == nil || x.user != user { + return nil + } + return x +} + +func (j *jobs) set(x *job, state string) { + j.mu.Lock() + defer j.mu.Unlock() + if x.Finished == 0 { + x.State = state + } +} + +func (j *jobs) finish(x *job, state string, result json.RawMessage, err string) { + j.mu.Lock() + defer j.mu.Unlock() + if x.Finished > 0 { + return + } + x.State, x.Result, x.Error, x.Finished = state, result, err, time.Now().UnixMilli() + close(x.done) +} + +func (j *jobs) snapshot(x *job) job { + j.mu.Lock() + defer j.mu.Unlock() + return job{ID: x.ID, Kind: x.Kind, What: x.What, State: x.State, Result: x.Result, Error: x.Error, Started: x.Started, Finished: x.Finished} +} + +func (j *jobs) wait(x *job, d time.Duration) job { + select { + case <-x.done: + case <-time.After(d): + } + return j.snapshot(x) +} + +type consentAsk struct { + ID string `json:"id"` + Agent string `json:"agent"` + What string `json:"what"` + Offers []string `json:"offers"` + Always string `json:"always"` + Expires int64 `json:"expires"` + Escape string `json:"escape"` + Notes []string `json:"notes,omitempty"` + user string + key string + answer chan string +} + +type consents struct { + mu sync.Mutex + pending map[string]*consentAsk + allowed map[string]bool +} + +func newConsents() *consents { + return &consents{pending: map[string]*consentAsk{}, allowed: map[string]bool{}} +} + +func (c *consents) remembered(key string) bool { + c.mu.Lock() + defer c.mu.Unlock() + return c.allowed[key] +} + +func (c *consents) open(user, key, agent, what string, notes []string) *consentAsk { + a := &consentAsk{ID: "consent_" + ids.New(), Agent: agent, What: what, Offers: []string{"deny", "once", "always"}, Always: "agent", + Expires: time.Now().Add(consentWait).UnixMilli(), Escape: "deny", Notes: notes, user: user, key: key, answer: make(chan string, 1)} + c.mu.Lock() + c.pending[a.ID] = a + c.mu.Unlock() + return a +} + +func (c *consents) close(id string) { + c.mu.Lock() + delete(c.pending, id) + c.mu.Unlock() +} + +func (c *consents) answer(id, user, choice string) bool { + c.mu.Lock() + defer c.mu.Unlock() + a := c.pending[id] + if a == nil || a.user != user { + return false + } + if choice == "always" { + c.allowed[a.key] = true + } + delete(c.pending, id) + a.answer <- choice + return true +} + +func (c *consents) mine(user string) []*consentAsk { + c.mu.Lock() + defer c.mu.Unlock() + var out []*consentAsk + for _, a := range c.pending { + if a.user == user { + out = append(out, a) + } + } + return out +} diff --git a/internal/agent/module.go b/internal/agent/module.go new file mode 100644 index 0000000..37b6b57 --- /dev/null +++ b/internal/agent/module.go @@ -0,0 +1,368 @@ +package agent + +import ( + "encoding/json" + "fmt" + "net/http" + "net/url" + "sort" + "strings" + "sync" + "time" + + "github.com/nodemode-ai/formledger/internal/app" + "github.com/nodemode-ai/formledger/internal/auth" + "github.com/nodemode-ai/formledger/internal/httpx" + "github.com/nodemode-ai/formledger/internal/policy" +) + +const ( + AgentHeader = "X-FormLedger-Agent" + WindowHeader = "X-FormLedger-Window" + keepAlive = 20 * time.Second +) + +type module struct { + auth *auth.Service + hub *hub + jobs *jobs + consent *consents + router *httpx.Router + once sync.Once + handler http.Handler + quit chan struct{} + stopOnce sync.Once + catMu sync.Mutex + catalogue map[string][]Command +} + +type Command struct { + ID string `json:"id"` + Label string `json:"label"` + Group string `json:"group"` + Description string `json:"description,omitempty"` + When string `json:"when,omitempty"` + Keys []string `json:"keys,omitempty"` + Params map[string]json.RawMessage `json:"params,omitempty"` + Mutates bool `json:"mutates"` + Risky bool `json:"risky,omitempty"` + Enabled *bool `json:"enabled,omitempty"` +} + +func Module(a *auth.Service) app.Module { + return &module{auth: a, hub: newHub(), jobs: newJobs(), consent: newConsents(), quit: make(chan struct{}), catalogue: map[string][]Command{}} +} + +func (m *module) ID() string { return "agent" } + +func (m *module) Stop() { m.stopOnce.Do(func() { close(m.quit) }) } + +func (m *module) Mount(r *httpx.Router, _ *app.Deps) error { + m.router = r + r.Use(m.changes) + r.HandleFunc("GET /api/live", m.auth.Session(m.live)) + r.HandleFunc("POST /api/agent/window/catalogue", m.auth.Session(m.windowOnly(m.putCatalogue))) + r.HandleFunc("POST /api/agent/window/result", m.auth.Session(m.windowOnly(m.putResult))) + r.HandleFunc("POST /api/agent/consent/{id}", m.auth.Session(m.windowOnly(m.answer))) + r.HandleFunc("GET /api/agent", m.auth.Public(m.signed(m.overview))) + r.HandleFunc("GET /api/agent/routes", m.auth.Public(m.signed(m.routes))) + r.HandleFunc("POST /api/agent/call", m.auth.Public(m.signed(m.call))) + r.HandleFunc("GET /api/agent/commands", m.auth.Public(m.signed(m.listCommands))) + r.HandleFunc("GET /api/agent/commands/{id}", m.auth.Public(m.signed(m.describeCommand))) + r.HandleFunc("POST /api/agent/commands/{id}", m.auth.Public(m.signed(m.runCommand))) + r.HandleFunc("GET /api/agent/jobs/{id}", m.auth.Public(m.signed(m.jobStatus))) + return nil +} + +func (m *module) signed(h auth.PrincipalHandler) auth.Handler { + return func(w http.ResponseWriter, r *http.Request) error { + p := auth.PrincipalFrom(r.Context()) + if p == nil { + return httpx.ErrUnauthorized + } + return h(w, r, p) + } +} + +func (m *module) windowOnly(h auth.PrincipalHandler) auth.PrincipalHandler { + return func(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + if o := r.Header.Get("Origin"); o != "" { + u, err := url.Parse(o) + if err != nil || !strings.EqualFold(u.Host, r.Host) { + return httpx.Fail(http.StatusForbidden, "window_only", "only the FormLedger window may answer here") + } + } + return h(w, r, p) + } +} + +type statusWriter struct { + http.ResponseWriter + code int +} + +func (s *statusWriter) WriteHeader(code int) { + if s.code == 0 { + s.code = code + } + s.ResponseWriter.WriteHeader(code) +} + +func (s *statusWriter) Write(b []byte) (int, error) { + if s.code == 0 { + s.code = http.StatusOK + } + return s.ResponseWriter.Write(b) +} + +func (s *statusWriter) Unwrap() http.ResponseWriter { return s.ResponseWriter } + +var quietPrefixes = []string{"/api/live", "/api/agent/", "/api/terminal", "/api/auth/", "/api/me/key-backed-up"} + +func quiet(path string) bool { + for _, p := range quietPrefixes { + if strings.HasPrefix(path, p) { + return true + } + } + return false +} + +func (m *module) changes(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !httpx.IsUnsafe(r.Method) || !strings.HasPrefix(r.URL.Path, "/api/") || quiet(r.URL.Path) { + next.ServeHTTP(w, r) + return + } + sw := &statusWriter{ResponseWriter: w} + next.ServeHTTP(sw, r) + if sw.code >= 400 { + return + } + by := "window" + if p := auth.PrincipalFrom(r.Context()); p != nil && p.AppToken { + by = "token" + } + if r.Header.Get(AgentHeader) != "" { + by = "agent" + } + m.hub.broadcast("change", map[string]any{"method": r.Method, "path": r.URL.Path, "area": area(r.URL.Path), "by": by, + "agent": clip(r.Header.Get(AgentHeader), 80), "window": clip(r.Header.Get(WindowHeader), 64), "at": time.Now().UnixMilli()}) + }) +} + +func area(path string) string { + parts := strings.Split(strings.TrimPrefix(path, "/api/"), "/") + if len(parts) > 1 && (parts[0] == "sales" || parts[0] == "purchase" || parts[0] == "stock" || parts[0] == "delivery" || parts[0] == "reports") { + return parts[0] + "/" + parts[1] + } + return parts[0] +} + +func clip(s string, n int) string { + if len(s) > n { + return s[:n] + } + return s +} + +func (m *module) live(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + rc := http.NewResponseController(w) + h := w.Header() + h.Set("Content-Type", "text/event-stream") + h.Set("Cache-Control", "no-store") + h.Set("X-Accel-Buffering", "no") + w.WriteHeader(http.StatusOK) + window := r.URL.Query().Get("window") == "1" + c := m.hub.join(p.UserID, window) + defer m.hub.leave(c) + send := func(e event) bool { + if _, err := fmt.Fprintf(w, "event: %s\ndata: %s\n\n", e.name, e.data); err != nil { + return false + } + return rc.Flush() == nil + } + if !send(encode("hello", map[string]any{"window": window, "windows": m.hub.windows(p.UserID)})) { + return nil + } + if window { + for _, a := range m.consent.mine(p.UserID) { + if !send(encode("consent", a)) { + return nil + } + } + } + tick := time.NewTicker(keepAlive) + defer tick.Stop() + for { + select { + case <-r.Context().Done(): + return nil + case <-m.quit: + return nil + case <-tick.C: + if _, err := fmt.Fprint(w, ": keep-alive\n\n"); err != nil || rc.Flush() != nil { + return nil + } + case e := <-c.ch: + if !send(e) { + return nil + } + } + } +} + +func (m *module) putCatalogue(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + var in struct { + Commands []Command `json:"commands"` + } + if err := httpx.Decode(r, &in); err != nil { + return err + } + sort.Slice(in.Commands, func(i, j int) bool { return in.Commands[i].ID < in.Commands[j].ID }) + m.catMu.Lock() + m.catalogue[p.UserID] = in.Commands + m.catMu.Unlock() + httpx.JSON(w, http.StatusOK, map[string]any{"ok": true, "size": len(in.Commands)}) + return nil +} + +func (m *module) putResult(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + var in struct { + Job string `json:"job"` + OK bool `json:"ok"` + Result json.RawMessage `json:"result"` + Error string `json:"error"` + } + if err := httpx.Decode(r, &in); err != nil { + return err + } + x := m.jobs.get(in.Job, p.UserID) + if x == nil { + return httpx.Fail(http.StatusNotFound, "job_gone", "no such job") + } + if in.OK { + m.jobs.finish(x, "done", compactRaw(in.Result, defaultLimit), "") + } else { + m.jobs.finish(x, "failed", nil, clip(in.Error, 2000)) + } + httpx.JSON(w, http.StatusOK, map[string]bool{"ok": true}) + return nil +} + +func (m *module) answer(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + var in struct { + Choice string `json:"choice"` + } + if err := httpx.Decode(r, &in); err != nil { + return err + } + if in.Choice != "deny" && in.Choice != "once" && in.Choice != "always" { + return httpx.Fail(http.StatusBadRequest, "bad_choice", "choice must be deny, once or always") + } + if !m.consent.answer(r.PathValue("id"), p.UserID, in.Choice) { + return httpx.Fail(http.StatusNotFound, "consent_gone", "this request is no longer waiting") + } + m.hub.toUser(p.UserID, "consent-closed", map[string]string{"id": r.PathValue("id")}) + httpx.JSON(w, http.StatusOK, map[string]bool{"ok": true}) + return nil +} + +func (m *module) agentOf(r *http.Request, p *policy.Principal) (key, name string) { + a := m.auth.Actor(r, p) + key = a.Kind + ":" + a.ID + if a.Kind != "app_token" { + key = "session:" + p.UserID + } + name = strings.TrimSpace(r.Header.Get(AgentHeader)) + switch { + case name != "" && a.Kind == "app_token": + name = clip(name, 60) + " (app token " + a.Name + ")" + case name == "" && a.Kind == "app_token": + name = "App token " + a.Name + case name == "": + name = "An agent" + } + return key, name +} + +func (m *module) ask(r *http.Request, p *policy.Principal, x *job, class, what string, notes []string) error { + key, name := m.agentOf(r, p) + key += "|" + class + if m.consent.remembered(key) { + return nil + } + if m.hub.windows(p.UserID) == 0 { + return httpx.Fail(http.StatusConflict, "consent_needs_window", "this action needs the owner's approval in the FormLedger window, and no window is open for this user: open FormLedger, then retry") + } + a := m.consent.open(p.UserID, key, name, what, notes) + m.jobs.set(x, "waiting_consent") + m.hub.toUser(p.UserID, "consent", a) + select { + case choice := <-a.answer: + if choice == "deny" { + return httpx.Fail(http.StatusForbidden, "consent_denied", "the person at the FormLedger window said no to: "+what) + } + m.jobs.set(x, "running") + return nil + case <-time.After(consentWait): + m.consent.close(a.ID) + m.hub.toUser(p.UserID, "consent-closed", map[string]string{"id": a.ID}) + return httpx.Fail(http.StatusRequestTimeout, "consent_timeout", "nobody answered the approval request in the FormLedger window within two minutes: "+what) + case <-m.quit: + return httpx.Fail(http.StatusServiceUnavailable, "stopping", "FormLedger is stopping") + } +} + +func waitOf(r *http.Request, asked float64) time.Duration { + s := asked + if q := r.URL.Query().Get("wait"); q != "" { + fmt.Sscanf(q, "%g", &s) + } + if s <= 0 { + s = 15 + } + if s > 60 { + s = 60 + } + return time.Duration(s * float64(time.Second)) +} + +func (m *module) reply(w http.ResponseWriter, j job) { + out := map[string]any{"job": j.ID, "state": j.State, "what": j.What} + switch j.State { + case "done": + out["result"] = j.Result + case "failed", "denied": + out["error"] = j.Error + default: + out["hint"] = "still " + strings.ReplaceAll(j.State, "_", " ") + "; poll GET /api/agent/jobs/" + j.ID + "?wait=30 (MCP: job_status)" + } + httpx.JSON(w, http.StatusOK, out) +} + +func (m *module) jobStatus(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + x := m.jobs.get(r.PathValue("id"), p.UserID) + if x == nil { + return httpx.Fail(http.StatusNotFound, "job_gone", "no such job, or it finished more than ten minutes ago") + } + d := time.Duration(0) + if r.URL.Query().Get("wait") != "" { + d = waitOf(r, 0) + } + m.reply(w, m.jobs.wait(x, d)) + return nil +} + +func (m *module) overview(w http.ResponseWriter, r *http.Request, p *policy.Principal) error { + m.catMu.Lock() + n := len(m.catalogue[p.UserID]) + m.catMu.Unlock() + httpx.JSON(w, http.StatusOK, map[string]any{ + "user": p.Email, "role": p.Role, "readOnly": p.ReadOnly, "windows": m.hub.windows(p.UserID), "commands": n, + "read": []string{"GET /api/agent/routes", "GET /api/agent/commands?text=word", "GET /api/agent/commands/{id}", "GET /api/agent/jobs/{id}"}, + "write": []string{"POST /api/agent/call {method, path, query, body, limit}", "POST /api/agent/commands/{id} {params, wait}"}, + "rules": "Money-moving, destructive and people actions wait for the owner's approval in the open window. Results are compact: lists over the limit are cut and counted. Long work answers a job id to poll.", + }) + return nil +} diff --git a/internal/server/server.go b/internal/server/server.go index 56d0ebc..a787ed5 100644 --- a/internal/server/server.go +++ b/internal/server/server.go @@ -5,6 +5,7 @@ import ( "io/fs" "log/slog" + "github.com/nodemode-ai/formledger/internal/agent" "github.com/nodemode-ai/formledger/internal/app" "github.com/nodemode-ai/formledger/internal/auditapi" "github.com/nodemode-ai/formledger/internal/auth" @@ -55,6 +56,7 @@ func Build(ctx context.Context, cfg config.Config, log *slog.Logger, st *store.S s.Modules = []app.Module{ health{}, accounts.Module(), + agent.Module(accounts), auditapi.Module(accounts.Audit(), accounts), billing.Module(st, accounts), coa.Module(st, accounts), From bb02a7cb8a5eb385f34590d78919806efd86518a Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:46:28 -0500 Subject: [PATCH 04/16] feat(cli): formledger cli mcp, an MCP server on stdio for Claude Code and other agents (0.15.2) The MCP server is a client of the running server with the same app token as the command line, so one process stays the only writer and the token's role and scope decide what it may do. Tools: ledger_overview, ledger_routes, ledger_get and ledger_call over every engine route, ledger_cli for any cli command, ledger_export and ledger_print to files on this computer, app_commands, app_command and app_run for the open window's command registry, and job_status. Writes made through it go through /api/agent/call, so posting, cancelling, deleting and the other approval classes wait for the owner in the window even when they come in as a cli command. --- internal/cli/cli.go | 7 +- internal/cli/client.go | 11 ++ internal/cli/mcp.go | 370 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 387 insertions(+), 1 deletion(-) create mode 100644 internal/cli/mcp.go diff --git a/internal/cli/cli.go b/internal/cli/cli.go index 60c0f85..7df65fe 100644 --- a/internal/cli/cli.go +++ b/internal/cli/cli.go @@ -57,11 +57,16 @@ func groups() []group { {"statement", "profit and loss and the balance sheet", statementVerbs()}, {"whoami", "the user and role behind the app token", []verb{whoamiVerb()}}, {"token", "how to make an app token", []verb{tokenVerb()}}, + {"mcp", "an MCP server on standard input and output for Claude Code, Codex, Cursor and other agents", []verb{mcpVerb()}}, } } func Run(args []string, out, errw io.Writer) int { - e := &env{out: out, errw: errw} + return (&env{out: out, errw: errw}).run(args) +} + +func (e *env) run(args []string) int { + out, errw := e.out, e.errw if len(args) == 0 || isHelp(args[0]) || args[0] == "help" { usage(out) return 0 diff --git a/internal/cli/client.go b/internal/cli/client.go index 747acf4..c43177e 100644 --- a/internal/cli/client.go +++ b/internal/cli/client.go @@ -23,6 +23,7 @@ type Client struct { Base string Token string HTTP *http.Client + Agent string } type userError struct{ msg string } @@ -51,6 +52,13 @@ func NewClient(tokenFile string) (*Client, error) { } func (c *Client) Do(method, path string, q url.Values, body any) (json.RawMessage, error) { + if c.Agent != "" && method != http.MethodGet && method != http.MethodHead { + return c.viaAgent(method, path, q, body) + } + return c.direct(method, path, q, body) +} + +func (c *Client) direct(method, path string, q url.Values, body any) (json.RawMessage, error) { u := c.Base + path if len(q) > 0 { u += "?" + q.Encode() @@ -69,6 +77,9 @@ func (c *Client) Do(method, path string, q url.Values, body any) (json.RawMessag } req.Header.Set("Authorization", "Bearer "+c.Token) req.Header.Set("Accept", "application/json") + if c.Agent != "" { + req.Header.Set("X-FormLedger-Agent", c.Agent) + } if body != nil { req.Header.Set("Content-Type", "application/json") } diff --git a/internal/cli/mcp.go b/internal/cli/mcp.go new file mode 100644 index 0000000..698169f --- /dev/null +++ b/internal/cli/mcp.go @@ -0,0 +1,370 @@ +package cli + +import ( + "bufio" + "bytes" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "sync" + + "github.com/nodemode-ai/formledger/internal/app" + "github.com/nodemode-ai/formledger/internal/export" + "github.com/nodemode-ai/formledger/internal/printout" +) + +const ( + mcpProtocol = "2025-06-18" + mcpTextCap = 24000 + AgentEnv = "FORMLEDGER_AGENT" +) + +const mcpInstructions = `FormLedger is a local-first business ledger: selling, buying, stock, the general ledger and reports. This server is a client of the running FormLedger server with your app token (FORMLEDGER_TOKEN); it never opens the database. + +Two ways in, same rules: +- Headless, over the books: ledger_routes lists every engine route; ledger_get reads one; ledger_call writes; ledger_cli runs any "formledger cli" command (accounts, customers, sales, invoice, payment, purchase, bill, pay, receipt, delivery, stock, report, statement, receivables, payables). Money is whole minor units plus a currency code; never send a float. +- The open window: app_commands lists every command of the FormLedger window (menus, buttons, pages, Preferences) with typed arguments; app_command describes one; app_run runs it in the window. view.open moves the window to any page or document, view.current says what is on screen. + +Posting, cancelling, allocating, amending, confirming, deleting, period locks, invitations and the app lock wait for the owner to say yes in the FormLedger window (Deny, Allow once, Always allow for this agent). Without an open window they are refused, so ask the person to open FormLedger. Sign-in, passwords, tokens, terminals and claiming the books are never reachable from here. + +Every change shows live in the open window. Results are compact: lists longer than the limit are cut and their full length is reported; pass limit (up to 500), a filter or a cursor for more. Anything slower than the wait (default 15 s) answers a job id; poll it with job_status.` + +type mcpTool struct { + Name string `json:"name"` + Title string `json:"title,omitempty"` + Description string `json:"description"` + InputSchema map[string]any `json:"inputSchema"` + Annotations map[string]any `json:"annotations,omitempty"` +} + +func obj(props map[string]any, required ...string) map[string]any { + s := map[string]any{"type": "object", "properties": props, "additionalProperties": false} + if len(required) > 0 { + s["required"] = required + } + return s +} + +func prop(kind, desc string) map[string]any { return map[string]any{"type": kind, "description": desc} } + +func hints(read, destructive bool) map[string]any { + return map[string]any{"readOnlyHint": read, "destructiveHint": destructive, "openWorldHint": false} +} + +var ( + limitProp = prop("integer", "Cut lists to this many rows (default 50, at most 500); the full length is reported.") + waitProp = prop("number", "Seconds to wait before answering a job id instead (default 15, at most 60).") + queryProp = map[string]any{"type": "object", "description": "Query parameters, for example {\"status\":\"draft\",\"from\":\"2026-01-01\"}.", "additionalProperties": map[string]any{"type": "string"}} +) + +func mcpTools() []mcpTool { + return []mcpTool{ + {Name: "ledger_overview", Title: "Who and what", Description: "The user and role behind the token, whether it is read-only, how many FormLedger windows are open and how many window commands they offer.", InputSchema: obj(map[string]any{}), Annotations: hints(true, false)}, + {Name: "ledger_routes", Title: "Engine routes", Description: "Every engine route an agent may call, with the approval class of those that wait for the owner (post, cancel, delete, allocate, amend, confirm, lock, invite, app lock).", InputSchema: obj(map[string]any{"text": prop("string", "Only routes containing this text, for example 'sales' or 'payments'.")}), Annotations: hints(true, false)}, + {Name: "ledger_get", Title: "Read the books", Description: "GET one engine route, for example /api/sales/docs with query {\"kind\":\"invoice\",\"status\":\"posted\"}, /api/reports/trial-balance or /api/customers/{id}. Compact JSON.", InputSchema: obj(map[string]any{"path": prop("string", "An /api/ path from ledger_routes, with ids filled in."), "query": queryProp, "limit": limitProp}, "path"), Annotations: hints(true, false)}, + {Name: "ledger_call", Title: "Change the books", Description: "POST, PATCH, PUT or DELETE one engine route with a JSON body. Drafts and master data change at once; posting, cancelling, allocating, amending, confirming, deleting, period locks and invitations wait for the owner's yes in the window. Answers the result, or a job id while it waits.", InputSchema: obj(map[string]any{"method": map[string]any{"type": "string", "enum": []string{"POST", "PATCH", "PUT", "DELETE"}}, "path": prop("string", "An /api/ path from ledger_routes."), "query": queryProp, "body": map[string]any{"type": "object", "description": "The JSON body. Money is integer minor units."}, "limit": limitProp, "wait": waitProp}, "method", "path"), Annotations: hints(false, true)}, + {Name: "ledger_cli", Title: "Run a cli command", Description: "Run one 'formledger cli' command, for example [\"sales\",\"list\",\"--kind\",\"invoice\"], [\"report\",\"trial-balance\"] or [\"invoice\",\"post\",\"SINV-0001\"]. [\"help\"] or [GROUP,\"help\"] lists them. Writes go through the same approval as ledger_call.", InputSchema: obj(map[string]any{"args": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "The words after 'formledger cli'."}}, "args"), Annotations: hints(false, true)}, + {Name: "ledger_export", Title: "Export CSV to a file", Description: "Write one export (any list or report) as CSV to a file on this computer, the same bytes as File, Export CSV. Names: " + strings.Join(export.Names(), ", ") + ".", InputSchema: obj(map[string]any{"name": prop("string", "The export name."), "out": prop("string", "Absolute path of the CSV file to write."), "query": queryProp}, "name", "out"), Annotations: hints(false, false)}, + {Name: "ledger_print", Title: "Print a document to PDF", Description: "Write a quote, order, invoice, purchase document or statement as a PDF file on this computer, the same as the Print button.", InputSchema: obj(map[string]any{"kind": prop("string", "Document kind, for example invoice, quote, order, purchase-order, purchase-invoice, goods-receipt, or statement."), "number": prop("string", "The document number (or the customer for a statement)."), "out": prop("string", "Absolute path of the PDF file to write.")}, "kind", "number", "out"), Annotations: hints(false, false)}, + {Name: "app_commands", Title: "Window commands", Description: "List the FormLedger window's commands: every menu item, button, page action and Preference, with argument names and approval class. Needs the window open.", InputSchema: obj(map[string]any{"text": prop("string", "Words that must all appear in the id, label or group."), "group": prop("string", "Only this group, for example Navigation, Sales, Payments, Preferences.")}), Annotations: hints(true, false)}, + {Name: "app_command", Title: "Describe a window command", Description: "One window command with its typed arguments (type, required, enum, min, max).", InputSchema: obj(map[string]any{"id": prop("string", "The command id from app_commands.")}, "id"), Annotations: hints(true, false)}, + {Name: "app_run", Title: "Run a window command", Description: "Run one command in the open FormLedger window, as if the person clicked it, and answer its compact result. Approval-class commands wait for the owner's yes.", InputSchema: obj(map[string]any{"id": prop("string", "The command id."), "params": map[string]any{"type": "object", "description": "The command's arguments."}, "wait": waitProp}, "id"), Annotations: hints(false, true)}, + {Name: "job_status", Title: "Poll a job", Description: "The state of a job id answered by ledger_call, ledger_get or app_run: running, waiting_consent, done (with result), failed or denied.", InputSchema: obj(map[string]any{"job": prop("string", "The job id."), "wait": waitProp}, "job"), Annotations: hints(true, false)}, + } +} + +type rpcIn struct { + JSONRPC string `json:"jsonrpc"` + ID json.RawMessage `json:"id,omitempty"` + Method string `json:"method"` + Params json.RawMessage `json:"params,omitempty"` +} + +type mcpServer struct { + tokenFile string + agent string + mu sync.Mutex + out io.Writer + client *Client +} + +func mcpVerb() verb { + return verb{"mcp", "", "serve MCP on standard input and output; add it to Claude Code with: claude mcp add formledger -e FORMLEDGER_TOKEN=... -- /path/to/formledger cli mcp", func(e *env, args []string) error { + if _, err := e.parse(e.flags("mcp"), args, 0, 0); err != nil { + return err + } + agent := strings.TrimSpace(os.Getenv(AgentEnv)) + if agent == "" { + agent = "MCP agent" + } + s := &mcpServer{tokenFile: e.tokenFile, agent: agent, out: e.out} + return s.serve(os.Stdin) + }} +} + +func (s *mcpServer) serve(in io.Reader) error { + sc := bufio.NewScanner(in) + sc.Buffer(make([]byte, 0, 1<<16), 16<<20) + var wg sync.WaitGroup + for sc.Scan() { + line := bytes.TrimSpace(sc.Bytes()) + if len(line) == 0 { + continue + } + var msg rpcIn + if err := json.Unmarshal(line, &msg); err != nil { + s.send(map[string]any{"jsonrpc": "2.0", "id": nil, "error": map[string]any{"code": -32700, "message": "parse error"}}) + continue + } + if len(msg.ID) == 0 { + continue + } + wg.Add(1) + go func(m rpcIn) { + defer wg.Done() + s.handle(m) + }(msg) + } + wg.Wait() + return sc.Err() +} + +func (s *mcpServer) send(v any) { + b, _ := json.Marshal(v) + s.mu.Lock() + defer s.mu.Unlock() + _, _ = s.out.Write(append(b, '\n')) +} + +func (s *mcpServer) handle(m rpcIn) { + reply := func(result any) { s.send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "result": result}) } + switch m.Method { + case "initialize": + var p struct { + ProtocolVersion string `json:"protocolVersion"` + } + _ = json.Unmarshal(m.Params, &p) + version := mcpProtocol + if p.ProtocolVersion != "" { + version = p.ProtocolVersion + } + reply(map[string]any{"protocolVersion": version, "capabilities": map[string]any{"tools": map[string]any{"listChanged": false}}, + "serverInfo": map[string]any{"name": "formledger", "title": "FormLedger", "version": app.Version}, "instructions": mcpInstructions}) + case "ping": + reply(map[string]any{}) + case "tools/list": + reply(map[string]any{"tools": mcpTools()}) + case "resources/list": + reply(map[string]any{"resources": []any{}}) + case "prompts/list": + reply(map[string]any{"prompts": []any{}}) + case "tools/call": + var p struct { + Name string `json:"name"` + Arguments map[string]any `json:"arguments"` + } + if err := json.Unmarshal(m.Params, &p); err != nil { + s.send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "error": map[string]any{"code": -32602, "message": "bad params"}}) + return + } + text, err := s.tool(p.Name, p.Arguments) + if err != nil { + reply(map[string]any{"content": []any{map[string]any{"type": "text", "text": err.Error()}}, "isError": true}) + return + } + reply(map[string]any{"content": []any{map[string]any{"type": "text", "text": capText(text)}}}) + default: + s.send(map[string]any{"jsonrpc": "2.0", "id": m.ID, "error": map[string]any{"code": -32601, "message": "method not found: " + m.Method}}) + } +} + +func capText(s string) string { + if len(s) <= mcpTextCap { + return s + } + return s[:mcpTextCap] + fmt.Sprintf("\n[cut at %d of %d characters; narrow the request or lower the limit]", mcpTextCap, len(s)) +} + +func (s *mcpServer) api() (*Client, error) { + s.mu.Lock() + defer s.mu.Unlock() + if s.client != nil { + return s.client, nil + } + c, err := NewClient(s.tokenFile) + if err != nil { + return nil, err + } + c.Agent = s.agent + s.client = c + return c, nil +} + +func sArg(a map[string]any, k string) string { + v, _ := a[k].(string) + return strings.TrimSpace(v) +} + +func queryArg(a map[string]any) url.Values { + q := url.Values{} + if m, ok := a["query"].(map[string]any); ok { + for k, v := range m { + q.Set(k, fmt.Sprint(v)) + } + } + return q +} + +func waitQuery(a map[string]any) url.Values { + q := url.Values{} + if w, ok := a["wait"].(float64); ok && w > 0 { + q.Set("wait", fmt.Sprint(w)) + } + return q +} + +func (s *mcpServer) tool(name string, a map[string]any) (string, error) { + if a == nil { + a = map[string]any{} + } + c, err := s.api() + if err != nil { + return "", err + } + raw := func(r json.RawMessage, err error) (string, error) { + if err != nil { + return "", err + } + return string(r), nil + } + switch name { + case "ledger_overview": + return raw(c.direct(http.MethodGet, "/api/agent", nil, nil)) + case "ledger_routes": + q := url.Values{} + if t := sArg(a, "text"); t != "" { + q.Set("text", t) + } + return raw(c.direct(http.MethodGet, "/api/agent/routes", q, nil)) + case "ledger_get", "ledger_call": + method := http.MethodGet + if name == "ledger_call" { + method = strings.ToUpper(sArg(a, "method")) + if method == "" || method == http.MethodGet { + return "", plain("ledger_call changes the books; use ledger_get to read") + } + } + query := map[string]string{} + for k, v := range queryArg(a) { + query[k] = v[0] + } + body := map[string]any{"method": method, "path": sArg(a, "path"), "query": query, "limit": a["limit"], "wait": a["wait"]} + if b, ok := a["body"]; ok { + body["body"] = b + } + return raw(c.direct(http.MethodPost, "/api/agent/call", nil, body)) + case "ledger_cli": + var args []string + if xs, ok := a["args"].([]any); ok { + for _, x := range xs { + args = append(args, fmt.Sprint(x)) + } + } + if len(args) > 0 && args[0] == "mcp" { + return "", plain("the mcp command is this server") + } + var out, errw bytes.Buffer + e := &env{out: &out, errw: &errw, client: c} + code := e.run(args) + text := strings.TrimSpace(out.String()) + if code != 0 { + return "", plain("%s", strings.TrimSpace(errw.String()+"\n"+text)) + } + return text, nil + case "ledger_export": + args := []string{sArg(a, "name"), "--out", sArg(a, "out")} + for k, v := range queryArg(a) { + args = append(args, "--"+k, v[0]) + } + if s.tokenFile != "" { + args = append(args, "--token-file", s.tokenFile) + } + if err := export.Command(args, io.Discard); err != nil { + return "", err + } + return fmt.Sprintf(`{"ok":true,"wrote":%q}`, sArg(a, "out")), nil + case "ledger_print": + args := []string{sArg(a, "kind"), sArg(a, "number"), "--out", sArg(a, "out")} + if s.tokenFile != "" { + args = append(args, "--token-file", s.tokenFile) + } + if err := printout.Command(args, io.Discard); err != nil { + return "", err + } + return fmt.Sprintf(`{"ok":true,"wrote":%q}`, sArg(a, "out")), nil + case "app_commands": + q := url.Values{} + for _, k := range []string{"text", "group"} { + if v := sArg(a, k); v != "" { + q.Set(k, v) + } + } + return raw(c.direct(http.MethodGet, "/api/agent/commands", q, nil)) + case "app_command": + return raw(c.direct(http.MethodGet, "/api/agent/commands/"+url.PathEscape(sArg(a, "id")), nil, nil)) + case "app_run": + params, _ := a["params"].(map[string]any) + return raw(c.direct(http.MethodPost, "/api/agent/commands/"+url.PathEscape(sArg(a, "id")), nil, map[string]any{"params": params, "wait": a["wait"]})) + case "job_status": + return raw(c.direct(http.MethodGet, "/api/agent/jobs/"+url.PathEscape(sArg(a, "job")), waitQuery(a), nil)) + } + return "", plain("no tool named %s", name) +} + +func (c *Client) viaAgent(method, path string, q url.Values, body any) (json.RawMessage, error) { + query := map[string]string{} + for k, v := range q { + if len(v) > 0 { + query[k] = v[0] + } + } + in := map[string]any{"method": method, "path": path, "query": query, "limit": 500, "wait": 60} + if body != nil { + in["body"] = body + } + raw, err := c.direct(http.MethodPost, "/api/agent/call", nil, in) + if err != nil { + return nil, err + } + var j struct { + Job string `json:"job"` + State string `json:"state"` + Error string `json:"error"` + Result struct { + Status int `json:"status"` + Data json.RawMessage `json:"data"` + } `json:"result"` + } + if err := json.Unmarshal(raw, &j); err != nil { + return nil, plain("the server's answer to %s %s was not understood", method, path) + } + switch j.State { + case "done": + if len(j.Result.Data) == 0 { + return json.RawMessage("{}"), nil + } + return j.Result.Data, nil + case "failed": + if j.Result.Status >= 400 { + return nil, apiFailure(j.Result.Status, method, path, j.Result.Data) + } + return nil, plain("%s", j.Error) + case "denied": + return nil, plain("%s", j.Error) + } + return nil, plain("%s %s is waiting for the owner's approval in the FormLedger window; poll job %s with job_status", method, path, j.Job) +} From 8ecb5fe31129ba2cb4a26c540b9318625d0b66ad Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:32 -0500 Subject: [PATCH 05/16] feat(window): open pages refresh live when the books change elsewhere, and view.open, view.current and view.refresh commands (0.15.2) Every API call from the window carries its window id, so the engine's change stream can tell the window's own writes from those of an agent, the command line or another window. On a change from elsewhere the open page refreshes in place: lists, reports and statements reload, master lists reload, and an open document or payment reloads unless the person has unsaved edits, in which case a note says it changed. Pages that are not open are marked and refresh when shown. view.open opens any page with typed parameters (id, kind, status, template, dates), view.current reports what is on screen and view.refresh reloads it. --- web/src/engine/session.ts | 4 ++- web/src/ui/views.ts | 69 ++++++++++++++++++++++++++++++++++++ web/src/ui/views/docform.ts | 31 ++++++++++++++-- web/src/ui/views/masters.ts | 11 ++++-- web/src/ui/views/payments.ts | 23 ++++++++++-- 5 files changed, 129 insertions(+), 9 deletions(-) diff --git a/web/src/engine/session.ts b/web/src/engine/session.ts index 2e77c9c..3439f87 100644 --- a/web/src/engine/session.ts +++ b/web/src/engine/session.ts @@ -63,6 +63,8 @@ export class ApiError extends Error { } } +export const WINDOW_ID = `w${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`; + export class Api { constructor(private readonly fetchFn: FetchFn) {} @@ -73,7 +75,7 @@ export class Api { method, cache: "no-store", credentials: "same-origin", - headers: body === undefined ? {} : { "content-type": "application/json" }, + headers: body === undefined ? { "x-formledger-window": WINDOW_ID } : { "content-type": "application/json", "x-formledger-window": WINDOW_ID }, body: body === undefined ? null : JSON.stringify(body), }); } catch { diff --git a/web/src/ui/views.ts b/web/src/ui/views.ts index f755e4e..3f348d2 100644 --- a/web/src/ui/views.ts +++ b/web/src/ui/views.ts @@ -34,6 +34,7 @@ export interface ViewDef { icon?: IconName; mount(host: HTMLElement, ctx: ViewContext, actions: HTMLElement): void; show?(params: URLSearchParams): void; + refresh?(): void; hide?(): void; } @@ -185,7 +186,75 @@ export function mountViews(engine: Engine): void { }, }); } + const stale = new Set(); + const refreshActive = () => { + if (!active) return; + stale.delete(active); + if (active.def.refresh) active.def.refresh(); + else active.def.show?.(parse(location.hash).params); + }; + document.addEventListener("formledger:live", () => { + for (const v of views.values()) if (v.ready && v !== active && v.def.refresh) stale.add(v); + refreshActive(); + }); + const ids = [...views.keys()].sort(); + const current = () => { + const { id, params } = parse(location.hash); + const route = engine.state.get("route"); + return { view: active ? active.def.id : route, title: active?.def.title ?? (route === "home" ? "Home" : route === "account" ? "Account" : ""), params: Object.fromEntries(params), hash: id ? location.hash : "" }; + }; + engine.commands.register({ + id: "view.open", + label: () => "Open a page", + group: () => "Navigation", + description: "Open any page of the window. id opens one document, payment, receipt or delivery note; kind picks the kind of a new document (quote, order, invoice); status filters a list; from, to and asOf set a report's dates; template starts a document from a template.", + mutates: false, + enabled: () => engine.state.get("screen") === "app", + params: { + view: { type: "string", required: true, enum: ["home", "account", ...ids] }, + id: { type: "string" }, + kind: { type: "string" }, + status: { type: "string" }, + template: { type: "string" }, + from: { type: "string", description: "YYYY-MM-DD" }, + to: { type: "string", description: "YYYY-MM-DD" }, + asOf: { type: "string", description: "YYYY-MM-DD" }, + }, + run: (p) => { + const view = String(p?.view ?? ""); + if (view === "home" || view === "account") { + engine.commands.run(view === "home" ? "nav.home" : "nav.account"); + return current(); + } + const params: Record = {}; + for (const k of ["id", "kind", "status", "template", "from", "to", "asOf"]) if (typeof p?.[k] === "string" && p[k]) params[k] = p[k] as string; + location.hash = hashFor(view, params); + return { view, title: views.get(view)?.def.title ?? "", params, hash: location.hash }; + }, + }); + engine.commands.register({ + id: "view.current", + label: () => "What is on screen", + group: () => "Navigation", + description: "The open page, its title and its address parameters.", + mutates: false, + run: () => current(), + }); + engine.commands.register({ + id: "view.refresh", + label: () => "Refresh this page", + group: () => "View", + mutates: false, + enabled: () => engine.state.get("screen") === "app", + run: () => { + refreshActive(); + return current(); + }, + }); engine.state.watch("screen", () => apply()); window.addEventListener("hashchange", apply); + window.addEventListener("hashchange", () => { + if (active && stale.has(active)) refreshActive(); + }); apply(); } diff --git a/web/src/ui/views/docform.ts b/web/src/ui/views/docform.ts index 867e73b..dd8c82b 100644 --- a/web/src/ui/views/docform.ts +++ b/web/src/ui/views/docform.ts @@ -79,7 +79,9 @@ function emptyTotals(): GridTotals { return { lines: [], subtotal: 0, tax: 0, total: 0 }; } -function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headActions: HTMLElement): (params: URLSearchParams) => void { +type FormShow = ((params: URLSearchParams) => void) & { refresh(): void }; + +function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headActions: HTMLElement): FormShow { const firstKind = spec.kinds[0]?.id ?? "order"; let doc: Doc | null = null; let newKind = firstKind; @@ -439,7 +441,26 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headAc reset(newKind); - return (params) => { + const linesOf = (d: Doc): GridLine[] => d.lines.map((l) => ({ itemId: l.itemId, description: l.description, qtyMilli: l.quantityMilli, unitPrice: l.unitPrice, taxRateId: l.taxRateId })); + const untouched = (d: Doc) => + dateInput.value === d.date && dueInput.value === d.dueDate && refInput.value === d.reference && memoInput.value === d.memo && (party.get()?.id ?? "") === d.partyId && sameLines(grid.getLines(), linesOf(d)); + const reload = () => { + const was = doc; + if (!was || running) return; + const seq = ++loadSeq; + void loadDoc(ctx.api, spec, was.id) + .then(async (d) => { + if (seq !== loadSeq || doc !== was) return; + if (was.status === "draft" && !untouched(was)) { + toast({ id: "doc-changed", tone: "info", message: "This document was changed elsewhere. Save your edits, or open it again to see the change." }); + return; + } + await fill(d); + }) + .catch(() => undefined); + }; + + const show = (params: URLSearchParams) => { const id = params.get("id"); const tpl = params.get("template"); if (!id && tpl) { @@ -458,11 +479,12 @@ function mountForm(spec: FamilySpec, host: HTMLElement, ctx: ViewContext, headAc if (seq === loadSeq) await fill(d); }); }; + return Object.assign(show, { refresh: reload }); } function formView(family: Family): ViewDef { const spec = SPECS[family]; - let show: ((params: URLSearchParams) => void) | null = null; + let show: FormShow | null = null; return { id: spec.view, title: spec.title, @@ -474,6 +496,9 @@ function formView(family: Family): ViewDef { show(params) { show?.(params); }, + refresh() { + show?.refresh(); + }, }; } diff --git a/web/src/ui/views/masters.ts b/web/src/ui/views/masters.ts index 3d3e07f..2915536 100644 --- a/web/src/ui/views/masters.ts +++ b/web/src/ui/views/masters.ts @@ -9,7 +9,7 @@ import type { ViewContext, ViewDef } from "../views"; const ICONS: Record = { customers: "user", suppliers: "user" }; -function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): void } { +function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): void; refresh(): void } { host.parentElement?.classList.add("page--fill"); const root = h("div", { class: m.id === "accounts" ? "masters masters--tree" : "masters" }); const listHost = h("div", { class: "masters__list" }); @@ -249,11 +249,15 @@ function mountMaster(m: Master, host: HTMLElement, ctx: ViewContext): { show(): void load(); if (tree) loadCash(); }, + refresh() { + void load(); + if (tree) loadCash(); + }, }; } export const views: ViewDef[] = MASTERS.map((m) => { - let mounted: { show(): void } | null = null; + let mounted: { show(): void; refresh(): void } | null = null; return { id: m.id, title: m.title, @@ -267,5 +271,8 @@ export const views: ViewDef[] = MASTERS.map((m) => { show() { mounted?.show(); }, + refresh() { + mounted?.refresh(); + }, }; }); diff --git a/web/src/ui/views/payments.ts b/web/src/ui/views/payments.ts index 9f05a11..29cf6df 100644 --- a/web/src/ui/views/payments.ts +++ b/web/src/ui/views/payments.ts @@ -30,6 +30,7 @@ import { delayedIndicator, h, setAttr, setText } from "../dom"; import { mountExport } from "../parts/exportbtn"; import { mountPicker } from "../parts/picker"; import { emptyBlock, mountTable, statusTone } from "../parts/table"; +import { toast } from "../toast"; import type { ViewContext, ViewDef } from "../views"; const STATUSES = ["", "draft", "posted", "cancelled"]; @@ -126,7 +127,9 @@ function field(label: string, control: HTMLElement): HTMLElement { return h("label", { class: "field pay__field" }, h("span", { class: "field__label", text: label }), control); } -function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: URLSearchParams) => void { +type FormShow = ((params: URLSearchParams) => void) & { refresh(): void }; + +function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): FormShow { const f: PayFamily = FAMILIES[dir]; const formId = dir === "in" ? "payment-in" : "payment-out"; const partyHost = h("div", { class: "pay__picker" }); @@ -446,11 +449,22 @@ function mountForm(dir: PayDir, host: HTMLElement, ctx: ViewContext): (params: U } }; - return (params) => void open(params.get("id")); + const untouched = (p: Payment) => date.value === p.date && amount.value === money(p.amount) && account.value === p.account && memo.value === p.memo && [...rows.values()].every((r) => r.input.value === ""); + const reload = () => { + const was = current; + if (!was) return; + if (was.status === "draft" && !untouched(was)) { + toast({ id: "payment-changed", tone: "info", message: "This payment was changed elsewhere. Save your edits, or open it again to see the change." }); + return; + } + void open(was.id); + }; + + return Object.assign((params: URLSearchParams) => void open(params.get("id")), { refresh: reload }); } function formView(dir: PayDir): ViewDef { - let show: ((p: URLSearchParams) => void) | null = null; + let show: FormShow | null = null; return { id: dir === "in" ? "payment-in" : "payment-out", title: dir === "in" ? "Payment received" : "Payment made", @@ -462,6 +476,9 @@ function formView(dir: PayDir): ViewDef { show(params) { show?.(params); }, + refresh() { + show?.refresh(); + }, }; } From 659f82bf8b4ec366f99cf91e150abb50062b9960 Mon Sep 17 00:00:00 2001 From: nodemode-ai Date: Wed, 2 Dec 2026 21:53:33 -0500 Subject: [PATCH 06/16] feat(window): every page action, menu item and preference is a typed command that agents can run, with the owner's approval in the dock (0.15.2) engine/agent.ts registers the page actions the buttons perform as commands with typed parameters: documents (list, read, save a draft, confirm or post, cancel, amend, make the next document, delete), payments (list, read, open invoices, save, post, allocate, cancel), goods receipts and delivery notes (read, post, cancel), master lists and the cash rule, every report and dashboard series, and templates. ui/agent-bridge.ts adds the menus' window and edit commands to the registry, prefs.get and prefs.set, opens the live stream after sign-in, sends the catalogue to the engine whenever it changes, runs commands the engine relays and answers their results, and feeds approval requests to the dock's Consent dialog, which the dock adapter now wires. Results are compact: long lists are cut to a limit and counted. --- web/src/dock-adapter.ts | 2 + web/src/engine/agent.ts | 162 +++++++++++++++++++++++++++++++++++++ web/src/ui/agent-bridge.ts | 161 ++++++++++++++++++++++++++++++++++++ web/src/ui/app.ts | 2 + web/src/ui/menus.ts | 12 +++ 5 files changed, 339 insertions(+) create mode 100644 web/src/engine/agent.ts create mode 100644 web/src/ui/agent-bridge.ts diff --git a/web/src/dock-adapter.ts b/web/src/dock-adapter.ts index 056a0c6..75ff4ec 100644 --- a/web/src/dock-adapter.ts +++ b/web/src/dock-adapter.ts @@ -1,5 +1,6 @@ import type { DockAdapter, DockAgentStatus, DockChannel, DockErrorKind, DockProgram, DockState, DockTerminal, PtyKind } from './dock/adapter'; import { Dock } from './dock/dock'; +import { consentFeed } from './ui/agent-bridge'; import './styles/dock-tokens.css'; import './dock/dock.css'; import './styles/terminal.css'; @@ -112,6 +113,7 @@ export function formledgerDock(): DockAdapter { t: (_key, english) => english, onTheme: (handler) => { document.addEventListener('formledger:theme', handler); }, errors: { message: (err) => (err instanceof DockError ? err.message : null), kind: errorKind }, + consent: consentFeed, terminal: { list: async () => (await call<{ terminals: EngineTerminal[] }>('/api/terminal')).terminals.map(record), open: async (kind, o) => { diff --git a/web/src/engine/agent.ts b/web/src/engine/agent.ts new file mode 100644 index 0000000..700f422 --- /dev/null +++ b/web/src/engine/agent.ts @@ -0,0 +1,162 @@ +import type { Commands, CommandParam } from "./commands"; +import { periodRange, series, top, type Metric, type TopWhat } from "./dashboards"; +import { amendDoc, cancelDoc, confirmDoc, loadDoc, makeNext, saveDraft, SPECS, type Draft, type Family } from "./docform"; +import { today } from "./format"; +import { loadAgeing, loadLedger, loadStock, loadTrial } from "./ledger-screens"; +import { create, listAll, loadCashPreference, MASTERS, saveCashPreference, update, type CashPreference } from "./masters"; +import { allocatePayment, cancelPayment, createPayment, FAMILIES, getPayment, getStockDoc, listPayments, openInvoices, postPayment, stockAction, updatePayment, type AllocationInput, type PayDir, type PaymentDraft, type StockKind } from "./payments"; +import type { Api } from "./session"; +import { balanceSheet, profitAndLoss } from "./statements"; +import { createTemplate, deleteTemplate, duplicateOf, listTemplates, updateTemplate, useTemplate, type Template } from "./templates"; + +type P = Record | undefined; + +const LIMIT = 50; +const enc = encodeURIComponent; +const s = (p: P, k: string, d = ""): string => (typeof p?.[k] === "string" && (p[k] as string).trim() ? (p[k] as string).trim() : d); +const n = (p: P, k: string, d: number): number => (typeof p?.[k] === "number" ? (p[k] as number) : d); +const o = (p: P, k: string): Record => (p?.[k] && typeof p[k] === "object" && !Array.isArray(p[k]) ? (p[k] as Record) : {}); + +function cut(rows: T[], limit: number): { rows: T[]; total: number; truncated?: true } { + return rows.length > limit ? { rows: rows.slice(0, limit), total: rows.length, truncated: true } : { rows, total: rows.length }; +} + +const family: CommandParam = { type: "string", required: true, enum: ["sales", "purchase"], description: "sales (quotes, sales orders, sales invoices) or purchase (purchase orders, purchase invoices)" }; +const id: CommandParam = { type: "string", required: true }; +const dir: CommandParam = { type: "string", required: true, enum: ["in", "out"], description: "in: payments received from customers; out: payments made to suppliers" }; +const limit: CommandParam = { type: "integer", min: 1, max: 500, description: `Rows to answer (default ${LIMIT}); the full count is reported.` }; +const day: CommandParam = { type: "string", description: "YYYY-MM-DD" }; + +function draftOf(raw: Record): Draft { + const t = (k: string) => (typeof raw[k] === "string" ? (raw[k] as string) : ""); + const lines = Array.isArray(raw.lines) ? (raw.lines as Record[]) : []; + return { + kind: t("kind"), + date: t("date") || today(), + dueDate: t("dueDate"), + partyId: t("partyId"), + warehouseId: t("warehouseId"), + reference: t("reference"), + memo: t("memo"), + lines: lines.map((l) => ({ + itemId: typeof l.itemId === "string" ? l.itemId : "", + description: typeof l.description === "string" ? l.description : "", + qtyMilli: typeof l.qtyMilli === "number" ? l.qtyMilli : 1000, + unitPrice: typeof l.unitPrice === "number" ? l.unitPrice : 0, + taxRateId: typeof l.taxRateId === "string" ? l.taxRateId : "", + ...(typeof l.account === "string" ? { account: l.account } : {}), + })), + }; +} + +function allocations(p: P): AllocationInput[] { + const raw = Array.isArray(p?.allocations) ? (p.allocations as Record[]) : []; + return raw.map((a) => ({ invoice: String(a.invoice ?? ""), amount: typeof a.amount === "number" ? a.amount : 0 })); +} + +export function registerAgentCommands(commands: Commands, api: Api, inApp: () => boolean): void { + const add = (c: Parameters[0]) => commands.register({ enabled: inApp, ...c }); + const spec = (p: P) => SPECS[s(p, "family") as Family]; + const pay = (p: P) => FAMILIES[s(p, "dir") as PayDir]; + + add({ id: "doc.list", label: () => "List sales or purchase documents", group: () => "Documents", mutates: false, params: { family, kind: { type: "string", description: "quote, order or invoice" }, status: { type: "string", enum: ["draft", "posted", "cancelled"] }, limit }, + run: async (p) => { + const q = new URLSearchParams({ limit: String(n(p, "limit", LIMIT)) }); + if (s(p, "kind")) q.set("kind", s(p, "kind")); + if (s(p, "status")) q.set("status", s(p, "status")); + return api.call("GET", `${spec(p).base}/docs?${q}`); + } }); + add({ id: "doc.get", label: () => "Read a document", group: () => "Documents", mutates: false, params: { family, id }, run: (p) => loadDoc(api, spec(p), s(p, "id")) }); + add({ id: "doc.save", label: () => "Save a document draft", group: () => "Documents", description: "Create a draft (no id) or change one. draft: { kind, date, dueDate, partyId, warehouseId, reference, memo, lines: [{ itemId, description, qtyMilli, unitPrice, taxRateId, account }] }; money in minor units, quantity in thousandths.", + params: { family, id: { type: "string" }, draft: { type: "object", required: true } }, + run: (p) => saveDraft(api, spec(p), s(p, "id") || null, draftOf(o(p, "draft"))) }); + add({ id: "doc.confirm", label: () => "Confirm or post a document", group: () => "Documents", risky: true, description: "Confirms a quote or order; posts an invoice to the ledger.", params: { family, id }, + run: async (p) => confirmDoc(api, spec(p), await loadDoc(api, spec(p), s(p, "id"))) }); + add({ id: "doc.cancel", label: () => "Cancel a document", group: () => "Documents", risky: true, description: "A posted invoice is cancelled with a reversal.", params: { family, id }, + run: async (p) => cancelDoc(api, spec(p), await loadDoc(api, spec(p), s(p, "id"))) }); + add({ id: "doc.amend", label: () => "Amend a document", group: () => "Documents", risky: true, params: { family, id }, + run: async (p) => ({ id: await amendDoc(api, spec(p), await loadDoc(api, spec(p), s(p, "id"))) }) }); + add({ id: "doc.make", label: () => "Make the next document", group: () => "Documents", description: "make-order from a quote, make-invoice from an order, make-delivery (sales) or make-receipt (purchase) from an order, which need warehouseId.", + params: { family, id, step: { type: "string", required: true, enum: ["make-order", "make-invoice", "make-delivery", "make-receipt"] }, warehouseId: { type: "string" } }, + run: async (p) => { + const sp = spec(p); + const step = sp.makes.find((m) => m.key === s(p, "step")); + if (!step) throw new Error(`${s(p, "family")} documents have no step ${s(p, "step")}`); + return { id: await makeNext(api, sp, await loadDoc(api, sp, s(p, "id")), step, s(p, "warehouseId")), target: step.target }; + } }); + add({ id: "doc.delete", label: () => "Delete a draft document", group: () => "Documents", risky: true, params: { family, id }, + run: (p) => api.call("DELETE", `${spec(p).base}/docs/${enc(s(p, "id"))}`) }); + + add({ id: "payment.list", label: () => "List payments", group: () => "Payments", mutates: false, params: { dir, status: { type: "string", enum: ["draft", "posted", "cancelled"] }, limit }, + run: async (p) => cut(await listPayments(api, pay(p), s(p, "status")), n(p, "limit", LIMIT)) }); + add({ id: "payment.get", label: () => "Read a payment", group: () => "Payments", mutates: false, params: { dir, id }, run: (p) => getPayment(api, pay(p), s(p, "id")) }); + add({ id: "payment.openInvoices", label: () => "Open invoices of a party", group: () => "Payments", mutates: false, params: { dir, partyId: { type: "string", required: true } }, run: (p) => openInvoices(api, pay(p), s(p, "partyId")) }); + add({ id: "payment.save", label: () => "Save a payment draft", group: () => "Payments", description: "draft: { party (code), date, amount (minor units), account (bank or cash account code), memo }. No id creates one.", + params: { dir, id: { type: "string" }, draft: { type: "object", required: true } }, + run: (p) => { + const d = o(p, "draft"); + const draft: PaymentDraft = { party: String(d.party ?? ""), date: String(d.date ?? today()), amount: typeof d.amount === "number" ? d.amount : 0, account: String(d.account ?? ""), memo: String(d.memo ?? "") }; + return s(p, "id") ? updatePayment(api, pay(p), s(p, "id"), draft) : createPayment(api, pay(p), draft); + } }); + const allocs: CommandParam = { type: "array", description: "[{ invoice: invoice id, amount: minor units }]" }; + add({ id: "payment.post", label: () => "Post a payment", group: () => "Payments", risky: true, params: { dir, id, allocations: allocs }, + run: async (p) => { await postPayment(api, pay(p), s(p, "id"), allocations(p)); return getPayment(api, pay(p), s(p, "id")); } }); + add({ id: "payment.allocate", label: () => "Allocate a payment to invoices", group: () => "Payments", risky: true, params: { dir, id, allocations: { ...allocs, required: true } }, + run: async (p) => { await allocatePayment(api, pay(p), s(p, "id"), allocations(p)); return getPayment(api, pay(p), s(p, "id")); } }); + add({ id: "payment.cancel", label: () => "Cancel a payment", group: () => "Payments", risky: true, params: { dir, id }, + run: async (p) => { await cancelPayment(api, pay(p), s(p, "id")); return getPayment(api, pay(p), s(p, "id")); } }); + + const kind: CommandParam = { type: "string", required: true, enum: ["receipt", "delivery"], description: "receipt: goods receipt; delivery: delivery note" }; + add({ id: "stockdoc.get", label: () => "Read a goods receipt or delivery note", group: () => "Stock", mutates: false, params: { kind, id }, run: (p) => getStockDoc(api, s(p, "kind") as StockKind, s(p, "id")) }); + for (const act of ["post", "cancel"] as const) { + add({ id: `stockdoc.${act}`, label: () => (act === "post" ? "Post a goods receipt or delivery note" : "Cancel a goods receipt or delivery note"), group: () => "Stock", risky: true, params: { kind, id }, + run: async (p) => { await stockAction(api, s(p, "kind") as StockKind, s(p, "id"), act); return getStockDoc(api, s(p, "kind") as StockKind, s(p, "id")); } }); + } + + const master: CommandParam = { type: "string", required: true, enum: MASTERS.map((m) => m.id) }; + const masterOf = (p: P) => { + const m = MASTERS.find((x) => x.id === s(p, "master")); + if (!m) throw new Error(`no list named ${s(p, "master")}`); + return m; + }; + add({ id: "master.list", label: () => "List customers, suppliers, items, tax rates, warehouses or accounts", group: () => "Setup", mutates: false, params: { master, limit }, run: async (p) => cut(await listAll(api, masterOf(p)), n(p, "limit", LIMIT)) }); + add({ id: "master.save", label: () => "Add or change a customer, supplier, item, tax rate, warehouse or account", group: () => "Setup", description: "body is the record's JSON as the engine takes it (see docs/selling and docs/ledger); no id adds one.", + params: { master, id: { type: "string" }, body: { type: "object", required: true } }, + run: (p) => (s(p, "id") ? update(api, masterOf(p), s(p, "id"), o(p, "body")) : create(api, masterOf(p), o(p, "body"))) }); + add({ id: "cash.get", label: () => "How cash is counted", group: () => "Setup", mutates: false, run: async () => ({ preference: await loadCashPreference(api) }) }); + add({ id: "cash.set", label: () => "Set how cash is counted", group: () => "Setup", params: { preference: { type: "string", required: true, enum: ["auto", "flagged", "named"] } }, + run: async (p) => ({ preference: await saveCashPreference(api, s(p, "preference") as CashPreference) }) }); + + add({ id: "report.trialBalance", label: () => "Trial balance", group: () => "Reports", mutates: false, params: { asOf: day, limit }, + run: async (p) => { const t = await loadTrial(api, s(p, "asOf", today())); return { ...t, ...cut(t.rows, n(p, "limit", LIMIT)) }; } }); + add({ id: "report.generalLedger", label: () => "General ledger of an account", group: () => "Reports", mutates: false, params: { account: { type: "string", required: true, description: "account code" }, from: day, to: day, limit }, + run: async (p) => { const l = await loadLedger(api, s(p, "account"), s(p, "from"), s(p, "to", today())); return { ...l, ...cut(l.lines, n(p, "limit", LIMIT)), lines: undefined }; } }); + add({ id: "report.ageing", label: () => "Receivables or payables ageing", group: () => "Reports", mutates: false, params: { side: { type: "string", required: true, enum: ["receivables", "payables"] }, asOf: day, by: { type: "string", enum: ["due", "date"] }, limit }, + run: async (p) => { const a = await loadAgeing(api, s(p, "side") as "receivables" | "payables", s(p, "asOf", today()), s(p, "by", "due")); return { totals: a.totals, ...cut(a.rows, n(p, "limit", LIMIT)) }; } }); + add({ id: "report.stock", label: () => "Stock balance and valuation", group: () => "Reports", mutates: false, params: { asOf: day, limit }, + run: async (p) => { const st = await loadStock(api, s(p, "asOf", today())); return { ...st, ...cut(st.rows, n(p, "limit", LIMIT)) }; } }); + add({ id: "report.profitAndLoss", label: () => "Profit and loss", group: () => "Reports", mutates: false, params: { from: { ...day, required: true }, to: day }, run: (p) => profitAndLoss(api, s(p, "from"), s(p, "to", today())) }); + add({ id: "report.balanceSheet", label: () => "Balance sheet", group: () => "Reports", mutates: false, params: { asOf: day }, run: (p) => balanceSheet(api, s(p, "asOf", today())) }); + const period: CommandParam = { type: "string", enum: ["month", "quarter", "year", "last12"], description: "A dashboard period, used when from and to are not given." }; + const range = (p: P) => (s(p, "from") ? { from: s(p, "from"), to: s(p, "to", today()) } : periodRange((s(p, "period", "year")) as "year", today())); + add({ id: "dashboard.series", label: () => "Dashboard series", group: () => "Reports", mutates: false, params: { metric: { type: "string", required: true, enum: ["revenue", "expenses", "profit", "cash", "receivables", "payables"] }, period, from: day, to: day }, + run: (p) => { const r = range(p); return series(api, s(p, "metric") as Metric, r.from, r.to); } }); + add({ id: "dashboard.top", label: () => "Dashboard top customers, items or suppliers", group: () => "Reports", mutates: false, params: { what: { type: "string", required: true, enum: ["customers", "items", "suppliers"] }, period, from: day, to: day, limit: { type: "integer", min: 1, max: 50 } }, + run: (p) => { const r = range(p); return top(api, s(p, "what") as TopWhat, r.from, r.to, n(p, "limit", 5)); } }); + + const find = async (tid: string): Promise