Skip to content

feat(buddy): agent-native WebPC: tools and skills for every app, saved chats, eval harness - #2

Merged
codemug merged 37 commits into
mainfrom
feat/buddy-agent-native
Nov 23, 2026
Merged

codemug merged 37 commits into
mainfrom
feat/buddy-agent-native

Conversation

@codemug

@codemug codemug commented Nov 23, 2026

Copy link
Copy Markdown
Owner

Buddy becomes an agent that can drive WebPC: the desktop, Files and every enabled app, through a tool catalog and a skill wiki built from per-app packs.

What changes

  • Agent runtime (src/apps/ai-agent/runtime/): six meta tools (lookup_skill_index, read_skill, find_in_skill, find_tool, describe_tool, call_tool) over a catalog of 257 tools in 25 packs and 187 skills. Small-model aids:

    • flat argument types with teaching errors (each names the fix as one call line);
    • repair of LFM3 tool-call output;
    • an action policy that asks before destructive or external actions, and before changes after untrusted input.
  • Packs (agent/): system, desktop and files, plus one folder per app with tools.js and skills.md. Covered: the 13 ArtCraft apps (page API tools, and open and save through Files), Docs, Excalidraw, CyberChef, BeepBox, Terminal, Media Player, Packet Viewer, Network Tools and SQLiteViz.

  • Saved chats: chats are kept in the browser and keep running in the background while you switch between them. They share one model worker through a scheduler; each chat has its own Stop, and approval cards appear in the chat. A badge on the Buddy button shows running chats.

  • Fixes found by live checks:

    • Network Tools showed no DNS records (it read Type and Data where DoH replies use type and data);
    • Docs could not type into a fresh document;
    • "open the app" requests no longer go to an app's open_file tool.
  • Eval harness (scripts/agent/eval.mjs, tests/agent-eval/tasks.yaml): 60 tasks run end to end against a real model in headless Chrome. Each task starts in an empty chat, and each check is proven by a positive and a negative control. Clean results on lfm3-1.7b, the default model:

    Variant Score
    Templates, prefetch on 24/60
    Templates, prefetch off (shipped) 29/60
    Examples, prefetch off 31/60

    Examples lead only on the GridCraft set, whose prompts reuse the example values word for word, so templates stay. qwen3.5-2b scored 0/20 on the first set (it loops on lookup_skill_index), so lfm3-1.7b stays the default.

  • Docs: a Buddy section in the README, and agent/README.md, a guide for adding an app pack.

How it was checked

  • node --test tests/*.test.mjs: 1110 pass, 0 fail, on the tree of this head.
  • npm run catalog: "agent packs valid: 257 tools in 25 packs, 187 skills."
  • Every pack's tools were run on the real WebPC page, and the result of each call was read. Examples:
    • GridCraft opens data.csv and reads Ada from A2;
    • CADCraft saves plan.dxf;
    • CyberChef SHA256 of "abc" is ba7816bf...20015ad;
    • SQLiteViz runs a GROUP BY;
    • NetTools lists the A records of example.com;
    • BeepBox plays and stops.
  • The eval harness checks passed positive and negative controls: 16 of 16 correct, plus the app reset for GridCraft, Docs and Excalidraw.
  • Public-safety scan of the 138 changed files: no internal names, local paths or work email.
  • Not run:
    • the Playwright browser suite on this head (last run: 25 of 25 Buddy browser tests at the saved-chats commit);
    • Safari, Firefox and a physical phone;
    • the four standalone ArtCraft apps' open and save, which wait for a click in the app;
    • Network Tools age encrypt and decrypt, which end in a browser download.

threads.js keeps one index row per chat under buddy:threads and one record per
chat under buddy:thread:<id>, with statuses for background runs, titles from the
first message, a 200-chat cap, and a one-time copy of the legacy single
conversation (legacy keys untouched). Every index write goes through one queue,
so concurrent saves from background chats never drop each other's changes.
runtime/search.mjs wraps MiniSearch for the tool catalog and the skill wiki:
OR semantics with prefix terms and field boosts, an auto mode (exact, then fuzzy,
then a regex of the longest word), a guarded regex mode, deterministic order,
filters, limits with a more flag, and excerpts. MiniSearch is MIT with no
dependencies, pinned exact and listed as an ai-agent npm source in catalog.yaml.
runtime/skills.mjs parses the skill wiki format (one skill per "## " heading,
slug, summary, keywords and tools metadata, When, Steps, Check and Gotchas
sections, steps as exact call_tool lines with quoted values and \n), checks
steps against the tool catalog and an injected argument checker, enforces the
1500 and 160 character caps, and renders a skill or one section within 1800
characters with a note naming the sections left out.
runtime/args.mjs coerces the raw strings small local models emit (and the JSON
values cloud models send) into nine flat parameter types: string, text,
integer, number, boolean, enum (with live app or window choices and aliases),
list, table and Files path. Every failure names the parameter, the expected
type or choices (at most 12 listed), the closest valid value, and one corrected
call_tool line to copy. Empty values count as absent.
runtime/catalog.mjs builds the tool catalog from packs: it checks names
(<pack>.<verb_object>, unique), effects, needs, parameter specs and every
example against the argument checker, reports all problems at once, builds the
search documents, and renders one-line signatures and describe_tool text within
1200 characters.
runtime/repair.mjs fixes, before validation, the mistakes real Qwen 0.8B and 2B
made in the M0 spike: signature text pasted into the tool name, inline k=v pairs
in it, cloud arguments objects or JSON strings, odd casing and separators, and
app-scoped window verbs (docs.close becomes desktop.close app=docs). Each repair
is reported back to the model. args.mjs now accepts JSON array text for list and
table values, and live enum specs (values: 'apps' or 'windows') pass specErrors.
agent/desktop/ is the first pack: 17 tools over window.pcHost (open, focus,
minimize, maximize, restore, close and force close, move, resize, tile, show
desktop, theme, icons, list apps and windows, open in a tab) and 15 skills
written as exact call_tool steps with task-like slugs.

scripts/agent/build.mjs, run by `npm run catalog`, discovers the packs (core
packs always, app packs only for enabled catalog apps), checks every tool and
skill step against the argument checker, and writes the catalog, the skill
wiki, both search indexes and the lazy pack imports to
src/apps/ai-agent/generated/ (gitignored). Any defect fails the build.
agent/files/ gives Buddy 10 tools over ctx.files (list, info, read, write,
overwrite, append, mkdir, rename, delete, find), with effects that mark
overwrite and delete destructive and errors that carry a corrected call (the
overwrite line when a file exists, a free name for a rename clash), plus 12
skills written as exact call_tool steps.
desktop.js now exposes a frozen window.pcHost (version 1): apps and windows,
open, focus, minimize, maximize (idempotent), restore, close (runs the app's
pcBeforeClose and reports dirty work instead of closing, unless forced), move,
resize, tile (left-right, grid, cascade), show desktop, theme, arrange icons,
open in a new tab or window, and appWindow (an app's window once it is ready,
with a timeout). Every call goes through the existing reducer and helpers, checks
its arguments first, and rejects with a code and the closest valid app ids.
Behaviour of the existing UI is unchanged.
runtime/meta-tools.mjs gives Buddy's model a fixed set of six tools over the
catalog, the skill wiki and their search indexes: lookup_skill_index,
read_skill, find_in_skill, find_tool (hits carry a ready call_tool line, not a
signature, because small models copy the text next to a name), describe_tool
and call_tool (repair, closest names on an unknown tool, argument checks with
teaching errors, then the executor; never retried).
Qwen 2B built names like desktop.close_app and desktop.close-app from skill
paths. An unknown name now tries dropping _app or _window, then adding _app,
and takes the first known tool.
Buddy's model now sees only the six fixed meta tools, so the tool block and
system prompt stay identical across rounds. Every action goes through call_tool
into the catalog built from the agent packs.

- runtime/index.mjs: the generated catalog, skills and search indexes, the meta
  tools, and an executor that checks each tool's needs (desktop host, Files,
  app, legacy tool), asks before destructive or external actions and after
  untrusted content, then runs the pack tool.
- Prefetch: before the first generation the runtime puts the best matching
  skill's steps (or the top tool examples) in the user turn. Only matches that
  share a meaningful word count; the note is never stored. In the M0 spike this
  took LFM3 from 5/10 to 9/10 tasks.
- session.js: agent mode is opt-in (legacy mode and its tests are unchanged).
  It has 16 rounds; a directly called catalog tool or an old name such as
  calculate runs through call_tool; http_get still allows hosts that
  web_search returned.
- agent/system: Buddy's existing tools moved into the system catalog, each
  delegating to its unchanged implementation, with 7 skills.
- runtime/files-ctx.mjs: ctx.files over the Files app's OPFS store.
- app.js wires the agent, window.pcHost, ctx.files and approvals (the native
  dialog for now); prepare-ai-agent bundles the runtime with esbuild.
runtime/policy.mjs decides each catalog call: reads are allowed; destructive
and external actions always ask; a change asks once the turn has read
untrusted content (a web page, search results, OCR text, or a file the user
did not name); a cloud model may only touch Files paths inside a granted
folder. An approval given this turn for the identical call is not asked again.
runtime/scheduler.mjs queues generation jobs per chat thread and runs them
round-robin with a set concurrency (1 for the single local model), so two busy
chats alternate step by step and a chat with many queued steps cannot starve
another. Cancelling a thread aborts its running job and drops its queued ones.
app.js builds the policy per call from the selected backend (local, cloud or
Chrome) and the current Files grants, so switching to a cloud model
immediately limits Files access to granted folders.
agent/shared/craft.js finds an ArtCraft app's page API (window.<id> inside the
WebPC wrapper's editor frame), waits for it to load, and wraps request,
execute, commands, inspect and screenshot with clear errors and no retries
(the upstream API warns that a retry can apply a command twice).

agent/apps/gridcraft/ ports 16 tools from GridCraft's own MCP server
(storytold/gridcraft v0.19.1 crates/mcp/src/tools.rs, MIT OR Apache-2.0), with
the same control-method mapping and flattened arguments: inspect, read and
write ranges, cells, formulas, selection, formatting, charts, tables, sort,
filter, new workbook, undo, redo and functions. It adds list_commands and
run_command over the app's live command list, plus 10 skills. The notice
records the source.
…raft sheet

- A pack tool may define effectFor(args). gridcraft.run_command uses it to mark
  file.new, file.close, sheet.delete and edit.clear destructive, so the policy
  asks first.
- app.js passes ctx.craft(id): the app's page API, opening the app when needed.
- Browser test: Buddy calls gridcraft.set_cells and GridCraft's own cell.get
  reads "Total" back from A1.
shared-model.js gives each chat thread a facade over the one local model (or
the cloud client). A thread's generation is issued only when the round-robin
scheduler gives it a turn, so two busy chats alternate and the cloud runs at
most 3 requests at once. Stopping a chat interrupts only its own request:
worker.js gains a per-request interrupt message (the running generation ends
early with its partial text, a queued one is dropped), ModelClient.interrupt(id)
and CloudClient.abort(id) send it, and the kill-everything stop() remains for
unloading the model.
agent/shared/inner-app.js finds an app's API inside its WebPC wrapper's inner
iframe and waits for it to load (polling, 30 s timeout, clear not_available
error). agent/apps/excalidraw/ drives Excalidraw's imperative API: add shapes
from a one-line-per-shape text spec, add text, list elements, fit the view, and
clear (destructive), plus skills. Checked live in the desktop: shapes, text,
listing and fit all work.
DeckCraft, CADCraft, PDFCraft, FigCraft, VectorCraft, FilmCraft, EffectCraft
and LightCraft join GridCraft. Each pack ports its tools from the app's own MCP
server at the release WebPC pins (MIT OR Apache-2.0; sources in the notices),
with the same control-method mapping and flattened arguments, plus
list_commands and run_command (with effectFor for destructive command ids) and
6 to 10 skills. FigCraft's skills adapt its upstream prompts.

agent/shared/craft.js maps each app's page API, normalises its command list
(array, {commands}, or a map), and turns an app's "no document open" into a
teaching error whose fix is the pack's own new-document call (new drawing in
CADCraft; new document in FigCraft and VectorCraft, which gain that tool; open
a PDF in PDFCraft). It also catches errors an app returns inside a successful
result.

Checked live in the desktop:
- every command id the packs and skills use exists in the real apps;
- real calls work from an empty app: the teaching error, then a new document,
  then edits read back (a circle in CADCraft, a frame in FigCraft, a rectangle
  and text in VectorCraft, slides in DeckCraft, opacity in EffectCraft, the
  playhead in FilmCraft, the library in LightCraft).
agent/apps/cyberchef/ bakes a recipe in the real CyberChef (inside its WebPC
wrapper frame) through the app's background worker, filling each operation's
default arguments the way CyberChef's own UI does (the first option's value
for editable options, the name for options), and lists operations by search.
Checked live: "hello world" through To_Base64 gives "aGVsbG8gd29ybGQ=", and
From_Hex then To_Upper_case on "68656c6c6f" gives "HELLO".
agent/apps/docs/ edits the real Docs editor: start a document, read its text
with a stable paragraph id each, insert a paragraph, set a heading, bold the
selection and find and replace. Edits land as accepted text: inserts are
accepted on the live editor view, replacements are a plain transaction on the
live view (so a paragraph is never split), and reads come from the live editor
state, not the page layout, which lags behind edits.

Checked live: new "Weekly report", insert "Second draft notes", replace "draft"
with "final"; get_text reads "Second final notes" as one paragraph.
readBytes and writeBytes let app packs open a file from Files in an app and
save the app's output back, with the same path checks, exists guard and change
broadcast as the text methods, and a size cap.
prepare-ai-agent copies an explicit file list into /pc/vendor/ai-agent/.
threads.js and shared-model.js were missing and runtime/scheduler.mjs was not
bundled, so Buddy's page failed to load in the browser while every unit test
(which imports from src/) passed. A new unit test fails whenever a relative
import of Buddy's page modules is not copied or bundled. The executor now
records approvals under the call line, the same key the policy uses.
Buddy posts pc:buddy-status {running, needsYou}; the taskbar button shows a
count badge (a warning colour when a chat needs the user) and an aria-label
such as "Buddy, 2 chats running". Only messages from Buddy's own frame count.
Buddy keeps every chat in browser storage and runs each in its own session on
the shared model:
- a Chats list (below the header) with New chat, rename, delete (asks first),
  relative times and status chips: running, waiting, needs you, done, failed,
  interrupted;
- switching chats never cancels anything, and a background chat's answer lands
  in its own history;
- New chat only starts a chat; it never stops one, unloads the model or
  clears the cloud key;
- Stop ends only the visible chat (during a model load it cancels the load);
- approvals are cards in the chat (Allow, Deny) instead of a blocking dialog,
  so a background chat can wait for the user;
- a reload reopens the chat that was open; chats running at the reload show
  interrupted;
- the legacy single conversation is copied into the list on first run;
- the badge counts are posted to the desktop.

Browser suite, run on a clean build: pc-buddy-threads, pc-buddy, pc-ai-agent
and pc-buddy-agent all pass (25 tests).
- media: play a file from Files (the app's own media-kind check, then an object
  URL on its player), pause, seek, volume (through the app's control, so it is
  saved) and status. Checked live: a WAV from Files plays, volume 0.4 applies,
  pause stops it.
- terminal: open the Terminal, read whether Linux is running, run code (the
  existing run_code bridge; the user still approves every run with a click),
  and save the Linux session.
Buddy can open a capture from Files, list its packets, apply a display
filter and read one packet's protocol tree, through the viewer's own file
input, filter box and table. A rejected filter comes back with the
viewer's own message.

Live check on the real page with a two-frame pcap (DNS query, TCP SYN to
443): open, list, filter tcp.port == 443 (1 match), list, detail 2, and a
broken filter all behaved as expected.
A freshly opened Docs window holds one empty paragraph with no paraId
yet, so docs.insert_text found nothing to insert after and told the
model to "type something first". It now types the text into that empty
paragraph on the live editor view and accepts it, like the other edits.

Live check on the real page, a fresh window: insert "Meeting notes",
get_text, then insert "Action items" after the new paraId: all OK.
Buddy can start a new song, set the tempo, read and load the song
link, and play or stop it. The editor is a top-level `let` in
BeepBox's page, so the pack reads it through the frame's own realm.
Stop decides from the synth's live playing state, and stopping a song
that is already stopped succeeds.

Live check on the real page: new_song, set_tempo 140, get_song, play
(playing true) and stop (playing false) all OK.
The DNS card printed "NOERROR:" followed by blank lines for every
lookup. formatDnsAnswer read rec.Type and rec.Data, but Cloudflare and
Google DoH replies carry lowercase type and data, and data is always a
presentation string. The old test fixture used the same wrong shape.
The test now holds replies captured from both services for A, TXT, MX,
NS, CAA and SOA.

The pack lets Buddy run a DNS lookup, an RDAP query, a subnet
calculation and a password strength check through the app's own forms,
and age encrypt or decrypt a file from Files.

Live check on the real page: example.com A gives 104.20.23.154 and
172.66.147.243; google.com MX gives 10 smtp.google.com.; subnet,
password strength, RDAP and a bad prefix (the app's own error) all
behave. The age tools end in a browser download and are not live
checked.
Buddy can open a file from Files in any of the 13 ArtCraft apps and
save the current document back to Files, so a user can say "open
data.csv in GridCraft" or "save this drawing as plan.dxf".

- Open drives the wrapper's own file input, so the app gets the file
  the way its Open button gives it, then waits until the app reports
  the new document before answering.
- Save takes the document bytes straight from the app where it can
  (GridCraft and DeckCraft file.saveBytes, CADCraft document.bytes,
  FigCraft file.saveAs, VectorCraft document.serialize). Elsewhere it
  captures the app's own save message, which also downloads the file.
- Bytes are always the app's own format. A target with another
  extension is refused with the corrected path (DeckCraft writes
  .deckcraft, not .pptx); VectorCraft lets the extension choose among
  its export formats.
- New packs for SoundCraft, PhotoCraft, MaterialCraft and TextureCraft,
  which have no page API: open, a save the user starts in the app, and
  status. LightCraft gets import_file.

Live check on the real page: GridCraft open data.csv, A2 reads Ada,
save out.xlsx (4089 B); DeckCraft refuses .pptx and saves .deckcraft;
CADCraft refuses .dwg and saves plan.dxf; PDFCraft open, doc_info and
a captured save; FigCraft, VectorCraft (.vectorcraft, .svg and .png),
FilmCraft and EffectCraft saves; LightCraft imports a PNG; the four
standalone apps report status. Their user-started saves are not live
checked.
Buddy can open a SQLite database from Files, list its tables and run
a query, reading the result table or the app's own error. Two
behaviours of the app needed handling:

- The editor copies typed SQL into the app's model after a 400 ms
  debounce, so the pack waits past it before pressing Run. Without the
  wait, a second query re-ran the previous SQL.
- A failed query shows its message in the result panel, not in the
  page's error line, so the pack reads it from there.

Live check on the real page with a seeded sales.db: open_db,
list_tables (sales), a GROUP BY giving North 160 and South 80 with
rowCount 2, and SELECT * FROM nope giving "the query failed: no such
table: nope." as a teaching error.
Once every ArtCraft app had an open_file tool, the small model on the
eval answered "Open GridCraft for me" with gridcraft.open_file. It
copied the example path from the parameter description, got a raw
browser error back, and looped.

- An open_file or import_file for a path that is not in Files now
  teaches: "<path> is not in Files. To open GridCraft itself, use
  desktop.open_app", with that call as the fix line.
- Path descriptions describe the accepted files instead of naming a
  realistic example file, and each open tool's when-line says it is
  not for opening the app itself.
- Files errors map a DOMException (numeric code 8) to not_found. Only
  string codes pass through as ToolError types, in files-ctx and in
  the Desktop, Files and Craft packs.
A 60-task suite now runs Buddy end to end against a real model in
headless Chrome (scripts/agent/eval.mjs, tests/agent-eval/tasks.yaml).
Scored on lfm3-1.7b, the default model, with each task in its own chat:

  templates, prefetch on      24/60
  templates, prefetch off     29/60  (new default)
  examples, prefetch off      31/60

- The per-turn skill note (prefetch) is off: it sat above the user's
  own text and often named the wrong skill. ?eval=1&prefetch=1 turns
  it back on, for eval comparisons only.
- find_tool, describe_tool and skill steps show call templates
  (key=<key>) instead of example values. Templates and examples tie
  on the suite. Examples lead only on the GridCraft set, whose prompts
  reuse the example values word for word. Elsewhere the model copied
  example values into real requests ("Second draft notes" for any
  Docs text). An unfilled placeholder is refused with a teaching
  error, and fix lines never echo an example path.
- lookup_skill_index ranks the apps a request names, so "open
  LightCraft" no longer reaches the Terminal skill first.
- qwen3.5-2b scored 0/20 on the first set: it loops on
  lookup_skill_index. lfm3-1.7b stays the default.

The runner reads every tool call through an ?eval=1 trace hook. It
deletes Buddy's saved chats at start and stops if a task does not
start in an empty chat. Earlier runs passed Buddy's 200-chat limit,
and the tasks then shared one chat, which skewed their scores. It
answers approval cards, clears Files and resets GridCraft, Docs and
Excalidraw before each task. A task passes only when the end-state
check holds and the expected tools ran in order; each check is proven
by a positive and a negative control.

Also: a Buddy section in the README, and agent/README.md, a guide for
adding an app pack.
Each change answers a failure class seen in the 60-task traces:

- An open_file or import_file with no path teaches desktop.open_app
  instead of a generic missing-argument fix ("Open the PDFCraft app"
  looped on pdfcraft.open_file).
- CyberChef bake takes SHA256, SHA-256 and the 224, 384 and 512
  sizes as SHA2 with that size. Live: SHA256 of "abc" is
  ba7816bf...20015ad and SHA512 matches shasum.
- Skill text: desktop switch, minimise, maximise and resize phrasings;
  files.list works without the Files window, but showing files means
  opening it; changing a word in Docs needs find_replace; the decode
  skill is found for "dode".
The eval model called describe_tool with path= instead of tool= and
got only "Unexpected field "path" is not allowed", then wandered. The
error now reads: Unexpected field "path"; this tool takes: tool.
@codemug
codemug merged commit c162308 into main Nov 23, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant