mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-05 01:08:50 +01:00
e52c65af80f19f4e36668d6c50a6061ba80dc8ed
28
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e52c65af80 |
feat(loki): suggested replies on every Loki chat — one tap sends the likely next message (#1115)
Adopts @bitbaum/chatkit 0.6.0 (bitbaum/chatkit#13, merged as 163c879). - askLoki/runLokiTurn take `replies`: the model is asked for chatkit's quick_replies block, and it is taken out of every model reply as it arrives (loop rounds, retries, gateway and Groq fallbacks), so it never reaches a work note, the grounding verifier, or the stored answer. Replies return separately as body.replies. - /loki: the messages route asks for replies and stores them in meta.replies; the thread shows them under the latest answer with chatkit's ChatReplies (the separate follow-ups call is now only the fallback for an answer that came without them). - Terminal Loki rail: ChatThread gets onReply; replies hidden under a summary that already carries its own "→" steps. - Floating assistant: /api/loki takes `replies`; buttons under the last answer. - The live preview is stripped once, in useLokiStream, for every surface; plainTextForSpeech drops the block so it is never read aloud. MCP, voice and prompt runs do not ask for replies, and a stray block is still removed from their text. Fixes found on the way: - Floating assistant printed answers as raw text (asterisks, bare [F1] handles): now rendered as markdown with resolved citations; multi-line user turns keep their line breaks. - /loki follow-up taps were sent on "Auto" instead of the model the operator last chose; the terminal rail's replies reuse its last choice. Claude-Session: https://claude.ai/code/session_01Mg5wrkfw95JWfmAz8yRT1j Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
6af0b11f5f |
fix(control,loki): an agent waiting on you says so, and Loki stops answering in fragments (#1108)
From a phone session on Skif (2026-10-09), where every surface told a
different story about one idle agent:
- Control: a live session whose agent wrote `status: blocked /
awaiting_user` fell through to "Agent idle" and was counted idle, so
the hero read "0 awaiting input". New `awaiting_you` state ("Waiting
for you"), counted as awaiting input, selected first.
- Terminal sheet: the same session read "Agent went quiet · Open
Terminal — or Retry". When the agent's own handoff (written during
this run) says it is blocked on you, the sheet now says "Your turn",
shows its `next:` line, and drops Retry.
- Loki answers ended mid-clause (~230 chars each): llm.ts reported
`cutOff` from finish_reason and the loop ignored it. A cut-off answer
now gets one retry with a larger budget; if it is still cut off, it
says so.
- Citations: the sheet dropped answer sources, so each [F1] vanished and
left "pickup ." — sources now travel with the message.
- The sheet shows "12s · Running list projects" instead of a bare
"Working on it".
- Hero copy pointed to a "Needs you" panel "below"; the queue is "To
review", above.
- Project rows: bulk checkboxes only after "Select"; the bare "On" chip
reads "Autopilot".
Claude-Session: https://claude.ai/code/session_011L2dmcydDLYAiNQwK4XcF4
Co-authored-by: Claude <noreply@anthropic.com>
|
||
|
|
88c08a70cb |
Claude Code as a phone conversation, texting-app chat, operator-only OpenClaw, one task to several projects (#1024)
* feat(control): one task, several projects — write a cross-repo task once
A change that spans repositories ("make it so I can post prompts in
OrangeCat and Loki") had to be pasted into each project separately, and
each agent then tried to build the whole thing in its own repo.
- lib/multi-project-dispatch.ts fans one task out through injectPrompt
(same routing, serialisation, tracking as /api/inject). Names resolve
before anything is sent; an unknown name refuses the whole task and
lists the projects that would have worked.
- lib/multi-dispatch-prompt.ts: with 2+ projects each agent is told who
else got the task, which part is theirs, and to write down any
cross-repo contract it assumed.
- POST /api/inject/multi (session / agent token).
- POST /api/orangecat/task: signed OrangeCat rail, runs as the Loki user
linked to the actor, 409 with the next step when unlinked.
- Control: select projects on the rail -> "Send a task" opens the shared
Composer; a partial send keeps the draft and retries only the refused.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cwwmrb1uCjRv7wKDWLiA21
* fix(loki): the operator's OpenClaw agent and personal session are the operator's alone
Loki is multi-user with open sign-up, but three paths let any signed-in
account reach the instance operator's private agent:
- ask_openclaw (a `read` tool every user's tool loop advertised) queried
the operator's OpenClaw agent, which remembers their Telegram and
WhatsApp threads.
- The gateway fallback ran for every user whose tool loop failed, with
the operator's gateway token at operator.write scope.
- LOKI_PERSONAL_SESSION_KEY put every user's "Ask Loki" into the
operator's personal session.
Now: tools can be marked operatorOnly and runLokiTurn drops them unless
operator === true (fail closed); askLoki resolves "operator" from the
account (users.is_default) — never from a caller option — and only then
may fall back to the gateway; the personal session key applies to the
operator's account only. Everyone else keeps the shared chain and their
own per-user thread.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cwwmrb1uCjRv7wKDWLiA21
* feat(loki): a texting-app chat on phones
On a phone the chat got about a fifth of the screen: the app top bar, a
second row of two icons, a "save this exchange" row, a row of starter
chips, a four-row composer and the bottom tabs. Now:
- An open conversation takes the whole phone (useImmersiveChat hides
the app top bar and bottom tabs below md). Its own ThreadHeader is one
line: back to chats, the title with the project scope under it, and a
menu (New chat, All chats, Projects).
- Your messages are neutral bubbles, answers are plain 16px text, and
copy/retry are icon-only 44px targets on phones.
- The composer is one rounded card: words first, then one row —
attach · model · project on the left, mic beside send on the right.
The project pill sits inline (tap to change, × to drop) instead of a
header row, the builder badge is a coloured dot on phones, and starter
chips stay off phones mid-conversation. chatkit's stylesheet is
unlayered, so these overrides are unlayered too (a rule inside @layer
components silently loses to it).
- "Save this exchange to a project" scrolls with the thread instead of
holding a fixed row.
- The start screen is a messages inbox — round initials, title + time,
project under it, eight deep. It used to hide recent chats on every
phone because the desktop rail's pin (on by default) was treated as
"the rail is visible", so Back from a thread landed on nothing.
- On the start screen the chat's own two icons render inside the app
top bar's empty left half (TopbarSlot) instead of a second header.
Checked at 320/390 in light and dark: no horizontal overflow, send
never pushed off (model and project pills give up width first).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cwwmrb1uCjRv7wKDWLiA21
* feat(terminal): Claude Code as a conversation on your phone; a model sheet that reads like one
/terminal showed a Claude session only as its PTY — answers as 80-column
TUI cells, unreadable on a phone. Claude Code already writes the same
conversation as structured data, so now it is shown as one.
- lib/claude-transcript.ts (pure, tested): Claude Code's session JSONL
→ user / assistant / tool items. A tool's result lands on a later line
and updates its row in place; harness noise, sidechains and meta lines
are dropped; results are previews, never whole files. Consecutive tool
calls fold into one line ("Ran 2 commands, edited a file"), and a live
one says what is happening now ("Running git push").
- Runner (desktop 0.8.37): transcript-streamer.ts follows the newest log
for the folder the agent was launched in, reading only appended bytes
with fs/promises on a 1s timer, and only while someone watches — it
rides peek_start/peek_stop.
- Server: POST /api/control/transcript-frame (runner token) and
GET /api/control/transcript-stream (session). The server keeps the
latest conversation per (user, tab), so a phone that slept repaints at
once.
- ClaudeChatView: bubbles, readable answers, folded tool runs you can
open, an animated status line while Claude works, Allow / Always / Deny
when Claude may be asking, and a composer that types into the same PTY
(bracketed paste, so newlines do not send early). Stop is Esc; once you
type mid-run the slot becomes Send and Claude Code queues it. Chat is
the default view; the raw terminal is one tap away (header icon on
phones, "Chat" in the desktop pane chrome) and agents that write no
Claude log always get the terminal.
- Model picker: a bottom sheet on phones — plain names, one line on what
each is for, a check, locked rows saying why in words.
- Fix: the chat model you picked never reached the chat turn (askLoki had
no model; runLokiTurn always started at LOKI_MODEL). It now sets where
the free chain starts. And it is no longer handed to dispatched project
agents, which were being launched with a Groq/OpenRouter model id.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Cwwmrb1uCjRv7wKDWLiA21
---------
Co-authored-by: Claude <noreply@anthropic.com>
|
||
|
|
85ca56c82d |
feat(loki): the chat the operator already uses — drafts, recordings, work trail, queue (#1022)
* fix(loki): the composer draft survives a discarded tab
On a phone, tapping the paperclip hands control to Android's file picker,
and the browser tab is fair game for the memory killer while it is away
("Zu wenig Speicher für vorherige Operation", 2026-10-03). The open thread
came back — it lives in ?c= — but every word in the composer was React
state and went with the tab.
The draft is now mirrored to localStorage on each change, keyed per
thread (the start page has its own key), and restored once on mount. A
prefill wins over a stale draft. The workspace clears the draft under the
key it was WRITTEN in at send time, because a first message creates the
thread and moves the composer to the new key before chatkit's own
clear-after-send runs — without that, the next /loki visit would offer an
already-sent message back.
Text only: staged images are base64 in memory and would exceed the storage
quota; the picker reopens them in one tap.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TtBnGxwf5ddXTzRNyjHVP7
* feat(loki): attach a voice recording and it is transcribed into the composer
What the screenshots on 2026-10-03 were trying to do: tap the paperclip,
browse to Recordings, hand Loki a voice memo. The paperclip filtered audio
out, and a file that arrived anyway (Android hands over .m4a typeless) was
treated as text and refused as too large.
chatkit b30c843 (v0.3.0) teaches the shared composer that a recording picked
as a file is dictation that happened earlier: it goes to the same Whisper
server leg as the mic, under its own name, and the words land in the box.
This pins it.
The server leg had its own ceiling: 10 MB on the route and Groq's ~25 MB
request cap, against a phone recorder that writes ~1 MB a minute. The route
now takes 120 MB (chatkit's upload cap, the same number), and
lib/transcribe downmixes anything over Groq's cap to 16 kHz mono Opus
(~11 MB an hour; Whisper resamples to that itself) and, if still over,
segments it on twenty-minute cuts and transcribes them in order. Both steps
need ffmpeg, which the box has for the local-Whisper fallback, and only run
past the cap, so the widget's 3 MB clips never reach them. A segment that
fails loses the take rather than leaving a silent twenty minutes that reads
as if nothing was said.
The lockfile entry for chatkit was computed from the codeload tarball
(sha512 of the exact archive, version from its package.json) because pnpm
cannot resolve a second, private git dep from this sandbox; CI's frozen
install is the check.
Test: pure decisions, plus a real ffmpeg downmix of a synthetic 25.6 MB WAV
that reaches the Groq step.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TtBnGxwf5ddXTzRNyjHVP7
* feat(loki): the thread shows what Loki said and ran, live and reopened
The operator reads one rhythm all day in the Claude Code app: a sentence,
a collapsed group of commands with a chevron, a sentence, the answer. Loki
threw that away twice. What the model SAID in a gathering round ("Found it
— checking who owns them") was discarded at the next round's `reset`, so
the operator watched a spinner where they should have read the thinking.
And the tools it ran lived only in the live spinner and a list of names in
provenance: a reopened thread showed an answer that had apparently cost
nothing.
lib/loki/work.ts is the shape, pure and client-safe: one list in turn
order of notes (what Loki said while gathering) and tools (what it ran,
with the outcome). The loop keeps a gathering round's prose as a note and
streams it as one before the reset; tool steps join the same list; the
whole `work` returns with the answer and is persisted in provenance. The
hook applies note and tool events to the identical list live, and
WorkTrail renders segments — notes as prose in the trail's voice,
consecutive tools folded into one collapsible group, the running group
open — for the live turn and the reopened one alike, so nothing changes
between watching a turn and coming back to it.
A note is never the answer: grounding verifies only `text`, Copy copies
only `text`, and the note is styled as the trail, not the bubble.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TtBnGxwf5ddXTzRNyjHVP7
* feat(loki): queue the next message while a turn runs; show the command under each step
Two more places the thread differed from the chat the operator uses all
day, closed.
Queue. A send during a turn was refused — Send went dark until the spinner
stopped, the one place a chat makes the person wait on the machine. Now
the composer takes it (chatkit 5f9d737, `queue`: Send stays live beside
Stop, placeholder "Queue a message…"), the workspace holds it in order and
shows it as a pill with a way to take it back, and sends it through the
same `send` when the turn ends. Held, not dropped, when the turn failed:
the error and its Try again stand in front of it. The draft is cleared
under the key it was typed in, like any send.
Detail. Each tool step in the work trail now carries its arguments as one
short line (`query: "Elena"`) — the command under the step — in the code
face, cut to one line, streamed live and persisted with the rest of the
work. Empty arguments are no line rather than `{}`.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TtBnGxwf5ddXTzRNyjHVP7
* feat(loki): elapsed time on the live turn, Listen under every answer, the rail shows where each thread stopped
Three more details from the chat the operator uses all day.
Elapsed. The live status line now reads "2m 3s · Working on it". Without
the number, forty seconds and four minutes are the same three dots, and
the operator cannot tell patience from a hang.
Listen. A play button under every answer reads it with the browser's own
voices — no upload, no key, offline. Markdown is flattened first
(lib/loki/speech-text.ts: headings, emphasis, citations, URLs and fenced
code are not prose), the voice language is guessed from the text so a
German answer is not read in an English voice, one utterance at a time,
stopped on unmount. Hidden where there is no speechSynthesis rather than
shown dead.
Rail. Each thread shows its last line under the title — a title says what
a thread is about, the last message says where it stopped, which is what
decides whether to reopen it — via one correlated subquery, and the thread
with a turn in flight shows a spinner.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TtBnGxwf5ddXTzRNyjHVP7
* fix(loki): drain the send queue after a turn lands, not from an effect
CI lint on
|
||
|
|
a1cc13053c |
feat(mcp): message Loki from any AI app; the Telegram agent reads screenshots and videos (#965)
* feat(openclaw): the Telegram agent reads screenshots, photos and videos The Telegram agent is OpenClaw on bitbaum, and OpenClaw already describes inbound media before the chat model reads the turn — but on defaults that cut every description at 500 characters and read one attachment per message. A screenshot lost most of its text; an album was read as its first picture; video had a one-line "Describe the video." prompt. - scripts/openclaw/media-understanding.json: versioned tools.media.image and tools.media.video blocks (Gemini; screenshots transcribed verbatim, albums read whole; videos returned as transcript + visuals + claims + authenticity signs so the agent can argue about whether a clip holds up). tools.media.audio is deliberately untouched — voice notes already work. - scripts/openclaw/install-media-understanding.sh: the only way it reaches the box. Refuses without a Gemini key, writes through OpenClaw's own schema-validating `config set`, restarts the gateway, then proves an image (and, where ffmpeg exists, a video) is actually described. - scripts/test/openclaw-media-config.ts: pins the limits and the audio hands-off rule. Validated against openclaw@2026.4.23's schema locally. Not yet applied to the box. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018tsc8Yu7TQR9a6Y5xNYkeD * refactor(actions): share the decision and the enqueue report; let a turn be read-only Groundwork for the MCP server, so it calls the same code the chat seams do instead of a copy of it: - lib/actions/decide-action.ts: approve/reject one draft, lifted out of POST /api/actions/[id]/decision (which now calls it; wire shape unchanged). - lib/actions/enqueue-report.ts: what an enqueue outcome may truthfully be called (auto-approved / awaiting-approval / deduped), lifted out of POST /api/actions/propose (wire shape unchanged). - config/orangecat.ts: the OrangeCat origin and OAuth issuer in a DB-free module; Auth.js and the identity bridge read the issuer from here instead of each re-deriving it. - askLoki / runLokiTurn take `readOnly`: the tool loop drops its propose tools and the OpenClaw gateway fallback is skipped, so a caller granted conversation but not action cannot get Loki to act by asking. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018tsc8Yu7TQR9a6Y5xNYkeD * feat(mcp): a remote MCP server so AI apps can message Loki and have it act POST /api/mcp speaks MCP Streamable HTTP (stateless JSON-RPC 2.0; protocol 2025-11-25 / 2025-06-18 / 2025-03-26). claude.ai and ChatGPT connectors, Claude Code and Cursor can ask Loki, list the approval queue and projects, dispatch work, book appointments and decide queued actions. Auth: a ck_* agent token (both scopes), or an OrangeCat RS256 access token verified with node:crypto against the issuer's JWKS — iss, aud (must be the Loki resource URL, never a client id), exp. `sub` maps to the Loki user via orangecatActorId; an unlinked actor gets the sign-in step, not a 500. A missing or bad token is a 401 whose WWW-Authenticate points at the RFC 9728 metadata served at /.well-known/oauth-protected-resource(/api/mcp). Scopes loki.chat / loki.act and the tool map are SSOT in src/config/mcp.ts. Act tools go through injectPrompt, enqueueAction and decideAction — the functions the Telegram skill's routes call — so the approval queue gates them exactly as it does there. Both paths are excluded from the session middleware (proxy.ts, with the reason), registered in api-route-auth and the demo sandbox. Docs: docs/development/mcp.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018tsc8Yu7TQR9a6Y5xNYkeD * fix(openclaw): match the installer's smoke output with a here-string, not a pipe printf | grep -q can report a miss on a match under pipefail (grep exits, the writer takes SIGPIPE). no-grep-q-in-a-pipe caught it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018tsc8Yu7TQR9a6Y5xNYkeD --------- Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
20f4cebf65 |
feat(settings): power Loki with your own model — paste a key, get your best model (#921)
* wip: user_model_keys table + ai-kit 1.17.0 * wip: chat runs on the user's own model * wip: settings API + screen for the user's own model * wip: budget refusal offers your own model; tests * fix: narrow userId for the own-model path; document BYOK_SEAL_SECRET * fix(demo): the shared demo account may not store a model key * fix(settings): deep links no longer cause a hydration mismatch |
||
|
|
4b9542c14e | feat(loki): deepen investigations without repeating tool actions (#865) | ||
|
|
33395d2c91 |
refactor(ecosystem): Loki is the execution layer, not the engineering one (#801)
"Engineering" named Loki's deepest capability, not the product. Today, People, Crew, Money, Goals and Habits ship here too, and OrangeCat — whose dashboard is economic entities — has no surface to receive them. Under the narrow label those two thirds read as scope creep, and the conclusion drawn from it, twice in one session, was "move the life-ops half to the Cat". There is nowhere to move it to. What actually separates the three products is AUDIENCE, not subject matter: OrangeCat is public by design, Loki private by default, Solon shared with its members. Work crosses a boundary when it needs to be seen, paid or decided — which is the seam Crew already implements, keeping an assignment private here and mirroring it to OrangeCat as a service only once it is paid. - fleet map: the `capability` layer becomes `execution`, and Loki's role sentence names the people, commitments and spending alongside the agents - both assistant prompts (chat + tool loop) introduce Loki as the operator's execution layer rather than a captain over projects alone - AGENTS.md / CLAUDE.md state the plane, and why the old word was wrong - new gate scripts/test/execution-plane.ts pins all three, so the rename cannot roll back quietly; picked up automatically by test:unit Claude-Session: https://claude.ai/code/session_01LJkpuZ2F3GWrB6TLycwy4A Co-authored-by: Claude <noreply@anthropic.com> |
||
|
|
254e451565 |
fix(ai): the tool loop spent tokens the ledger never saw (#776)
"One door" was wrong, and I said it confidently yesterday. groq.ts was metered — 19 callers, rows landing, verified. But Loki's CHAT turns do not go through groq.ts. They go through llm.ts, the tool loop, which records vendor quota, refusals and preflight skips and never recorded SPEND. Two days were spent working inside that file without checking it. THE LEDGER SAID SO PLAINLY 2026-09-17 groq 15 calls 13,806 tokens 2026-09-16 groq 11 calls 14,586 tokens 2026-09-15 groq 4 calls 1,926 tokens Three days, groq only, never once google — not because Gemini was idle, but because Gemini serves CHAT and chat was not being recorded at all. Every row on the capacity page's "spent today" was a background feature; the biggest consumer was missing entirely. IT ALSO MADE YESTERDAY'S FIX DEAD CODE The google row reads ai_usage to prove a vendor served despite publishing no limits. For the one vendor it was written for, that table could never contain a row. Correct, and structurally unable to fire. THE FIX `feature` is required on ModelCallInput, exactly as on GroqOptions, so the compiler names any caller that has not declared itself. The tool loop charges its spend on the success path, beside the health signal, fire-and-forget and caught like every other write there. A turn's three calls — round, plan retry, grounding repair — share one label, "loki-chat". They are one question being answered; three lines on the capacity page would read as three features. Two checks aimed at how the hole opened: BOTH doors must call recordUsage, and the label must be REQUIRED rather than optional. An optional field is what let sixteen callers go unnamed the first time. Gate green: tsc, lint, format, design, unit 194/194, home, desktop, ops. Claude-Session: https://claude.ai/code/session_01Nm2REqtdsVsvjukBU2maCz Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
a4529b94e3 |
fix(loki): the tool loop answers too, it does not narrate its plan (#717)
#709 stopped the Groq FALLBACK serving the model's plan as the answer. The same guard was missing on the tool loop — the path that serves nearly every turn. WHY GROUNDING CANNOT COVER THIS A plan asserts nothing, cites nothing and invents no proper noun, so it passes every rule in verifyAnswer while telling the operator nothing at all. That is exactly how it reached production: retrieval was fine, the answer was scratchpad, and every automatic check said the turn was clean. WHY THE GAP IS REAL AND NOT THEORETICAL openai/gpt-oss-20b — the model that demonstrably wrote "We need to answer: … We must cite each claim … Let's go through each:" and spent its whole budget on it — is link TWO of this chain. The only reason the leak has not been seen here is that gpt-oss-120b usually answers first. That is luck, and a fallback chain exists precisely for the times the first link cannot answer. MEASURED BEFORE ADDING IT Ran the detector over every assistant reply Loki has stored: 106 replies, fires on exactly 2 — both the same question, both from before the fallback fix, both genuine leaks. ZERO false positives on the other 104. That was the deciding number rather than the hit rate. A guard that misfires costs a second model call on a rate-limited free tier, which is the resource this whole week of work has been about conserving. THE CURE MUST NOT BE WORSE Four properties pinned, three of them about restraint: - a plan is retried ONCE, with the instruction the first attempt showed it needed — never a loop - a second plan is not an improvement, so it is not retried again - an EMPTY retry never replaces a real reply: a plan at least shows the model read the question - a good answer is never re-asked, so the common path costs nothing The retry carries no tools: the model already gathered what it needed, and the failure was in writing the answer, not in finding it. A failed retry leaves the first reply standing — losing the turn to protect its formatting is the worse trade. The stream is reset so the plan does not sit on screen above the answer. Proved by mutation: disabling the guard fails "the plan must not reach the operator" and nothing else. Verify green, 233 checks. Claude-Session: https://claude.ai/code/session_01Nm2REqtdsVsvjukBU2maCz Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
95c40a9cd8 |
refactor: rename the product from FleetCrown to Loki (#695)
The product, its assistant, the repo, the host and every unit on the box now share one name. 638 files, ~3,000 mentions: UI copy, config, env keys (FLEETCROWN_* -> LOKI_*), systemd units (fleetcrown-* -> loki-*), docs, articles, the deploy workflow other repos reuse, and nine file names. - Three article slugs carried the old name and had been shared; permanent redirects keep those links alive (next.config.ts). - test-no-retired-name.sh now also forbids the old product name across the whole repo, so the rename cannot creep back through templates and examples. - ASSISTANT_STACK collapses the product and the assistant into one entry, because they are now the same name. Infra was cut over ahead of this merge: /opt/loki, loki-* units, the `loki` database and role, loki.orangecat.ch (old host 308s to it; /api, /widget, /embed keep proxying), GitHub repos bitbaum/loki and bitbaum/loki-releases. The Resend sending domain stays fleetcrown.orangecat.ch until the new domain is verified in DNS. Claude-Session: https://claude.ai/code/session_016YJVAanfj8keVSXyZnTemh Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> |
||
|
|
83968bae23 |
perf(loki): show the tools the question needs, accept all of them (#687)
Groq's window is 8,000 tokens per minute. A measured feedback turn was 10,153, so the preflight skips Groq on every single call and a whole free provider is never used — which is the direct reason OpenRouter burns its 50 requests a day. Cutting RECORDS to fit would recreate the failure this retrieval layer exists to end. So I measured where the tokens actually are before touching anything: system prompt (tools on) : 1,869 of which the catalogue: 1,328 native tool schema : 1,141 FIXED OVERHEAD : 3,010 tokens, before a single record That is 47% of a 6,442-token turn, spent on eighteen tool descriptions. Scoping the catalogue to what the planner already routed saves 1,100–1,700 tokens per turn. The feedback question goes 6,442 -> ~4,780, inside Groq's budget, without dropping one record. THIS REMOVES NO CAPABILITY, AND THAT IS TESTED Only what the model SEES narrows. The accepted-name set stays the whole registry and every handler stays reachable, so a model that names an unadvertised tool still runs it. A test advertises exactly one tool, has the model call a different one, and asserts it executes. Three more properties pinned: the tools for every planned source are always advertised; the core four are always present (the pulse and project list answer "what else", the knowledge index answers "why did we decide that", and propose_action is the only lever Loki has on the world); and a question nobody could route advertises EVERYTHING, because it might need anything. MEASURED FIRST, ON PRODUCTION Baseline across five real questions before changing anything: every answer grounded ok, both objective checks passed (named "Heidi" for the latest feedback, "34" for the project count) — and ZERO turns called a tool. The seed answered all five. So this reclaims tokens from capability that no measured turn was spending. The same five re-run after deploy is what decides whether this stays. 164/164 unit test files; 38 planner checks (up from 33), 17 loop checks (15). Claude-Session: https://claude.ai/code/session_01Nm2REqtdsVsvjukBU2maCz Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
e5f8e8ea49 |
fix(loki): let it think, and fetch the thing you asked about (#668)
Asked "what do you think about heidi", Loki answered:
...`.
Everything is clean and strictly compliant.
</think>An opinion or assessment is: Not in your data.
…and then listed every record containing "Heidi", including two unrelated
people who happen to be named Heidi. Four defects, stacked.
## 1. A model's private reasoning was persisted as the answer
There is a literal `</think>` in the database. This repo already knew the
trick — TWICE, in `frontier/propose.ts` and `orchestration/dod-gate.ts` — and
both copies exist to make JSON parse. The one path a HUMAN reads had none.
`stripReasoning` now lives once, at the model seam next to
`stripToolCallLines`, and is applied at all four seams (tool loop, groq
buffered, groq streamed, gateway). The two old copies call it.
`lastIndexOf` rather than a regex is load-bearing: the leak had a CLOSING tag
and no opening one, because the head of the reasoning was lost upstream. A
`<think>[\s\S]*?</think>` pattern matches nothing there.
While streaming, nothing can know text is reasoning until the tag arrives — so
the gate now RETRACTS what it showed the moment the tag proves what it was.
## 2. It was forbidden to have a view
`buildContract` says every claim must cite a record (1) and anything without
one gets exactly "Not in your data." (3). An opinion is not a record, so the
model looked one up, failed, and refused. It was obeying the contract exactly.
ai-kit's OTHER builder, `buildAssistantRules`, already carries the equivalent
carve-out as its rule 5 ("general knowledge … is not covered by rules 1–2").
The typed-record builder never grew one — so the WEAKER contract is the usable
one and the stronger contract forbids reasoning.
Rules 7–10 are added as a NARROWING, inserted INSIDE the contract section:
the contract opens with "this overrides every formatting instruction below",
so a narrowing placed after the records would be outranked by the rule it
narrows. Both grounded paths share one assembly point, because the production
refusal came through the gateway while the loop carried the same defect.
The durable fix belongs upstream in `buildContract`; noted in the module.
## 3. Retrieval fetched the wrong subject
This was the one that made the answer useless, and it survived the prompt fix.
`peopleFacts(userId, message)` searches by the message. `documentFacts(userId,
message, limit)` searches by the message. `projectFacts(userId)` ignored it:
projects came back in table order and were then head-sliced. With ~30
registered projects that is a lottery, and the `Heidi` PROJECT lost it — while
the people search matched two contacts by name. Retrieval chose the subject of
the answer, and chose wrong. No prompt rule can recover a record that was
never fetched.
Projects the message NAMES are now ranked ahead of the slice. Pure, in its own
module because `sources.ts` imports `@/db`, which throws at load without a
connection string — and this repo's unit suite is env-independent.
## 4. A citation the verifier could not see
Found only by running it: nemotron cited `【F16】` in fullwidth brackets. Both
readers are ASCII-only, so the verifier's unknown-citation check silently had
nothing to check, and the renderer printed the handle verbatim as plumbing.
Normalised at the seam, before verification.
## Verified
Against REAL production records through the read-only tunnel, same question:
Heidi is an active project — status active [F16]. Its recorded description
is "Learn to understand and text in Zurich Swiss German.
heidi.orangecat.ch" [F16]. The latest development log notes the creation of
a /check page … and a PR #4 that has not yet been merged [F16].
No reasoning tags, no refusal, ASCII citations, 0 grounding violations.
Three new pure suites, each proven by MUTATION: removing the judgment clause
fails 7/10 checks; a no-op `stripReasoning` fails 3. The prose-gate test
replays the exact production bytes.
Claude-Session: https://claude.ai/code/session_018SCNNZ3cqMFzQtuGe6e1V9
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
||
|
|
4e29a12578 |
feat(loki): the chat shows its work — streaming, a stop button, one rail (#665)
Loki did more work than any other surface in the app and showed the least
of it. A turn is up to three model rounds with real retrieval in between —
it searches your people, reads your projects, queries the knowledge graph —
and all of it happened behind one static "Loki is thinking" line for as long
as it took. `runLokiTurn` has always returned `toolsUsed`, carrying the
comment "surfaced so the UI can show work". Nothing ever surfaced it.
## The turn streams, for real
Not a typewriter over a finished string. `agent/llm.ts` gained a genuine
`stream: true` path against the providers' OpenAI-compatible endpoint, with
`stream_options.include_usage` so a streamed turn is still BILLED — without
it the final chunk carries no usage and the day's ration would drain for
free on exactly the turns someone is watching.
Two rules keep the preview honest:
- **Prose is released a whole line at a time.** A weak model narrates its
tool calls as `TOOL:` / `ARGS:` lines, and the buffered path strips them
before anyone sees them. A chunk ending in `TOO` could still become
`TOOL:`, so nothing is shown until a newline proves the line finished.
Extracted as `createProseGate` and covered by `test:loki-prose-gate`,
including that it agrees with `stripToolCallLines` on the same text.
- **`delta` is a preview; `message` is the record.** The loop REPLACES its
answer every round (`text = turn.text`), and the grounding repair pass can
delete unsupported claims from a finished one. So round boundaries and
dead links emit `reset`, and the persisted turn replaces the preview when
it lands. Appending instead would leave a fabrication on screen that the
database does not contain.
The fallback path streams too. It is tempting to treat it as degraded and
therefore allowed to be silent — but it runs precisely when the free tiers
are drained and the tool loop cannot start, which is to say on the slowest
days. Leaving it unstreamed meant no visible streaming exactly when progress
most needed showing. One shared SSE frame reader, not two.
## What else changed
- **A stop button.** There was none: a running turn could not be cancelled.
It takes the same slot as send, and the abort reaches the provider call.
- **The work trail** — each tool as it runs, with the records it actually
returned. A failed tool reads as "unavailable", never as "nothing found".
- **One rail instead of four navigations.** The global sidebar, a
Chat/Control/Terminal strip, a pinned history rail AND a "Chats / New"
toolbar all led to the same two actions. The rail owns them now.
- **A model picker** that says what it does: a choice sets where the CHAIN
starts, and the fallback below it survives — a hard pin on a free tier is
a scheduled outage. Vendors without a key are listed, disabled, with the
reason; never hidden, never fake-enabled.
- Copy and try-again on an answer. Autoscroll that follows only while you
are at the bottom, plus a way back down.
## Bugs found on the way
- `bg-accent-primary` + `text-white` is invisible in dark mode, where
`--accent-primary` is near-WHITE. The send arrow did not exist on a dark
screen. Same bug in `.ui-assist-send`; both now `text-text-inverted`.
- The composer was keyed on `activeId`, so creating the thread REMOUNTED it
mid-send — silently resetting the model choice and dropping staged files.
- That same transition looked like a thread SWITCH, so the transcript
cleared, showed "Loading conversation" over the streaming turn, and
refetched a thread the server had not finished writing. The question
vanished and the answer arrived alone.
- `.ui-loki-thread` was missing `flex flex-col`, making its `mt-auto` inert:
a short conversation pinned to the top with dead space above the composer.
- The rail's project filter could hide the thread you were reading, because
scope follows the answer. A filter may narrow what else is offered; it may
not hide where you are.
## Refactor
Three components deleted. The composer finally uses `useAttachments` — the
hook that was extracted FROM it and adopted by the Control and Terminal
composers, leaving the one surface it came from as the only one with a
private copy. Dispatch/approval/project-picker footers moved out verbatim,
because rewriting honest-status logic to move it is how the regressions its
comments warn about get reintroduced.
`check-loki-classes.mjs` (wired into `check:design`) asserts every
`ui-loki-*` class is both defined and used. A renamed class is invisible to
tsc, eslint and the build — it still renders, as unstyled markup. It found
six orphaned rules on its first run, and fails under mutation.
Verified live: page renders at 1440/390/320 with no horizontal overflow, a
real turn streams against real models and the local DB, and the stop button
cancels one.
Claude-Session: https://claude.ai/code/session_01PMLf9PxnoryRqRxzVLu7WM
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
|
||
|
|
ebeeb8101d |
feat(loki): retrieve before answering — Loki could not see the fleet it is named for (#647)
George filed two reports through FleetCrown's own feedback widget, watched nothing happen, and asked Loki "what was the most recent feedback sent". Not in your data. Both rows were in site_feedback, filed minutes earlier. Four runs spawned from them sat in `waiting`. Twenty-four runs had errored in three days. The answer was nevertheless honest: Loki had been handed no records, so the sentence was true of what it could see — which is worse than an error, because a truthful negative reads as a checked one. Three independent causes, each sufficient alone. 1. NO SOURCE READ THE TABLE. `grep -rn feedback src/lib/agent/` returned nothing. Nor did runs, agent sessions, alerts, or notes. Loki could see the "life" half of the product (people, projects, goals) and nothing of the fleet half the product is named after. 2. THE PROMPT BUDGET WAS ARITHMETICALLY IMPOSSIBLE. One module constant — Groq's 12000-token minute window x 0.8 / 3 rounds = 3200 — applied to every vendor. Groq has since cut the window to 8000, and the prompt's own fixed cost measures 2946 tokens (system prompt 1264 + native tool schema 977 + catalog), leaving ~254 tokens: one fact. With the operator's message it goes negative, the fit correctly returns zero, and production logged `[loki] round 1: 40 facts exceed the call budget — sending 0` on every turn and sent it anyway with an empty Records block. 3. THE RICHER SEED WAS ON THE FALLBACK PATH ONLY. buildGroundedTurn (approvals, knowledge, economy, cues) ran only inside askLokiViaGateway. The primary loop seeded people + projects. So the approval queue seeded in #262 *specifically to survive losing the tool loop* was, on the path that normally ran, reachable only by the tool call the loop could not afford. WHAT CHANGED Retrieve first, then reason. A pure keyword planner (src/lib/agent/plan.ts) reads the question and fetches the relevant sources in parallel BEFORE the model is called; tools become depth, not basic retrieval. A tool loop needs a healthy model and a fitting prompt before it can ask its first question, which is exactly what is missing when this class fires. A regex is dumber than a model and never rate-limited. This is how OrangeCat's Cat has always worked. Eleven new fact adapters: feedback, runs, live agent sessions, alerts, notes, plus a computed fleet pulse (runner state, runs waiting/errored, unread feedback, pending approvals, today's AI budget) and a buildFleetBrief of SQL-computed answers the model may only phrase. Six new tools over them. Budgets follow the vendor: linkPromptBudgetTokens() sizes Groq from its minute window and large-context vendors by usefulness; the prompt is sized against the largest usable link and the walker SKIPS links it does not fit (a preflight, not a refused round-trip). Env-tunable without a deploy. When overhead busts every budget the loop now throws instead of sending an empty Records block. Conversation history reaches the primary path, so continuity no longer appears and disappears depending on which brain served the turn. Provenance is rendered: model, what was read per source, tools used, elapsed time, and the grounding verdict. The verdict was always computed and always returned; the route dropped it on persist and the assistant never read it, so a flagged answer looked exactly like a clean one — the failure the harness exists to prevent, reintroduced at the last inch. THE GATE (this is the third time this class has fired) Every read tool's data must ALSO be reachable from the seed. Seed = survivability, tool = depth, one adapter called by both. scripts/test/loki-retrieval-plan.ts fails the build on a read tool with no seed source, and on a seed source no question can reach. It caught a real orphan on its first run: the OrangeCat economy feed, fetchable but unreachable. Also fixed while here: propose_action reported a failed DB write as a successfully queued draft; the repair pass accepted a repair that invented a NEW unsupported claim if it had fewer total; assignee matching used a bare substring (the dr-UZH-nikov pattern on the write side); pageContext over 2000 chars 400'd the whole request instead of being clamped; the native tool schema repeated each full description, paying for the same prose twice. Docs: docs/architecture/loki-answering.md. Tests: 4 files, 63 checks, all env-independent. Claude-Session: https://claude.ai/code/session_01CAfKwM1oUSA9tU9fgdhfdf Co-authored-by: Cato <georgy.butaev@revamp-it.ch> Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com> |
||
|
|
d97fd69db1 |
refactor(deps): ai-kit comes from npm — @bitbaum/ai-kit ^0.6.2 (#473)
The package is now published to the npm registry as @bitbaum/ai-kit (npm's typosquat guard blocked the bare name "ai-kit", hence the scope; ai-kit PR #25 documents the rename — content is identical to the github:bitbaum/ai-kit#v0.6.2 tag). The git pin is retired: the lockfile no longer records the writer's ssh transport and npm-major-specific resolution for this dependency, so the whole lockfile-writer trap class dies with it. All imports move from 'ai-kit' / 'ai-kit/grounding' to '@bitbaum/ai-kit' / '@bitbaum/ai-kit/grounding'. Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
caa0e41c3b |
chore: add a formatter (#449)
* chore: add a formatter, matching the style this repo already writes singleQuote=false was chosen by counting this repo's own imports, not by fleet decree. The fleet is genuinely split and the two repos that already had a .prettierrc disagreed with each other, so there was no standard to restore. Quote style does not cross repo boundaries; having a gate does. Markdown is ignored for now — prettier rewraps prose, which would bury the real diff. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * style: format with prettier (1062 files) Mechanical. No behaviour change. This SHA is listed in .git-blame-ignore-revs so `git blame` skips it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * chore: teach git blame to skip the reformat Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * fix(lint): reattach two guards the reformat detached Both effects were one-liners, so a trailing eslint-disable-line covered the setState call: useEffect(() => { setSelected(new Set()); }, [q.length]); // eslint-disable-line ... prettier expanded the block. The comment stayed on the closing line while the call moved above it, so the guard protected nothing and the rule its author had deliberately silenced failed the build. This is the second shape of the same defect — hirnli had the eslint-disable-NEXT-line variant. Both come from the same fact: an eslint directive binds to a line number, so reformatting can silently unbind it, which makes 'mechanical, no behaviour change' false for any bulk reformat. * chore(desktop): bump the runner version the reformat requires desktop-release-drift enforces that anything built into Fleet Runner which differs from the last released tag must carry a version ahead of that tag — main read 0.8.15 and fleet-runner-v0.8.15 already shipped. A whole-repo reformat changes bytes under desktop/, so the gate fires. The alternative was adding desktop/ to .prettierignore, which would buy a quiet PR by carving a permanent hole in the formatter's coverage — the precise shape of silent drift this test was written to catch. Bumping is what the rule asks for and costs one patch release whose only content is whitespace. * chore: merge main and re-format A whole-repo reformat conflicts with any concurrent commit, and a conflicting PR runs no checks at all while reporting nothing. Conflicts resolved to main, which is correct because this branch changes formatting and nothing else. * chore: leave desktop/ out of this reformat desktop-release-drift is right to refuse this. Everything under desktop/ is built into Fleet Runner, so changing it means shipping: bump the version AND add a FLEET_RUNNER_RELEASES entry, whose stated audience is 'person who installed Fleet Runner and wants to know what changed'. For a whitespace-only build the honest answer is 'nothing', so that release should not exist — and I should not write release notes claiming otherwise. I had bumped to 0.8.16 to get the gate green. That was the wrong direction: publishing a build to three OS runners to keep a formatting PR quiet. Reverted. desktop/ is excluded in .prettierignore with the reasoning recorded there, to be formatted alongside the next real runner change, where the bump and the notes are true anyway. --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
bc0493f68f |
refactor(agent): the grounding harness is imported, not mirrored (#448)
FleetCrown half of the mirror retirement (fleet AI-engine plan, Phase 2). src/lib/agent/core was the CANONICAL copy of the harness, mirrored byte-for-byte into OrangeCat and policed by scripts/test/agent-core-drift.ts plus scripts/sync-agent-core.ts. Its own README called the duplication "deliberate and temporary" and named extraction to a package as the exit. ai-kit v0.6.2 is that exit; OrangeCat's twin PR (#846, merged) deletes the other side. Fourteen imports across nine files collapse from three deep paths to one subpath import. The sync script, the drift check and the npm script that ran it are deleted rather than kept green: with a single copy there is nothing left to drift, and a gate with no possible failure mode is noise wearing a uniform. ai-kit also moves v0.2.1 -> v0.6.2 (still the ai-ration name in the old lock entry); the three root imports this repo uses (chain, fair-share, limits) are unchanged surfaces across that jump, which typecheck confirms. The packaged copy differs from the deleted canonical by two mechanical deltas, both made where the code now lives: .js extensions on relative imports (pure ESM) and two null-guards under ai-kit's noUncheckedIndexedAccess. tsc clean; 124/124 unit test files pass (one fewer than before: the drift check no longer exists to run). Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
776d12b625 |
feat(ai-budget): enforce the ration, and bill it from the provider's own count (#304)
#303 shipped the fair-share policy with nothing calling it. This wires it in, so the free daily pool is actually divided instead of merely divisible. ai_spend one row per (user, UTC day). A rollup, not an event log: the only questions asked are "what has this user spent today" and "how many drew today", both on the hot path of every turn. UTC because the vendors reset on UTC midnight; bucketing on local midnight would hand out a share against a budget that had not refilled. dayCapacityTokens() sums the daily budget of every KEYED provider. A vendor whose key is absent contributes nothing, however generous its tier — counting it would ration users against tokens that cannot be reached. askLoki gates the WHOLE turn once, before any provider is called. Gating per path would burn the budget on two fallbacks and still say no. BILLED FROM REALITY, NOT FROM A GUESS. `llm.ts` now reads the provider's own `usage.total_tokens` and `loop.ts` sums it across every round AND the repair pass. Charging only the final call would under-count the expensive turns by the most — precisely the ones worth rationing. Admission still uses an estimate because it must decide before anything is spent, and it is deliberately on the high side: under-estimating admits turns the pool cannot cover, which produces the late-day wall this whole mechanism exists to prevent. Booked on paths that are easy to forget: a turn that produced no usable text (the tokens were spent anyway), a repair pass that was discarded (same), and the degraded Groq fallback (it draws on the same pool, so a user degraded onto it would otherwise spend the shared day for free). THE GATE FAILS OPEN. If the ledger cannot be read, the turn is admitted. Rationing is a nicety; a database hiccup becoming "Loki is down" is not a trade anyone would choose. This fleet has already lost a day to a guard that turned a QUESTION into a fatal step, so the test asserting it is the one that matters most here. The two refusals keep their distinct meanings all the way out to the user: `paced` carries a retry and explains WHY there is a wait ("so everyone gets a turn" is a reason a person accepts; an unexplained refusal reads as breakage), `share-spent` carries none and says when it resets. Offering a retry that cannot succeed today is the "try again shortly" lie in another costume. Migration is additive only — CREATE TABLE + FK + index, no destructive statements. The unique (user, day) index is load-bearing: without it two concurrent turns both read zero, both insert, and that user gets two rows and twice the share. The increment happens inside the database. Tests: 10 for the gate (fail-open, capacity SSOT, both refusals, a newcomer admitted at any hour), on injectable seams so they need no database — the behaviour worth proving is exactly what a DB-dependent test would not cover. tsc clean · eslint 0 errors · 85/85 unit files · 150 home tests · design ok · desktop ok. Co-authored-by: t <t@t.t> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
6b6cff070c |
fix(loki): shedding records was silent, so the count was confidently wrong (#286)
Asked "how many projects am I tracking, and what are their names?", prod Loki answered "You are tracking 5 projects" and named them, with citations. The account holds 22. The five were simply the tail of the list that survived trimFactsToBudget — sbb-lost-found, solon, surf-your-life, truthseeker, vitareba, the last five alphabetically. Nothing in the prompt told the model a longer list existed. It received a short list and answered the question in front of it, correctly. A wrong count that arrives with source citations is worse than "not in your data": it reads as a checked answer, and the most basic question you can ask a fleet dashboard is how many projects it is watching. facts.ts already solved this exact problem one level down — a field with no value renders as `<not recorded>` rather than being omitted, because a stated negative is far harder to overwrite than silence. Budget-dropped records had no such statement. So give them one: when the fit sheds records, the prompt now says how many were withheld, that the list is therefore incomplete, and that a total must not be stated from it. The notice is measured INSIDE fitFactsToBudget rather than appended after it — otherwise the very text that reports the shedding is what busts the budget and causes more of it. Not fixed here: the counts themselves still come from records rather than SQL. Directives (core/contract.ts) are the right home for an exact count and are currently built only for the daily brief. This change stops the confident wrong answer; it does not yet produce the confident right one. Guard: four cases in test:fact-budget, including that the notice is charged against the budget. Verified they bite by reverting the notice to a no-op and watching the suite fail. Co-authored-by: t <t@t.t> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
6d224282f8 |
fix(loki): don't teach the answering round a protocol it is forbidden to use (#277)
With the prompt now sized to fit (#274), the tool loop reaches its final round — and returned NOTHING. Observed on prod: three rounds ran, then "tool loop produced no text — falling back to gateway". The loop did all the work and threw the answer away. The final round disables tools at the API layer, but the system prompt still explained the TOOL:/ARGS: text protocol and listed the whole catalog. The model did as it was taught and wrote a tool call; stripToolCallLines removed those lines, because a narrated call must never reach the operator as an answer; what remained was an empty string. Same hazard in the repair pass, which also runs with tools off. So the prompt now depends on whether tools are actually callable. On an answering round it withholds the protocol, drops the catalog, and says to answer now from the facts. That also returns ~640 tokens to the fact budget on the round that needs them most — the catalog is the single largest block in the prompt after the facts themselves. The guardrails that do not depend on tools — no power to act, no web browsing, cite the record id — are kept on both paths, and the test pins that. Co-authored-by: t <t@t.t> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
761d6cb756 |
fix(loki): size the prompt to the minute's allowance instead of discovering it by failing (#274)
Loki's tool loop never completed a round in production. Every question fell back to the toolless path, which cannot read the tables the questions are about — so Loki answered from seed facts or said it had no data. Measured on prod, both models at FULL budget (70B 11959/12000 remaining, 8B 5959/6000 — there is no fleet contention): a 40-fact grounded prompt is ~15000 tokens. Groq charges the whole request against a tokens-per-MINUTE allowance of 12000, and a turn spends MAX_ROUNDS calls inside that same minute. So the first call of every turn exceeded the entire minute's allowance on its own, and even a first call that squeaked through left nothing for rounds 2 and 3. Retrying could not fix that: the shed ladder only reacts AFTER a refusal, and it re-entered each following round just as oversized. The loop was arithmetically incapable of finishing. Facts are what's big — fixed overhead (system prompt + all nine tool schemas) measures only ~1900 tokens — so the fix is to fit facts to a per-call budget BEFORE sending: 12000 × 0.8 split across the rounds. Overhead is charged first and recomputed per round, because the conversation grows as tool results accumulate. The reactive ladder stays as a safety net. Also fixes a silent bug the new tests found in trimFactsToBudget: `slice(-0)` is `slice(0)`, so a budget of ZERO returned the ENTIRE array — the exact opposite of the request. Nothing hit it before because the ladder floors at 4. Co-authored-by: t <t@t.t> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
52ede1bf1b |
fix(loki): a 429 that means "too big" is not a 429 that means "too busy" (#270)
* fix(loki): a 429 that means "too big" is not a 429 that means "too busy"
Groq returns 429 for two unrelated conditions and the handler treated them as
one. CAPACITY ("Rate limit reached ... Used 5959, Requested 400") means the
per-minute window is momentarily spent — waiting helps, and a smaller model has
its own budget so stepping down helps too. SIZE ("Request too large ... Limit
6000, Requested 15041, please reduce your message size") means ONE request is
larger than the entire allowance — waiting can never help, and stepping down
makes it strictly worse because the cheaper model has HALF the ceiling
(verified 2026-08-14: llama-3.3-70b-versatile = 12000 TPM,
llama-3.1-8b-instant = 6000).
So an oversized prompt stepped down to the model that could not possibly take
it, burned 25s in a wait for a window that never grows big enough, and then gave
up the turn. Loki's tool loop died on every question and every answer came from
the toolless fallback — which cannot read the tables the questions are about.
- classifyGroqLimit (pure) tells the two apart from the response body; status,
type and code are identical in both, so only the wording distinguishes them.
- llm.ts throws size-429s immediately, worded so loop.ts's shed ladder
recognises them and retries with fewer facts — the only thing that actually
fixes an oversized prompt.
- The shed ladder now goes to 5 attempts instead of 2: it is the cure now, not
a long shot, so let it shed far enough to fit.
- Unrecognisable bodies default to capacity: that path retries and degrades,
where guessing "size" would shed context that was never the problem.
Tests use bodies captured verbatim from the live API, including the daily-cap
body (capacity — the budget refills) which shares the size body's phrasing about
tokens per minute.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
* test(deploy-gate): a fixture builder must not be able to aim at a real repo
setup_repo commits and renames a branch to `main`. Pointed at a real checkout
that is a repo-destroying sequence, and this suite runs from `verify` on every
push, in parallel sessions — so "the paths are obviously fine" is not a property
worth assuming. It now refuses unless the fixture path is under $TMP, and
asserts the clone actually produced its own repo there (a failed clone would
leave the -C target missing, and with no `set -e` the suite marches on).
Also guards an empty $TMP, which would make fixture paths absolute-from-root
while still satisfying the "$TMP"/* containment pattern.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
---------
Co-authored-by: test <test@test>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: t <t@t.t>
|
||
|
|
8af9d46678 |
fix(loki): tool results always survive fact shedding (#260)
* feat(loki): approval queue is readable from in-app chat 'What's pending for approval?' grounded to 'Not in your data.' because the tool registry had the write half (propose_action) but no read over the actions table. Adds list_pending_approvals (read, Fact-contract, short ids quotable for chat decisions) + the pending_action fact kind. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(loki): wait out a bottom-rung Groq 429 instead of losing the turn The step-down handles a 70B rate limit, but when the 8B model ALSO 429s (org-wide tokens-per-minute — autopilot bursts starve interactive chat) the loop threw and fell back to the gateway, which cannot read the tables the question is about. Now: one bounded wait (retry-after, capped 25s), then retry; only then give up the turn. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(loki): tool results always survive fact shedding Two head-keeping slices silently deleted the tail — where tool results live — so the model fetched the approval queue and then answered 'Not in your data.': (1) the MAX_FACTS merge cap dropped fresh tool facts entirely when the seed already filled the cap; (2) the 413 prompt trim kept only the seed head. Policy extracted to fact-budget.ts (pure): merge keeps fresh facts whole and fills remaining room from the front; trim keeps both ends. Unit-covered (scripts/test/fact-budget.ts). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: test <test@test> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
b1d93fbe0a |
fix(people): Loki actually sees the book; search by company; do not crash sync (#250)
Seed named people into the Loki turn (it was answering from projects only). Search company/title/location. Read OpenClaw knowledge as JSON so better-sqlite3 cannot kill the prod process. Refuse single-token name matches so a random George cannot attach to another George. Co-authored-by: test <test@test> |
||
|
|
2814c0acfb |
fix(loki): citations are sources, not plumbing on the screen (#225)
The grounding work was leaking its own internals into the answer. From a live transcript: The habit most at risk today is Exercise — 0-day streak at stake, not yet done today [no record id]. FleetCrown Phase 2 — Adapters [F8] because it is stuck at 0% ... FleetCrown Phase 1 [F8] because it has a target date inside 3 days ... Three separate defects, all mine: 1. "[no record id]" — the contract demands a citation for every claim, but COMPUTED answers (the SQL brief) had no id to cite, so the model honestly wrote that the id did not exist. Computed answers now carry a [D1] handle like anything else, and the verifier accepts the D-series as legal — without which a model that correctly cites a computed result gets flagged for citing "something that does not exist", training the repair pass to delete TRUE statements. 2. Raw [F8] in prose. A bare handle is internal plumbing wearing the costume of a source: it tells the reader nothing and makes the sentence worse. Citations now render as a quiet superscript whose tooltip carries the actual record (subject, source, stored fields), resolved from `sources` returned by the turn and persisted into the message meta so a reopened thread still resolves them. An id with no resolvable record renders as NOTHING rather than bare — a dangling handle implies a source the operator cannot reach. 3. The save-to-context bar rendered in full after EVERY message, permanently occupying the strip between transcript and composer; on a laptop it clipped the tail of the answer being read. Saving to a project is an occasional deliberate act, not a per-turn one, so it is now a one-line trigger that expands when asked for. Mirror re-synced (the drift gate caught the core edit, as designed); OrangeCat's 690 cat tests still pass. 67/67 FleetCrown unit files. NOT fixed here, and worth stating: the same [F8] was cited for two different goals, and the verifier only checks that a cited id EXISTS, never that it SUPPORTS the claim. That is a real gap in the check, not a rendering problem, and it needs its own change. Co-authored-by: test <test@test> Co-authored-by: Claude Opus 5 <noreply@anthropic.com> |
||
|
|
44a9ffbd5f |
fix(loki): shed facts on a 413 instead of abandoning the tool loop (#223)
Browser-tested the previous fix and read the box log. The 429 step-down
fired exactly as designed:
[loki] llama-3.3-70b-versatile rate-limited, stepping down to
llama-3.1-8b-instant
[loki] tool loop failed: groq 413: Request too large for model
`llama-3.1-8b-instant`
A prompt sized for a 128k context does not fit a small one. So the loop
still gave up and fell back to the weaker-retrieval path, and the
step-down that was supposed to keep tools working achieved nothing — it
just moved the failure one line down the log.
The answer the operator saw was correct, but only because the FALLBACK
path now has fixed people lookup. The tool loop itself was not serving
production turns at all.
Facts are the elastic part of the prompt (projects plus accumulated tool
results) and the first ones are the most relevant, so a 413 now halves
the fact budget and retries: 40 -> 20 -> 10, which fits every model in
the chain. Non-413 errors still propagate immediately — retrying a 401
or a 500 only burns latency for a guaranteed second failure.
Both behaviours pinned in scripts/test/agent-tool-loop.ts (11 checks).
67/67 unit files pass.
Co-authored-by: test <test@test>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
|
||
|
|
538d9993f0 |
feat(loki): give Loki its own in-app tool loop (#214)
Loki was a thin proxy to the OpenClaw `main` agent, whose tool root is
~/.openclaw/workspace/. Asked who to contact, it grepped a schema-less
JSON blob there and narrated the incidental matches as attributes —
"Ilya Druzhnikov (UZH)", where UZH is the substring inside drUZHnikov.
FleetCrown's own `people` table, the authoritative one, was invisible.
You cannot constrain an agent whose retrieval you do not own. The
previous PR grounded the CONTEXT; this moves retrieval in-app so the
grounding is actually enforceable.
tools/registry.ts SSOT + defineTool(). Two kinds only: `read` and
`propose`. There is deliberately no `execute` —
Loki still cannot act, it queues drafts and the
operator approves. A test asserts that boundary.
tools/handlers.ts 8 tools over FleetCrown's own tables: people,
projects, pgvector knowledge, goals, habits,
commitments/events, propose_action — and
ask_openclaw, the gateway DEMOTED to one tool
whose output is labelled an unverified
second-hand report.
llm.ts the model seam, with TWO tool protocols.
loop.ts seed → model → tools → facts → verify → repair.
THE INVARIANT: every tool returns Fact[], never prose. A tool result
therefore enters the same contract as everything else — declared fields,
<not recorded> gaps, a citation id, the verifier. There is no channel by
which a tool can put text in front of the model without it also becoming
checkable evidence. ToolResult has no escape hatch; keep it that way.
Dual protocol, because tool calling is where cheap models diverge most.
Native `tools` is advertised; a line protocol (TOOL:/ARGS:) is parsed
from ordinary text on every response regardless, and the two are merged
and deduped. Line-based, not nested JSON, chosen for the weakest model
expected to run it.
That decision is measured, not assumed. `npm run probe:loki-models`
against live Groq: llama-3.3-70b, llama-3.1-8b-instant, qwen3.6-27b,
allam-2-7b and compound-mini ALL drive the loop — and all five did it
via the TEXT protocol, even where native tool calling was advertised
and supported. A native-only parser would have scored zero on every one.
Loop bounds are observed failure modes, not padding: weak models re-call
a tool that already answered, so 3 rounds; the final round advertises no
tools so the model is forced to answer rather than hang; a repair is kept
only if it reduces violations, so the safety pass cannot degrade a turn.
loki-core prefers the loop, falls back to the gateway (still grounded and
verified) on error or LOKI_TOOL_LOOP=0 — an operational escape hatch, not
a feature flag.
Loop deps are imported lazily so the module stays pure to load, which is
what lets scripts/test/agent-tool-loop.ts run with no DB and no API key:
10 checks over protocol tolerance (bolded keys, fenced ARGS, copied
parens, bare calls, trailing prose), the no-execute boundary, fact
accumulation, bad-argument recovery, and bounds.
Co-authored-by: test <test@test>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
|