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 => {
+ const t = (await listTemplates(api)).find((x) => x.id === tid);
+ if (!t) throw new Error(`no template has the id ${tid}`);
+ return t;
+ };
+ add({ id: "template.list", label: () => "List templates", group: () => "Templates", mutates: false, params: { limit }, run: async (p) => cut(await listTemplates(api), n(p, "limit", LIMIT)) });
+ add({ id: "template.use", label: () => "Read a template as a draft", group: () => "Templates", mutates: false, description: "Answers the draft a template fills in; open it in the window with view.open { view: sales-doc or purchase-doc, template: id }.", params: { id }, run: (p) => useTemplate(api, s(p, "id")) });
+ add({ id: "template.save", label: () => "Add or change a template", group: () => "Templates", description: "template: { name, kind (quote, sales-order, sales-invoice, purchase-order, purchase-invoice), category, customer or supplier, memo, terms, lines }; no id adds one.",
+ params: { id: { type: "string" }, template: { type: "object", required: true } },
+ run: async (p) => {
+ const t = o(p, "template") as unknown as Omit;
+ return s(p, "id") ? updateTemplate(api, { ...(await find(s(p, "id"))), ...t, id: s(p, "id") }) : createTemplate(api, t);
+ } });
+ add({ id: "template.duplicate", label: () => "Duplicate a template", group: () => "Templates", params: { id }, run: async (p) => createTemplate(api, duplicateOf(await find(s(p, "id")))) });
+ add({ id: "template.delete", label: () => "Delete a template", group: () => "Templates", risky: true, params: { id }, run: async (p) => { await deleteTemplate(api, s(p, "id")); } });
+}
diff --git a/web/src/ui/agent-bridge.ts b/web/src/ui/agent-bridge.ts
new file mode 100644
index 0000000..c51f346
--- /dev/null
+++ b/web/src/ui/agent-bridge.ts
@@ -0,0 +1,161 @@
+import type { ConsentChoice, ConsentRequest } from "../dock/adapter";
+import type { Engine } from "../engine";
+import { registerAgentCommands } from "../engine/agent";
+import { WINDOW_ID } from "../engine/session";
+import { shellEntries } from "./menus";
+import { dockShown, menusInWindow, setDockShown, setMenusInWindow, IS_MAC } from "./prefs";
+import { ACCENTS, readAccent, readTheme, setAccent, setTheme, THEME_CHOICES, type ThemePref } from "./themes";
+import { toast } from "./toast";
+
+type Add = (request: ConsentRequest) => void;
+type Withdraw = (id: string) => void;
+
+const listeners: Array<{ add: Add; withdraw: Withdraw }> = [];
+const pending = new Map();
+
+function post(path: string, body: unknown): Promise {
+ return fetch(path, { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
+}
+
+export const consentFeed = {
+ subscribe(add: Add, withdraw: Withdraw): void {
+ listeners.push({ add, withdraw });
+ for (const r of pending.values()) add(r);
+ },
+ async answer(id: string, choice: ConsentChoice): Promise {
+ pending.delete(id);
+ await post(`/api/agent/consent/${encodeURIComponent(id)}`, { choice }).catch(() => undefined);
+ },
+};
+
+function data(e: Event): T | null {
+ try {
+ return JSON.parse((e as MessageEvent).data) as T;
+ } catch {
+ return null;
+ }
+}
+
+const SHELL_GROUP: Record = { edit: "Edit", view: "View", window: "Window", app: "FormLedger", help: "Help" };
+const SHELL_RISKY = new Set(["app.quit", "window.close", "app.reload"]);
+
+function registerShell(engine: Engine, inApp: () => boolean): void {
+ for (const s of shellEntries()) {
+ if (engine.commands.get(s.id)) continue;
+ engine.commands.register({ id: s.id, label: () => s.label, group: () => SHELL_GROUP[s.id.split(".")[0] ?? ""] ?? "Window", mutates: false, risky: SHELL_RISKY.has(s.id), enabled: () => inApp() && s.enabled(), run: () => s.run() });
+ }
+ const prefs = () => ({ theme: readTheme(), accent: readAccent(), dock: dockShown(), ...(IS_MAC ? { menusInWindow: menusInWindow() } : {}), themes: THEME_CHOICES.map(([id]) => id), accents: ACCENTS.map((a) => a.id) });
+ engine.commands.register({ id: "prefs.get", label: () => "Read the preferences", group: () => "Preferences", mutates: false, run: prefs });
+ engine.commands.register({
+ id: "prefs.set",
+ label: () => "Change the preferences",
+ group: () => "Preferences",
+ description: "Theme, accent, the agent dock and, on macOS, menus in the window. The app lock is account.lock.",
+ mutates: false,
+ params: {
+ theme: { type: "string", enum: THEME_CHOICES.map(([id]) => id) },
+ accent: { type: "string", enum: ACCENTS.map((a) => a.id) },
+ dock: { type: "boolean" },
+ ...(IS_MAC ? { menusInWindow: { type: "boolean" as const } } : {}),
+ },
+ run: (p) => {
+ if (typeof p?.theme === "string") setTheme(p.theme as ThemePref);
+ if (typeof p?.accent === "string") setAccent(p.accent);
+ if (typeof p?.dock === "boolean") setDockShown(p.dock);
+ if (IS_MAC && typeof p?.menusInWindow === "boolean") setMenusInWindow(p.menusInWindow);
+ return prefs();
+ },
+ });
+}
+
+function plain(v: unknown): unknown {
+ if (v === undefined) return { ok: true };
+ try {
+ return JSON.parse(JSON.stringify(v)) as unknown;
+ } catch {
+ return String(v);
+ }
+}
+
+export function mountAgentBridge(engine: Engine): void {
+ const inApp = () => engine.state.get("screen") === "app";
+ registerAgentCommands(engine.commands, engine.api, inApp);
+ registerShell(engine, inApp);
+
+ let source: EventSource | null = null;
+ let timer = 0;
+ let sent = "";
+ const push = () => {
+ window.clearTimeout(timer);
+ timer = window.setTimeout(() => {
+ if (!source) return;
+ const commands = engine.commands.catalogue().filter((c) => engine.commands.get(c.id)?.hidden?.() !== true).map((c) => ({ ...c, enabled: engine.commands.get(c.id)?.enabled?.() !== false }));
+ const body = JSON.stringify({ commands });
+ if (body === sent) return;
+ sent = body;
+ void fetch("/api/agent/window/catalogue", { method: "POST", credentials: "same-origin", headers: { "content-type": "application/json" }, body }).catch(() => {
+ sent = "";
+ });
+ }, 250);
+ };
+ const before = engine.commands.onChange;
+ engine.commands.onChange = () => {
+ before?.();
+ push();
+ };
+ engine.state.watch("me", () => push());
+ engine.state.watch("route", () => push());
+
+ const live = (detail: unknown) => document.dispatchEvent(new CustomEvent("formledger:live", { detail }));
+
+ const run = async (job: string, id: string, params: Record) => {
+ const c = engine.commands.get(id);
+ if (c?.mutates !== false) toast({ id: "agent-run", tone: "info", message: `An agent ran ${c ? c.label() : id}.` });
+ try {
+ const out = await engine.commands.invoke(id, params);
+ await post("/api/agent/window/result", { job, ok: true, result: plain(out) });
+ if (c?.mutates !== false) live({ by: "agent", command: id });
+ } catch (e) {
+ await post("/api/agent/window/result", { job, ok: false, error: e instanceof Error ? e.message : String(e) }).catch(() => undefined);
+ }
+ push();
+ };
+
+ const open = () => {
+ if (source) return;
+ const es = new EventSource("/api/live?window=1");
+ source = es;
+ es.addEventListener("hello", () => {
+ sent = "";
+ push();
+ });
+ es.addEventListener("change", (e) => {
+ const d = data<{ window?: string; by?: string; area?: string }>(e);
+ if (!d || d.window === WINDOW_ID) return;
+ live(d);
+ if (d.by === "agent") toast({ id: "agent-live", tone: "info", message: `An agent changed ${d.area ?? "the books"}.` });
+ });
+ es.addEventListener("command", (e) => {
+ const d = data<{ job: string; id: string; params?: Record }>(e);
+ if (d) void run(d.job, d.id, d.params ?? {});
+ });
+ es.addEventListener("consent", (e) => {
+ const d = data(e);
+ if (!d || pending.has(d.id)) return;
+ pending.set(d.id, d);
+ for (const l of listeners) l.add(d);
+ });
+ es.addEventListener("consent-closed", (e) => {
+ const d = data<{ id: string }>(e);
+ if (!d) return;
+ pending.delete(d.id);
+ for (const l of listeners) l.withdraw(d.id);
+ });
+ };
+ const close = () => {
+ source?.close();
+ source = null;
+ sent = "";
+ };
+ engine.state.watch("screen", (screen) => (screen === "app" ? open() : close()), { immediate: true });
+}
diff --git a/web/src/ui/app.ts b/web/src/ui/app.ts
index 7ce85b4..be658b9 100644
--- a/web/src/ui/app.ts
+++ b/web/src/ui/app.ts
@@ -14,6 +14,7 @@ import { mountMenus } from "./menus";
import { mountDock, reserveDock } from "../dock-adapter";
import { mountPrefsDialog, type PrefsDialog } from "./prefs-dialog";
import { watchTrafficLights } from "./traffic-lights";
+import { mountAgentBridge } from "./agent-bridge";
const SERVER_TOAST = "server-health";
@@ -274,4 +275,5 @@ export function mountApp(engine: Engine): void {
mountKeyNotice(engine);
mountViews(engine);
mountShell(engine);
+ mountAgentBridge(engine);
}
diff --git a/web/src/ui/menus.ts b/web/src/ui/menus.ts
index 4446e38..809d912 100644
--- a/web/src/ui/menus.ts
+++ b/web/src/ui/menus.ts
@@ -161,6 +161,18 @@ const SHELL: Record = {
"help.notices": { run: () => void window.open(`${location.origin}/notices`), enabled: () => true },
};
+export function shellEntries(): Array<{ id: string; label: string } & Shell> {
+ const labels = new Map();
+ const walk = (items: MenuItem[]): void => {
+ for (const i of items) {
+ if (isSub(i)) walk(i.items);
+ else if (isCommand(i) && !labels.has(i.id)) labels.set(i.id, i.label.replace(/\.+$/, ""));
+ }
+ };
+ for (const d of MENUS) walk(typeof d.items === "function" ? d.items() : d.items);
+ return Object.entries(SHELL).map(([id, s]) => ({ id, label: labels.get(id) ?? id, ...s }));
+}
+
function matches(e: KeyboardEvent, combo: string): boolean {
const parts = keyParts(combo);
const key = parts[parts.length - 1] ?? "";
From d08045e827860f87834a4490ab22ffb2a3747a47 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Wed, 2 Dec 2026 21:53:35 -0500
Subject: [PATCH 07/16] fix(agent): plain refusals for agents, the reach of
Always allow, and the dock's engine address for the cli (0.15.2)
The cli no longer words an agent refusal (blocked route, denied or unanswered approval, no window, unknown command) as a role refusal. The approval dialog says that Always allow covers that kind of action from that credential until FormLedger restarts. With FORMLEDGER_URL unset the cli follows FORMLEDGER_ENGINE_URL, which the agent dock sets in its terminals, so a cli or MCP server started there reaches the desktop app even on a moved port.
---
internal/agent/module.go | 1 +
internal/cli/client.go | 5 +++++
2 files changed, 6 insertions(+)
diff --git a/internal/agent/module.go b/internal/agent/module.go
index 37b6b57..3374018 100644
--- a/internal/agent/module.go
+++ b/internal/agent/module.go
@@ -295,6 +295,7 @@ func (m *module) ask(r *http.Request, p *policy.Principal, x *job, class, what s
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")
}
+ notes = append(notes, "Always allow covers "+class+" actions from this agent's credential until FormLedger restarts.")
a := m.consent.open(p.UserID, key, name, what, notes)
m.jobs.set(x, "waiting_consent")
m.hub.toUser(p.UserID, "consent", a)
diff --git a/internal/cli/client.go b/internal/cli/client.go
index c43177e..6cf1a61 100644
--- a/internal/cli/client.go
+++ b/internal/cli/client.go
@@ -34,6 +34,9 @@ func plain(format string, a ...any) error { return &userError{fmt.Sprintf(format
func NewClient(tokenFile string) (*Client, error) {
base := strings.TrimRight(strings.TrimSpace(os.Getenv(URLEnv)), "/")
+ if base == "" {
+ base = strings.TrimRight(strings.TrimSpace(os.Getenv("FORMLEDGER_ENGINE_URL")), "/")
+ }
if base == "" {
base = DefaultURL
}
@@ -118,6 +121,8 @@ func apiFailure(status int, method, path string, raw []byte) error {
return plain("the server refused the app token; check %s or the token file, or make a new token under Account", TokenEnv)
case status == http.StatusForbidden && code == "read_only":
return plain("this app token is read-only, so it may not change anything")
+ case code == "agent_blocked" || strings.HasPrefix(code, "consent_") || code == "no_window" || code == "no_command":
+ return plain("%s", msg)
case status == http.StatusForbidden && code == "session_only":
return plain("this needs a signed-in browser session; an app token may not do it")
case status == http.StatusForbidden:
From 51f717ce9bb4b55e4dce12335f31c535b0b5ea11 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Wed, 2 Dec 2026 21:54:31 -0500
Subject: [PATCH 08/16] docs(agents): the MCP server, the window's commands,
approval, compact results and the live stream (0.15.2)
docs/ledger/agents.md lists the MCP tools, how to connect Claude Code with an app token, the window command groups, which actions wait for the owner's approval and which are never reachable, the limits and jobs, the live stream and the engine routes behind them. README, AGENTS.md, CLAUDE.md, the harness skill and its evals no longer say there is no MCP server, and say that a new window action must be a typed command and a new money-moving route must fall in an approval class. The cli guide names FORMLEDGER_ENGINE_URL and points to the agents page.
---
.claude/skills/formledger-harness/EVALS.json | 2 +-
.claude/skills/formledger-harness/SKILL.md | 5 +-
AGENTS.md | 2 +-
CLAUDE.md | 2 +-
README.md | 4 +-
docs/ledger/agents.md | 69 ++++++++++++++++++++
docs/ledger/cli.md | 4 +-
7 files changed, 81 insertions(+), 7 deletions(-)
create mode 100644 docs/ledger/agents.md
diff --git a/.claude/skills/formledger-harness/EVALS.json b/.claude/skills/formledger-harness/EVALS.json
index c7f683c..b9f8a2c 100644
--- a/.claude/skills/formledger-harness/EVALS.json
+++ b/.claude/skills/formledger-harness/EVALS.json
@@ -44,7 +44,7 @@
"files": [],
"expected_behavior": [
"Does not open source files or propose code changes",
- "Says the repository is a scaffold and has no MCP server or agent tool yet, and does not invent app features or menu paths"
+ "Points to docs/ledger/agents.md and the formledger cli mcp server for using the app, and does not invent app features or menu paths"
]
}
],
diff --git a/.claude/skills/formledger-harness/SKILL.md b/.claude/skills/formledger-harness/SKILL.md
index 7870221..86b4f25 100644
--- a/.claude/skills/formledger-harness/SKILL.md
+++ b/.claude/skills/formledger-harness/SKILL.md
@@ -14,7 +14,7 @@ FormLedger is a local-first business app that is the system of record for a smal
This pack is for agents who change the repository. It is not about using the app. `docs/BEHAVIOURS.md` is the specification: every phase's exit criterion traces to a behaviour there, and nothing outside the repo is a source of behaviour. Outside reference products are never opened or copied.
-There is no MCP server or agent-facing tool yet; they are later phases. Do not add `.mcp.json` or describe agent tools until a phase builds them. `./formledger cli` is a client of the running server over HTTP with an app token (`FORMLEDGER_URL`, `FORMLEDGER_TOKEN`); it never opens the database, because one server process is the only writer.
+Agents use the app through `./formledger cli mcp` (stdio MCP, in `internal/cli/mcp.go`), the `internal/agent` module (`/api/agent/*`: routes, call, window commands, jobs, approval; `/api/live`: the change stream) and the window's command registry, bridged by `web/src/ui/agent-bridge.ts`; `docs/ledger/agents.md` is the reference. A new window action must be a registered command with typed params (`web/src/engine/agent.ts` holds the page actions), and a new money-moving, destructive or people route must fall in an approval class in `internal/agent/call.go`. There is no `.mcp.json`, because the server needs the user's own app token. `./formledger cli` is a client of the running server over HTTP with an app token (`FORMLEDGER_URL`, `FORMLEDGER_TOKEN`); it never opens the database, because one server process is the only writer.
## Repo map
@@ -31,7 +31,8 @@ There is no MCP server or agent-facing tool yet; they are later phases. Do not a
| `internal/coa`, `internal/fiscal` | The chart of accounts with its starter chart; fiscal years, monthly periods and the period lock |
| `internal/journal`, `internal/posting` | Draft entries and the triggers that protect posted rows; post and cancel, each one transaction, with gapless numbers |
| `internal/reports` | Trial balance, general ledger, balances, period activity and the integrity check, all read-only SQL |
-| `internal/cli` | `./formledger cli`, the HTTP client |
+| `internal/cli` | `./formledger cli`, the HTTP client, and `cli mcp`, the agents' MCP server |
+| `internal/agent` | The agents' engine side: `/api/live` change stream, `/api/agent/*` routes, call, window commands, jobs and the owner's approval |
| `docs/ledger/` | One page per ledger part, with routes and refusal codes |
| `internal/customers`, `internal/items`, `internal/taxrates` | The parties and the things sold; tax is basis points, computed half-up per line |
| `internal/series`, `internal/sales` | Gapless numbers for any document prefix; the sales document tables with their protecting triggers, drafts and server-side totals |
diff --git a/AGENTS.md b/AGENTS.md
index 213ad21..cc8eef1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -10,7 +10,7 @@ FormLedger: a local-first business app that is the system of record for a small
`.claude/skills/formledger-harness/SKILL.md` holds the repo map, the commands, the ports, the rules of the build, the ledger invariants and the hand-back. Read it before changing anything. `docs/BEHAVIOURS.md` is the specification.
-There is no MCP server, CLI for agents or agent-facing tool yet.
+Agents that use FormLedger (not change it) connect with `./formledger cli mcp`, an MCP server on stdio that is a client of the running server with an app token. It reaches every engine route, every `formledger cli` command and every command of the open window, and the window shows their changes live. Posting, cancelling, allocating, amending, confirming, deleting, period locks, invitations and the app lock wait for the owner's approval in the window; sign-in, tokens and terminals are never reachable. `docs/ledger/agents.md` lists the tools. When you add a user action to the window, register it as a command with typed params in the engine's registry so agents get it too.
## Build and check
diff --git a/CLAUDE.md b/CLAUDE.md
index 54d6fa0..97c70db 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -8,7 +8,7 @@ A local-first business app that is the system of record for a small company. Go
- `embed.go` embeds `web/dist` into the binary. `src-tauri/` starts the server as the sidecar `binaries/formledger-server`.
- `docs/BEHAVIOURS.md` is the specification; every phase's exit criterion traces to it. Outside reference products are never opened or copied.
- `formledger`, `formledger_oc_install` and `build_app` at the root are the scripts the repo ships, not build output.
-- There is no MCP server, CLI for agents or agent-facing tool yet, and so no `.mcp.json`. They are later phases.
+- Agents reach the app through `./formledger cli mcp` (stdio MCP, a client of the server with an app token), the engine's `internal/agent` module (`/api/agent/*` and the `/api/live` stream) and the window's command registry. Every new user action is a registered command with typed params; money-moving, destructive and people actions stay behind the owner's approval. See `docs/ledger/agents.md`. There is no `.mcp.json`: the server needs the user's own app token.
- The planning documents (`DEV_PLAN.md`, `BUILD_NOTES.md`) live in a planning sidecar outside the repo.
## Skills
diff --git a/README.md b/README.md
index eebdad4..298e668 100644
--- a/README.md
+++ b/README.md
@@ -124,7 +124,9 @@ The command line is a client of the running server; it never opens the database.
[`docs/ledger/cli.md`](docs/ledger/cli.md) walks from an empty company to a trial balance. What the app commits to do is listed in [`docs/BEHAVIOURS.md`](docs/BEHAVIOURS.md), and [`AGENTS.md`](AGENTS.md) is the guide for coding agents working on the repo.
-From 0.15.0 the window also has an agent dock, opened from View, Agent Dock, the robot button at the top right or with Cmd or Ctrl plus J: a terminal panel beside the books with a shell tab and tabs for Claude Code, Codex, Cursor and, from 0.15.1, Antigravity when they are installed on your computer. Only the owner of the books can open it, and only from this computer. On Windows its terminals do not open yet. FormLedger has no MCP server yet; an agent drives the books through the command line above.
+From 0.15.0 the window also has an agent dock, opened from View, Agent Dock, the robot button at the top right or with Cmd or Ctrl plus J: a terminal panel beside the books with a shell tab and tabs for Claude Code, Codex, Cursor and, from 0.15.1, Antigravity when they are installed on your computer. Only the owner of the books can open it, and only from this computer. On Windows its terminals do not open yet.
+
+From 0.15.2 agents can do what you can do at the window. `./formledger cli mcp` is an MCP server for Claude Code, Codex, Cursor and others (`claude mcp add formledger -e FORMLEDGER_TOKEN=fl_... -- /path/to/formledger cli mcp`): it reads and writes the books over every engine route and the command line, and runs any of the window's commands, from opening a page to posting an invoice or changing a preference. Posting, cancelling, allocating, deleting, period locks and invitations wait for your yes in the window, sign-in and tokens stay with you, and whatever an agent changes shows in the open window at once. [`docs/ledger/agents.md`](docs/ledger/agents.md) lists the tools.
## Network
diff --git a/docs/ledger/agents.md b/docs/ledger/agents.md
new file mode 100644
index 0000000..63ebb10
--- /dev/null
+++ b/docs/ledger/agents.md
@@ -0,0 +1,69 @@
+# Agents: MCP, the window bridge and the live stream
+
+Claude Code, Codex, Cursor and other agents can do in FormLedger what a person can do at the window. They work as a client of the running server with an app token, so one server process stays the only writer and the token's role and scope decide what they may do. Money-moving, destructive and people actions wait for the owner's yes in the open window.
+
+## Connect an agent
+
+1. Under Account in the window, make an app token (read or write). See `./formledger cli token`.
+2. Add the MCP server to the agent. For Claude Code:
+
+```
+claude mcp add formledger -e FORMLEDGER_TOKEN=fl_... -- /path/to/formledger cli mcp
+```
+
+`FORMLEDGER_URL` points it at a server other than `http://127.0.0.1:8340`. Inside the agent dock's terminals the server's own address is already set (`FORMLEDGER_ENGINE_URL`), so only the token is needed. `FORMLEDGER_AGENT` names the agent in the approval dialog (default `MCP agent`).
+
+## Tools
+
+| Tool | Does |
+| --- | --- |
+| `ledger_overview` | The user and role behind the token, read-only or not, open windows, window commands |
+| `ledger_routes` | Every engine route an agent may call, with the approval class of those that wait for the owner |
+| `ledger_get` | GET one engine route, compact JSON |
+| `ledger_call` | POST, PATCH, PUT or DELETE one engine route |
+| `ledger_cli` | Any `formledger cli` command, for example `["invoice","post","SINV-0001"]`; its writes go through the same approval |
+| `ledger_export` | One CSV export to a file on this computer, the same bytes as File, Export CSV |
+| `ledger_print` | A document or statement as a PDF file on this computer, the same as Print |
+| `app_commands` | The open window's commands: menus, buttons, page actions and Preferences, with argument names and approval class |
+| `app_command` | One window command with its typed arguments |
+| `app_run` | Run one window command, as if the person clicked it |
+| `job_status` | Poll a job id answered by a slow call |
+
+## The window's commands
+
+Every action of the window is a command in one registry (`web/src/engine/commands.ts`) with typed parameters (type, required, enum, min, max). The palette, the menus, the keyboard and agents all run the same commands. Groups: Navigation (`view.open`, `view.current`, `go.*`, `nav.*`), File and New (`new.*`, `file.*`), View, Window and Edit (the menus), Preferences (`prefs.get`, `prefs.set`, `app.preferences`), Account and People (`account.lock`, `invites.*`, `session.logout`), Documents (`doc.*`), Payments (`payment.*`), Stock (`stockdoc.*`), Setup (`master.*`, `cash.*`), Reports (`report.*`, `dashboard.*`) and Templates (`template.*`).
+
+`view.open { view, id, kind, status, template, from, to, asOf }` opens any page or one document, so an agent can show the person what it did.
+
+## Approval
+
+These wait for the owner in the window's Consent dialog (Deny, Allow once, Always allow), whether they come as an engine call, a cli command or a window command:
+
+- posting, cancelling, allocating, amending, confirming, deleting;
+- locking and unlocking periods;
+- inviting people and withdrawing invitations, the app lock, signing out, closing or reloading the window.
+
+Always allow covers that kind of action from that credential until FormLedger restarts. With no window open these are refused with `consent_needs_window`. Nothing in FormLedger sends mail or anything else off this computer.
+
+Never reachable by agents: sign-in, set-up, unlock, invitation acceptance, claiming the books, app tokens and the dock's terminals. A read-only token stays read-only on every path.
+
+## Compact results and jobs
+
+Lists longer than the limit (default 50, at most 500) are cut and their full length is reported under `truncated`. Binary output is not sent; `ledger_export` and `ledger_print` write files instead. A call that takes longer than its wait (default 15 s, at most 60) answers `{ job, state }`; poll it with `job_status`. States: `running`, `waiting_consent`, `done`, `failed`, `denied`.
+
+## Live
+
+`GET /api/live` is a server-sent event stream for the signed-in window. Every successful write publishes a `change` event (method, path, area, by `window`, `token` or `agent`, and the window id that made it). The open page refreshes in place; a document or payment with unsaved edits keeps them and says it changed. The same stream carries `consent` and `command` events to the window.
+
+## Engine routes
+
+| Route | Who | Does |
+| --- | --- | --- |
+| `GET /api/agent` | token or session | Overview |
+| `GET /api/agent/routes` | token or session | Callable routes with approval classes |
+| `POST /api/agent/call` | token or session | Run one route with the caller's credential, approval and compact answer |
+| `GET /api/agent/commands`, `GET /api/agent/commands/{id}` | token or session | The window's catalogue |
+| `POST /api/agent/commands/{id}` | token or session | Run a window command |
+| `GET /api/agent/jobs/{id}` | token or session | Poll a job |
+| `GET /api/live` | window session | The live stream |
+| `POST /api/agent/window/catalogue`, `POST /api/agent/window/result`, `POST /api/agent/consent/{id}` | window session | The window's side of the bridge |
diff --git a/docs/ledger/cli.md b/docs/ledger/cli.md
index 1ec5c08..6d9e4ac 100644
--- a/docs/ledger/cli.md
+++ b/docs/ledger/cli.md
@@ -12,13 +12,15 @@ bin/formledger cli --help the compiled binary
| Setting | What it does |
|---|---|
-| `FORMLEDGER_URL` | the server address, default `http://127.0.0.1:8340` |
+| `FORMLEDGER_URL` | the server address; unset, `FORMLEDGER_ENGINE_URL` (set in the agent dock's terminals), else `http://127.0.0.1:8340` |
| `FORMLEDGER_TOKEN` | the app token, `fl_...` |
| `--token-file FILE` | read the token from a file instead (it wins over the variable) |
| `--table` | print a table instead of the server's JSON |
Every command prints JSON on stdout, or a table with `--table`. A problem prints one plain sentence on stderr: no token, a refused token, a read-only token asked to change something, a role that may not do the action, a server that does not answer, or a server that does not know the command yet. Exit codes: 0 done, 1 refused or failed, 2 wrong usage. `--help` works at every level (`formledger cli journal --help`, `formledger cli journal new --help`).
+`formledger cli mcp` serves the same commands, every engine route and the open window's commands to Claude Code and other agents over MCP; see [agents.md](agents.md).
+
## Making the first app token
A token cannot be made from the command line. `POST /api/me/tokens` needs a signed-in browser session, and an app token may not make another one; `formledger cli token` only prints these steps.
From 7f23326fbfebe5b1baa8ca534b89423194ed68da Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Wed, 2 Dec 2026 22:04:28 -0500
Subject: [PATCH 09/16] feat(dock): each agent tab gets its own write token and
Claude Code starts with the formledger MCP server (0.15.2)
Following FormCite's dock: when an agent tab starts (Claude Code, Codex, Cursor, Antigravity) the dock mints a write-scoped app token for the owner, named for the program and the dock ("Claude Code tab, FormLedger dock"), stored hashed like any other token, and puts FORMLEDGER_TOKEN, FORMLEDGER_URL and FORMLEDGER_AGENT in the tab's environment, so the cli works there with no setup. Claude Code is started with --mcp-config naming the running binary's "cli mcp" as the formledger server (the token passed by ${FORMLEDGER_TOKEN} expansion, not on the command line) and a short system note. The token is withdrawn when the tab closes, and tokens left by a run that ended without closing its tabs are withdrawn when the dock mounts; both are audited as the FormLedger dock. The owner's approval still gates the risky actions. tokens.create and tokens.revoke are window-only commands, refused to agents.
---
internal/agent/call.go | 2 +-
internal/auth/tabtokens.go | 62 ++++++++++++++++++++++++++++++++++++++
internal/dock/module.go | 40 +++++++++++++++++++++++-
3 files changed, 102 insertions(+), 2 deletions(-)
create mode 100644 internal/auth/tabtokens.go
diff --git a/internal/agent/call.go b/internal/agent/call.go
index 6d8708c..766affa 100644
--- a/internal/agent/call.go
+++ b/internal/agent/call.go
@@ -26,7 +26,7 @@ const (
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}
+ blockedCommands = map[string]bool{"session.setup": true, "session.login": true, "session.unlock": true, "invite.accept": true, "account.claim": true, "tokens.create": true, "tokens.revoke": 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"}
)
diff --git a/internal/auth/tabtokens.go b/internal/auth/tabtokens.go
new file mode 100644
index 0000000..00037e6
--- /dev/null
+++ b/internal/auth/tabtokens.go
@@ -0,0 +1,62 @@
+package auth
+
+import (
+ "context"
+ "database/sql"
+ "strings"
+
+ "github.com/nodemode-ai/formledger/internal/audit"
+ "github.com/nodemode-ai/formledger/internal/ids"
+ "github.com/nodemode-ai/formledger/internal/secrets"
+ "github.com/nodemode-ai/formledger/internal/store"
+)
+
+const TabTokenSuffix = " tab, FormLedger dock"
+
+var dockActor = audit.Anonymous("FormLedger dock")
+
+func (s *Service) MintTabToken(ctx context.Context, userID, program string) (id, plain string, err error) {
+ name := strings.TrimSpace(program) + TabTokenSuffix
+ plain = secrets.Token(TokenPrefix, 32)
+ id = ids.New()
+ prefix := plain[:len(TokenPrefix)+6]
+ err = s.st.Tx(ctx, func(tx *sql.Tx) error {
+ if _, err := tx.ExecContext(ctx, `INSERT INTO api_tokens (id, user_id, name, token_hash, prefix, scope, created_at) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ id, userID, name, secrets.Hash(plain), prefix, "write", store.NowMS()); err != nil {
+ return err
+ }
+ return s.audit.Record(ctx, tx, audit.Entry{Actor: dockActor, Action: "token.create", ObjectKind: "api_token", ObjectID: id,
+ Detail: map[string]any{"name": name, "scope": "write", "prefix": prefix, "user": userID}})
+ })
+ return id, plain, err
+}
+
+func (s *Service) RevokeTabToken(ctx context.Context, id string) { s.revokeTab(ctx, id, "tab closed") }
+
+func (s *Service) revokeTab(ctx context.Context, id, why string) {
+ _ = s.st.Tx(ctx, func(tx *sql.Tx) error {
+ var name string
+ if err := tx.QueryRowContext(ctx, "DELETE FROM api_tokens WHERE id = ? AND name LIKE ? RETURNING name", id, "%"+TabTokenSuffix).Scan(&name); err != nil {
+ return err
+ }
+ return s.audit.Record(ctx, tx, audit.Entry{Actor: dockActor, Action: "token.revoke", ObjectKind: "api_token", ObjectID: id, Detail: map[string]any{"name": name, "why": why}})
+ })
+}
+
+func (s *Service) SweepTabTokens(ctx context.Context) {
+ rows, err := s.st.R.QueryContext(ctx, "SELECT id FROM api_tokens WHERE name LIKE ?", "%"+TabTokenSuffix)
+ if err != nil {
+ return
+ }
+ var stale []string
+ for rows.Next() {
+ var id string
+ if rows.Scan(&id) == nil {
+ stale = append(stale, id)
+ }
+ }
+ rows.Close()
+ for _, id := range stale {
+ s.revokeTab(ctx, id, "left from an earlier run")
+ }
+}
diff --git a/internal/dock/module.go b/internal/dock/module.go
index ea8cd4a..60ed540 100644
--- a/internal/dock/module.go
+++ b/internal/dock/module.go
@@ -1,6 +1,7 @@
package dock
import (
+ "context"
"encoding/json"
"net/http"
"os"
@@ -10,6 +11,7 @@ import (
"github.com/nodemode-ai/formledger/internal/app"
"github.com/nodemode-ai/formledger/internal/auth"
+ "github.com/nodemode-ai/formledger/internal/config"
"github.com/nodemode-ai/formledger/internal/httpx"
"github.com/nodemode-ai/formledger/internal/policy"
)
@@ -35,6 +37,7 @@ func (m *module) Stop() { m.reg.closeAll() }
func (m *module) Mount(r *httpx.Router, d *app.Deps) error {
m.dataDir = d.Config.DataDir
+ m.auth.SweepTabTokens(context.Background())
g := func(h auth.PrincipalHandler) http.HandlerFunc { return guard(m.auth, h) }
r.HandleFunc("GET /api/terminal", g(m.list))
r.HandleFunc("POST /api/terminal", g(m.openShell))
@@ -121,15 +124,50 @@ func (m *module) openProgram(w http.ResponseWriter, r *http.Request, p *policy.P
m.status.mu.Unlock()
return errMissing(prog)
}
+ ctx := context.WithoutCancel(r.Context())
+ tokenID, token, err := m.auth.MintTabToken(ctx, p.UserID, prog.title)
+ if err != nil {
+ return err
+ }
+ url := engineURL(r)
+ if prog.kind == "claude" {
+ args = append(claudeMCP(url), args...)
+ }
argv := append([]string{st.path}, args...)
- s, err := m.reg.add(p.UserID, prog.kind, prog.title, launch{argv: argv, env: childEnv(engineURL(r), st.path), dir: m.workdir()}, cols, rows)
+ env := append(childEnv(url, st.path), config.EnvPrefix+"URL="+url, config.EnvPrefix+"TOKEN="+token, config.EnvPrefix+"AGENT="+prog.title)
+ s, err := m.reg.add(p.UserID, prog.kind, prog.title, launch{argv: argv, env: env, dir: m.workdir()}, cols, rows)
if err != nil {
+ m.auth.RevokeTabToken(ctx, tokenID)
return err
}
+ revoke := func() { m.auth.RevokeTabToken(context.Background(), tokenID) }
+ s.mu.Lock()
+ closed := s.closed
+ if !closed {
+ s.onClose = append(s.onClose, revoke)
+ }
+ s.mu.Unlock()
+ if closed {
+ revoke()
+ }
httpx.JSON(w, http.StatusOK, s.describe())
return nil
}
+const tabNote = "You are running inside FormLedger's agent dock. FormLedger's MCP server is connected as formledger: use its tools to read and change the person's books and to drive the open FormLedger window. Posting, cancelling, deleting and similar actions wait for the owner's approval in the window."
+
+func claudeMCP(url string) []string {
+ exe, err := os.Executable()
+ if err != nil {
+ return nil
+ }
+ cfg, _ := json.Marshal(map[string]any{"mcpServers": map[string]any{"formledger": map[string]any{
+ "type": "stdio", "command": exe, "args": []string{"cli", "mcp"},
+ "env": map[string]string{config.EnvPrefix + "URL": url, config.EnvPrefix + "TOKEN": "${" + config.EnvPrefix + "TOKEN}", config.EnvPrefix + "AGENT": "Claude Code"},
+ }}})
+ return []string{"--mcp-config", string(cfg), "--append-system-prompt", tabNote}
+}
+
func (m *module) openClaude(w http.ResponseWriter, r *http.Request, p *policy.Principal) error {
b := struct {
Cols int `json:"cols"`
From 0ab458466fdf9f5d9ffa5b7f9c0eb7e0fea837a2 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Wed, 2 Dec 2026 22:04:28 -0500
Subject: [PATCH 10/16] feat(account): an App tokens panel lists, makes and
revokes the owner's tokens, including the dock's tab tokens (0.15.2)
Account had no screen for app tokens, so the cli and its docs sent people to curl. The new panel lists every token of the signed-in user with its scope, prefix and last use, makes one from a name and a scope (the value is shown once, with Copy) and revokes any of them, the dock's tab tokens included. tokens.create and tokens.revoke are registered commands with typed params; the list loads on sign-in and whenever Account opens, and is cleared on sign-out. Rows are kept by id and patched in place.
---
web/index.html | 15 +++++++++++
web/src/engine/index.ts | 56 ++++++++++++++++++++++++++++++++++++++++-
web/src/ui/account.ts | 52 +++++++++++++++++++++++++++++++++++++-
3 files changed, 121 insertions(+), 2 deletions(-)
diff --git a/web/index.html b/web/index.html
index df335c3..f5f0f3c 100644
--- a/web/index.html
+++ b/web/index.html
@@ -191,6 +191,21 @@
People
No open invitations
+
+
App tokens
+
An app token lets the command line, an MCP server or a script use these books as you. The agent dock makes one for each agent tab and withdraws it when the tab closes.
+
+
+
+
+
+
No app tokens
+
diff --git a/web/src/engine/index.ts b/web/src/engine/index.ts
index 429fa20..aa16f4b 100644
--- a/web/src/engine/index.ts
+++ b/web/src/engine/index.ts
@@ -17,6 +17,18 @@ export interface AppState {
inviteError: string;
invites: Invite[];
created: Created | null;
+ tokens: AppToken[];
+ newToken: AppToken | null;
+}
+
+export interface AppToken {
+ id: string;
+ name: string;
+ prefix: string;
+ scope: "read" | "write";
+ createdAt: number;
+ lastUsedAt: number;
+ token?: string;
}
export interface EngineOptions {
@@ -45,6 +57,8 @@ export function createEngine(options: EngineOptions): Engine {
inviteError: "",
invites: [],
created: null,
+ tokens: [],
+ newToken: null,
});
const commands = new Commands();
const api = new Api(options.fetch);
@@ -57,10 +71,17 @@ export function createEngine(options: EngineOptions): Engine {
if (out) state.set("invites", out.invites ?? []);
};
+ const loadTokens = async () => {
+ if (!state.get("me")) return state.set("tokens", []);
+ const out = await api.call<{ tokens: AppToken[] }>("GET", "/api/me/tokens").catch(() => null);
+ if (out) state.set("tokens", out.tokens ?? []);
+ };
+
const enter = (me: Me) => {
state.set("me", me);
state.set("screen", "app");
void loadInvites();
+ void loadTokens();
};
const resolve = async () => {
@@ -137,6 +158,8 @@ export function createEngine(options: EngineOptions): Engine {
state.set("me", null);
state.set("invites", []);
state.set("created", null);
+ state.set("tokens", []);
+ state.set("newToken", null);
state.set("route", "home");
state.set("screen", "signin");
},
@@ -189,13 +212,44 @@ export function createEngine(options: EngineOptions): Engine {
},
});
+ commands.register({
+ id: "tokens.create",
+ label: () => "Make an app token",
+ group: () => "Account",
+ enabled: () => state.get("screen") === "app",
+ params: { name: { type: "string", required: true }, scope: { type: "string", required: true, enum: ["read", "write"] } },
+ run: async (p) => {
+ const out = await api.call("POST", "/api/me/tokens", { name: str(p, "name"), scope: str(p, "scope") });
+ state.set("newToken", out);
+ await loadTokens();
+ return { id: out.id, name: out.name, scope: out.scope };
+ },
+ });
+
+ commands.register({
+ id: "tokens.revoke",
+ label: () => "Revoke an app token",
+ group: () => "Account",
+ enabled: () => state.get("screen") === "app",
+ params: { id: { type: "string", required: true } },
+ run: async (p) => {
+ const id = str(p, "id");
+ await api.call("DELETE", `/api/me/tokens/${encodeURIComponent(id)}`);
+ if (state.get("newToken")?.id === id) state.set("newToken", null);
+ await loadTokens();
+ },
+ });
+
commands.register({
id: "nav.account",
label: () => "Account",
group: () => "Navigation",
mutates: false,
enabled: () => state.get("screen") === "app",
- run: () => state.set("route", "account"),
+ run: () => {
+ state.set("route", "account");
+ void loadTokens();
+ },
});
const health = new HealthMonitor(
options.fetch,
diff --git a/web/src/ui/account.ts b/web/src/ui/account.ts
index 1774de0..9c6cf64 100644
--- a/web/src/ui/account.ts
+++ b/web/src/ui/account.ts
@@ -1,4 +1,4 @@
-import { ApiError, type Engine, type Invite } from "../engine";
+import { ApiError, type AppToken, type Engine, type Invite } from "../engine";
import { h, ref, setAttr, setText } from "./dom";
import { iconNode } from "./icons";
@@ -230,9 +230,59 @@ function bindPasswordToggles(): void {
}
}
+function bindTokens(engine: Engine): void {
+ const c = engine.commands;
+ const panel = ref("tokens");
+ const form = bindForm("token-new", (d) => c.invoke("tokens.create", { name: field(d, "name"), scope: field(d, "scope") }));
+ const value = ref("token-value");
+ const copy = ref("token-copy");
+ const list = ref("tokens-list");
+ const empty = ref("tokens-empty");
+ const rows = new Map();
+ const usedText = (t: AppToken) => `${t.scope}, ${t.prefix}..., ${t.lastUsedAt ? `last used ${new Date(t.lastUsedAt).toLocaleString()}` : "not used yet"}`;
+ engine.state.watch("me", (me) => (panel.hidden = !me), { immediate: true });
+ engine.state.watch("newToken", (t) => {
+ value.value = t?.token ?? "";
+ copy.disabled = !t?.token;
+ if (t) (form.elements.namedItem("name") as HTMLInputElement).value = "";
+ });
+ copy.addEventListener("click", () => {
+ value.select();
+ void navigator.clipboard?.writeText(value.value).catch(() => document.execCommand("copy"));
+ setText(copy, "Copied");
+ setTimeout(() => setText(copy, "Copy token"), 1500);
+ });
+ engine.state.watch("tokens", (tokens) => {
+ const ids = new Set(tokens.map((t) => t.id));
+ for (const [id, r] of rows) {
+ if (ids.has(id)) continue;
+ r.li.remove();
+ rows.delete(id);
+ }
+ for (const t of tokens) {
+ const have = rows.get(t.id);
+ if (have) {
+ setText(have.used, usedText(t));
+ continue;
+ }
+ const btn = h("button", { class: "btn btn--quiet", attrs: { type: "button" }, text: "Revoke" });
+ const used = h("span", { class: "invite-row__role", text: usedText(t) });
+ const li = h("li", { class: "invite-row" }, h("span", { class: "invite-row__email", text: t.name }), used, btn);
+ btn.addEventListener("click", () => {
+ btn.disabled = true;
+ c.invoke("tokens.revoke", { id: t.id }).catch(() => (btn.disabled = false));
+ });
+ rows.set(t.id, { li, used });
+ list.append(li);
+ }
+ empty.hidden = rows.size > 0;
+ });
+}
+
export function mountAccount(engine: Engine): void {
bindPasswordToggles();
bindGates(engine);
bindFrame(engine);
bindAccountForms(engine);
+ bindTokens(engine);
}
From f43b79d193bdc1f276a68f8de76de6ac53ad7006 Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Wed, 2 Dec 2026 22:04:29 -0500
Subject: [PATCH 11/16] docs(agents): the dock connects agents by itself, and
Account makes and revokes app tokens (0.15.2)
agents.md describes the per-tab token, its environment, Claude Code's preset MCP server, revocation on close and at start, and the Account panel; cli.md replaces the note that the web app had no token screen; the README's agent paragraph says the dock needs no setup.
---
README.md | 2 +-
docs/ledger/agents.md | 6 +++++-
docs/ledger/cli.md | 2 +-
3 files changed, 7 insertions(+), 3 deletions(-)
diff --git a/README.md b/README.md
index 298e668..13c3244 100644
--- a/README.md
+++ b/README.md
@@ -126,7 +126,7 @@ The command line is a client of the running server; it never opens the database.
From 0.15.0 the window also has an agent dock, opened from View, Agent Dock, the robot button at the top right or with Cmd or Ctrl plus J: a terminal panel beside the books with a shell tab and tabs for Claude Code, Codex, Cursor and, from 0.15.1, Antigravity when they are installed on your computer. Only the owner of the books can open it, and only from this computer. On Windows its terminals do not open yet.
-From 0.15.2 agents can do what you can do at the window. `./formledger cli mcp` is an MCP server for Claude Code, Codex, Cursor and others (`claude mcp add formledger -e FORMLEDGER_TOKEN=fl_... -- /path/to/formledger cli mcp`): it reads and writes the books over every engine route and the command line, and runs any of the window's commands, from opening a page to posting an invoice or changing a preference. Posting, cancelling, allocating, deleting, period locks and invitations wait for your yes in the window, sign-in and tokens stay with you, and whatever an agent changes shows in the open window at once. [`docs/ledger/agents.md`](docs/ledger/agents.md) lists the tools.
+From 0.15.2 agents can do what you can do at the window. `./formledger cli mcp` is an MCP server for Claude Code, Codex, Cursor and others (`claude mcp add formledger -e FORMLEDGER_TOKEN=fl_... -- /path/to/formledger cli mcp`): it reads and writes the books over every engine route and the command line, and runs any of the window's commands, from opening a page to posting an invoice or changing a preference. Posting, cancelling, allocating, deleting, period locks and invitations wait for your yes in the window, sign-in and tokens stay with you, and whatever an agent changes shows in the open window at once. In the agent dock it needs no setup: each agent tab gets its own token, listed under Account, App tokens and withdrawn when the tab closes, and Claude Code starts with the server already connected. [`docs/ledger/agents.md`](docs/ledger/agents.md) lists the tools.
## Network
diff --git a/docs/ledger/agents.md b/docs/ledger/agents.md
index 63ebb10..b8fd008 100644
--- a/docs/ledger/agents.md
+++ b/docs/ledger/agents.md
@@ -4,7 +4,11 @@ Claude Code, Codex, Cursor and other agents can do in FormLedger what a person c
## Connect an agent
-1. Under Account in the window, make an app token (read or write). See `./formledger cli token`.
+In the agent dock nothing needs setting up. Each agent tab (Claude Code, Codex, Cursor, Antigravity) gets its own write-scoped app token when it starts, named for example `Claude Code tab, FormLedger dock`, with `FORMLEDGER_TOKEN`, `FORMLEDGER_URL` and `FORMLEDGER_AGENT` in its environment, so `formledger cli` works in it at once. Claude Code also starts with the `formledger` MCP server in its `--mcp-config` and a short note saying it is there. The token is stored hashed, is listed under Account, App tokens, where the owner can revoke it, and is withdrawn when the tab closes; tokens left by a run that ended without closing its tabs are withdrawn when FormLedger next starts. Both show in the audit log as the FormLedger dock.
+
+Outside the dock:
+
+1. Under Account, App tokens, make an app token (read or write). It is shown once.
2. Add the MCP server to the agent. For Claude Code:
```
diff --git a/docs/ledger/cli.md b/docs/ledger/cli.md
index 6d9e4ac..a827644 100644
--- a/docs/ledger/cli.md
+++ b/docs/ledger/cli.md
@@ -25,7 +25,7 @@ Every command prints JSON on stdout, or a table with `--table`. A problem prints
A token cannot be made from the command line. `POST /api/me/tokens` needs a signed-in browser session, and an app token may not make another one; `formledger cli token` only prints these steps.
-The web app has no screen for app tokens yet, so for now a token is made with curl and a session cookie. The `fl_...` value is in the answer's `token` field and is shown once:
+In the window, Account, App tokens makes one (name and scope; the `fl_...` value is shown once) and lists and revokes them. The agent dock makes one for each agent tab by itself. Without the window, a token is made with curl and a session cookie; the `fl_...` value is in the answer's `token` field and is shown once:
```
curl -c jar -H 'Content-Type: application/json' \
From 0be20277d6616880f0bd7682b0ce890c66e135ff Mon Sep 17 00:00:00 2001
From: nodemode-ai
Date: Wed, 2 Dec 2026 23:31:49 -0500
Subject: [PATCH 12/16] docs(hashout): the 0.16.0 roles' rationale for the
engine, the window and the shell (0.16.0)
ledger-startup (the missing app_ready call behind the 20 s macOS fallback,
and the shorter fallback) and ledger-parity (the agent module, the live
stream, the command bridge, the stdio MCP server, approval for risky
steps, per-tab dock tokens and the App tokens panel) appended their
sections and left them for one commit at the end.
---
internal/HASHOUT_LOG.md | 27 +++++++++++++++++++++++++++
src-tauri/HASHOUT_LOG.md | 9 +++++++++
web/HASHOUT_LOG.md | 34 ++++++++++++++++++++++++++++++++++
3 files changed, 70 insertions(+)
diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md
index 1a9e325..0a2609e 100644
--- a/internal/HASHOUT_LOG.md
+++ b/internal/HASHOUT_LOG.md
@@ -1958,3 +1958,30 @@ RFC 6455 server side only: the handshake through `http.ResponseController.Hijack
- logged: v0.15.1 · 2026-12-01 (EST)
The Form shell standard, line 3, lists Claude Code, Codex, Cursor and Antigravity tabs when installed. FormLedger 0.15.0 had the first three only. Antigravity is FormVis's fourth program (`backend/app/services/agent_lookup.py`): the executable `agy`, the install line `curl -fsSL https://antigravity.google/cli/install.sh | bash`. It joins `programs`, so `/api/agent/status` now answers `{claude,codex,cursor,antigravity}` and `POST /api/terminal/agent` takes `kind: antigravity`. It is looked for on `PATH` and the same install folders as the others and has no sign-in probe, so `signedIn` is null ("cannot tell"). FormVis writes an MCP entry into Antigravity's own folder for its tab; FormLedger has no MCP server, so nothing is written, as for the other programs. Removed: the refusal text `"the agent program must be codex or cursor"`, now `"the agent program must be codex, cursor or antigravity"`.
+
+### internal/agent · agents do what the person at the window can do
+- refers-to: internal/agent/module.go :: Mount, changes, live, ask; internal/agent/call.go :: call, routeClass, commandClass, blocked, compactResponse; internal/agent/jobs.go :: jobs, consents
+- kind: rationale
+- logged: v0.15.2 · 2026-12-03 (EST)
+
+The owner's rule (2 Dec): Claude Code and the other agents must be able to do everything a user can in FormLedger. Before this, agents had only `formledger cli` with a hand-made app token; the window's command registry was unreachable, nothing told the window about changes made elsewhere (views cache their data on first show), and the dock's shared Consent dialog was never wired. Design, the general one rather than a tool per screen: one module that (a) streams a `change` event after every successful unsafe `/api/` request (a middleware added from `Mount`, inside the auth middleware so the principal is known; quiet for the stream, the bridge, terminals and sign-in), (b) relays the window's command registry to agents (the window posts its catalogue; a run is pushed to the newest window of the same user over the same stream and its answer posted back), (c) runs any engine route for an agent through the full router (`router.Handler()` built once on first use, so every middleware, the auth middleware and each route's own `Require` see the caller's own `Authorization` header and cookies; no scope is widened), and (d) holds approval-class actions until the owner answers in the window.
+
+Approval classes are decided on the server, not trusted from the window: any DELETE, a last path segment of post, cancel, allocate, amend, confirm, lock or unlock, `POST /api/invites`, `/api/account/lock`; for window commands the same words in the id after the first segment plus `invites.*`, `account.lock`, `session.logout`, `app.quit`, `window.close`, `app.reload`, or the window's own `risky` flag. Blocked outright: sign-in, set-up, unlock, invitation accept, claim, app tokens, key backup, terminals, the agent routes themselves and the stream (`blockedPrefixes`), and the window commands `session.setup`, `session.login`, `session.unlock`, `invite.accept`, `account.claim`. With no window open an approval-class call is refused with `consent_needs_window`. "Always allow" is kept in memory per credential (token id, or the session's user) and class, until restart, never on disk. FormLedger sends no mail and makes no outbound request, so there is no external class.
+
+Every call or command is a job; the handler waits up to `wait` (default 15 s, at most 60) and otherwise answers the job id for `GET /api/agent/jobs/{id}`. Finished jobs are dropped after ten minutes. Answers are compacted on the server: any JSON array longer than the limit (default 50, at most 500) is cut and its full length reported under `truncated` with its JSON path, strings cut at 4000 characters, text at the limit's lines, and binary bodies replaced by their type and size. The stream sends a comment every 20 s and ends on shutdown through `Stop`, so `srv.Shutdown` does not wait on it.
+
+The direct `formledger cli` with a token is unchanged: it is the owner's own scripted path and keeps its existing role and scope checks. Writes made through `formledger cli mcp` (including its `ledger_cli` tool) go through `/api/agent/call` and so through approval, because the MCP client sets `Client.Agent`.
+
+### internal/cli/mcp.go · formledger cli mcp
+- refers-to: internal/cli/mcp.go :: mcpTools, mcpServer, viaAgent; internal/cli/cli.go :: run; internal/cli/client.go :: Do, NewClient, apiFailure
+- kind: rationale, alternative
+- logged: v0.15.2 · 2026-12-03 (EST)
+
+The MCP server is a `cli` group, not a top-level command, so it lives with the HTTP client that already holds the token handling and the one-writer rule, and `cmd/formledger/main.go` (ledger-startup's file this release) is untouched. It speaks newline-delimited JSON-RPC 2.0 on stdio, answers `initialize` (echoing the client's protocol version, with instructions), `tools/list`, `tools/call`, `ping` and empty resource and prompt lists, and runs calls concurrently so a call waiting for approval does not block a read. Tool text is cut at 24000 characters. `Run` became `(*env).run` so `ledger_cli` can run any cli command into a buffer with the agent client. Alternative not taken: a streamable HTTP `/mcp` on the server, which would need its own token handling inside the engine and would be reachable from any process on the machine without the user adding it to their agent. `NewClient` now falls back to `FORMLEDGER_ENGINE_URL`, which the dock sets in its terminals, because the desktop app may move to a free port.
+
+### internal/auth/tabtokens.go, internal/dock/module.go · a token per agent tab
+- refers-to: internal/auth/tabtokens.go :: MintTabToken, RevokeTabToken, SweepTabTokens; internal/dock/module.go :: openProgram, claudeMCP, Mount
+- kind: rationale
+- logged: v0.15.2 · 2026-12-03 (EST)
+
+The orchestrator's decision, on FormCite's precedent (its dock issues a write token per agent tab, host "FormCite dock", hashed, revocable, listed under the owner's tokens): Claude Code in the dock must work with no setup. `api_tokens` has no host column and no migration is added for one, so a tab token is marked by its name suffix `" tab, FormLedger dock"`; only tokens with that suffix can be revoked by `RevokeTabToken`, so a token the owner made by hand is never touched. The token belongs to the owner who opened the tab (the dock is owner-only and loopback-only), scope write; role checks and the approval classes still apply to everything it does. It is created and revoked in one transaction with an audit row whose actor is `FormLedger dock`. Revocation runs from the session's `onClose`, so closing the tab, closing all tabs on shutdown, or the dock's own close all withdraw it; if the server dies without closing, `SweepTabTokens` at the dock's `Mount` withdraws what is left ("left from an earlier run"). Restarting a tab keeps its token. Claude Code gets `--mcp-config` with a stdio server whose command is `os.Executable()` (the desktop sidecar is the same binary, so `cli mcp` exists there) and the token as `${FORMLEDGER_TOKEN}`, expanded by Claude Code from the tab's environment, so the secret is not in any process's argv. Codex, Cursor and Antigravity get the same environment (so `formledger cli` works) but no MCP entry yet: their config overrides were not checked against their current versions here.
diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md
index c51d0e8..7a915b6 100644
--- a/src-tauri/HASHOUT_LOG.md
+++ b/src-tauri/HASHOUT_LOG.md
@@ -373,3 +373,12 @@ Removed: `let window = WebviewWindowBuilder::new(handle, "main", WebviewUrl::Ext
- logged: v0.15.1 · 2026-12-01 (EST)
`menu::build` is the macOS menu bar from launch until the page has built its own from `web/src/ui/menus.ts` (`MENUS`, through `NativeMenus.build` and `setAsAppMenu`), and the one left if that build fails. It lacked three items the page's list has: FormLedger > Account (`cmd:nav.account`), View > Agent Dock (`cmd:view.dock`, Cmd+J) and View > Menus in Window (`cmd:view.menus-in-window`). They are added in the page's order and run through `window.__formledgerRun` like every other `cmd:` item. Menus in Window is a plain item here, not a check item, because the shell cannot read the page's `localStorage` choice; the page's menu, which replaces this one, shows the check. Checked with `cargo check` on Linux. The page's own build was checked in a stand-in macOS shell: 7 menus (FormLedger, File, Edit, View, Go, Window, Help), the 5 Go submenus, 55 command items and the predefined items, set as the app menu once.
+
+### src/reveal.rs · FALLBACK from 20 s to 6 s
+- refers-to: src/reveal.rs :: FALLBACK, conceal, show_main
+- kind: rationale
+- logged: v0.15.2 · 2026-12-03 (EST)
+
+The owner: "formledger takes 30 seconds JUST TO open" (macOS, 0.15.1). In 0.15.1 the page never invoked `app_ready` (see `web/HASHOUT_LOG.md`, revealApp), so this fallback was what showed the window, 20 s after the engine's ready line, behind the splash. With the invoke back the window shows at the later of 2.6 s after launch (`SPLASH_MIN`, kept, shared with the other Form apps) and the page's paint plus 220 ms for the bar. The fallback is now a safety net only, cut to 6 s so a future break of the invoke costs 6 s, not 20; the window is built with the dark `BACKGROUND`, so a page still loading shows that colour. The spawn path itself was read and needs no change: the sidecar is a native Go binary in `Contents/MacOS` (Tauri `externalBin`), not a onefile archive to unpack, and the shell waits on the ready line, not a poll. The rest of the owner's 30 s (20 s fallback plus engine start well under 1 s plus the 2.6 s splash floor leaves about 7 s) is most likely macOS's own first-launch assessment of a quarantined app and its sidecar (Gatekeeper, syspolicyd, translocation), which depends on FormCompiler's signing and notarisation, outside this repo (`tauri.conf.json` sets `hardenedRuntime` and an empty entitlements file; no signing identity here). Verified: `cargo check` on Linux. Not verified: a macOS build and launch.
+
+Removed: `const FALLBACK: Duration = Duration::from_secs(20);`
diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md
index e200474..0b08aa5 100644
--- a/web/HASHOUT_LOG.md
+++ b/web/HASHOUT_LOG.md
@@ -1033,3 +1033,37 @@ The window is moved by `data-tauri-drag-region="deep"` on the top bar, the sideb
The coordinator's review of the 0.15.1 captures: "Show the agent dock" drew as a plain checkbox, and so did the app lock in Preferences > Security and on the Account page. The Form apps use a toggle switch. FormPortal styles the checkbox itself (`main.css` `.switch`: `appearance: none`, a 36 by 20 px track with radius 10 px, `--bg-tertiary` with a 1 px `--border-light` inset edge, a 16 px knob drawn by `::after` 2 px in, `--text-primary` with `--shadow-sm`, the accent track and a 16 px knob move when checked, and the focus outline). FormVis draws the same sizes with a track span and a knob span (`dialogs.css` `.cv-toggle`). FormLedger's markup is already `
-
+
diff --git a/cmd/HASHOUT_LOG.md b/cmd/HASHOUT_LOG.md
index 563aa65..6ab7d07 100644
--- a/cmd/HASHOUT_LOG.md
+++ b/cmd/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the entry point, `embed.go`, `internal/server`, `internal/static` and `internal/startup`. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. Read it first, then edit code surgically.
-Current build version: v0.15.1
+Current build version: v0.16.0
Last updated: 2026-11-26 (US Eastern) · skeleton port from form.md
---
diff --git a/internal/HASHOUT_LOG.md b/internal/HASHOUT_LOG.md
index 0a2609e..1ea9040 100644
--- a/internal/HASHOUT_LOG.md
+++ b/internal/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of comment content, rationale and removed code for the core skeleton packages under `internal/`. Source files stay comment-free; what they would have said lives here, indexed. Read it first, then edit code surgically. Covers the packages ported in the core slice only; `internal/server`, `internal/static` and `internal/startup` are logged by their own slice.
-Current build version: v0.15.1
+Current build version: v0.16.0
Last updated: 2026-11-27 (US Eastern) · profit and loss and the balance sheet
---
diff --git a/internal/app/version.go b/internal/app/version.go
index bf7d754..dd10787 100644
--- a/internal/app/version.go
+++ b/internal/app/version.go
@@ -1,5 +1,5 @@
package app
-var Version = "v0.15.1"
+var Version = "v0.16.0"
const Product = "FormLedger"
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index f1800c4..f190825 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -1106,7 +1106,7 @@ dependencies = [
[[package]]
name = "formledger-desktop"
-version = "0.15.1"
+version = "0.16.0"
dependencies = [
"objc2",
"objc2-app-kit",
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index 66e35df..6d92cbb 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "formledger-desktop"
-version = "0.15.1"
+version = "0.16.0"
description = "FormLedger desktop app"
authors = ["NodeAgentc, Inc."]
license = "Apache-2.0"
diff --git a/src-tauri/HASHOUT_LOG.md b/src-tauri/HASHOUT_LOG.md
index 7a915b6..34ac465 100644
--- a/src-tauri/HASHOUT_LOG.md
+++ b/src-tauri/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the Tauri 2 desktop shell (`src-tauri`). Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of the shell: read it first, then edit code surgically.
-Current build version: v0.15.1
+Current build version: v0.16.0
Last updated: 2026-11-26 (US Eastern) · the shell ported from form.md's src-tauri and renamed for FormLedger
---
diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json
index 941ac4c..4865cbf 100644
--- a/src-tauri/tauri.conf.json
+++ b/src-tauri/tauri.conf.json
@@ -2,7 +2,7 @@
"$schema": "https://schema.tauri.app/config/2",
"productName": "FormLedger",
"mainBinaryName": "formledger-desktop",
- "version": "0.15.1",
+ "version": "0.16.0",
"identifier": "ai.nodemode.formledger",
"build": { "frontendDist": "splash" },
"app": {
diff --git a/web/HASHOUT_LOG.md b/web/HASHOUT_LOG.md
index 6300c1f..370a71b 100644
--- a/web/HASHOUT_LOG.md
+++ b/web/HASHOUT_LOG.md
@@ -2,7 +2,7 @@
Living log of all comment content, explainers, rationale, TODOs, & removed (hashed-out) code for the web client. Source files stay comment-free per dev-rules `sub-skills/hashout-log/SUB-SKILL.md`; everything they would have said lives here, indexed. This file is also the compressed contextual map of the web side: read it first, then edit code surgically.
-Current build version: v0.15.1
+Current build version: v0.16.0
Last updated: 2026-11-26 (US Eastern) · account screens, and the fixes from the throttled browser check
---
diff --git a/web/package-lock.json b/web/package-lock.json
index 3cf213b..8c70e01 100644
--- a/web/package-lock.json
+++ b/web/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "formledger",
- "version": "0.15.1",
+ "version": "0.16.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "formledger",
- "version": "0.15.1",
+ "version": "0.16.0",
"license": "Apache-2.0",
"dependencies": {
"@tauri-apps/api": "2.12.5",
diff --git a/web/package.json b/web/package.json
index afb9d1d..e352035 100644
--- a/web/package.json
+++ b/web/package.json
@@ -1,7 +1,7 @@
{
"name": "formledger",
"private": true,
- "version": "0.15.1",
+ "version": "0.16.0",
"license": "Apache-2.0",
"type": "module",
"scripts": {