diff --git a/.gitignore b/.gitignore index d283938..347d881 100644 --- a/.gitignore +++ b/.gitignore @@ -28,6 +28,7 @@ public/pc/vendor/ # Generated from catalog.yaml (npm run catalog) src/scripts/pc/registry.generated.json +src/apps/ai-agent/generated/ # Upgrader output upgrade-plan.json @@ -35,3 +36,6 @@ upgrade-report.md # Upstream app icons placed by scripts/catalog/icons.mjs (pinned in catalog.yaml) public/pc/icons/ + +# Buddy eval run results (scripts/agent/eval.mjs) +tests/agent-eval/results/ diff --git a/README.md b/README.md index 2a63d85..043681a 100644 --- a/README.md +++ b/README.md @@ -65,6 +65,21 @@ | **Developer** | Terminal (Alpine Linux) · Packet Viewer (Wireshark dissectors) · VS Code (opens vscode.dev) | | **Utilities** | Files · Media Player · SQLiteViz · CyberChef · Network Tools (DNS, RDAP, global ping, subnets, password strength, age encryption) · VERT (opens vert.sh) | +## Buddy + +Buddy is the assistant behind the taskbar's Buddy button: a panel over the right third of the desktop, not a window. It runs a local model by default (Qwen3.5 0.8B or 2B, or LFM3 1.7B, the default; the weights download once after you load the model and are cached in this browser) and can use an optional cloud model with your own key, opt-in per session and never persisted. + +Buddy acts through a tool catalog of 257 tools in 25 packs, built by `npm run catalog` from the source packs in `agent/`: the desktop and its windows, the Files area, and every enabled app. It finds what to do with six meta tools: + +- `lookup_skill_index`: search the skill wiki for how to do a task. +- `read_skill`: read one skill by path, or one of its sections. +- `find_in_skill`: find matching lines inside one skill. +- `find_tool`: search the tool catalog for what a tool does. +- `describe_tool`: show a tool's full parameter list, effect and call template. +- `call_tool`: call a catalog tool with its own parameters. + +The action policy allows reads and asks before destructive or external actions, and asks before a change in a turn that took in untrusted content, such as a file read whose name was not in the user's message; an approval already given this turn for the same call is not asked again (`src/apps/ai-agent/runtime/policy.mjs`). `scripts/agent/eval.mjs` runs 60 tasks from `tests/agent-eval/tasks.yaml` against a running preview; the contributor guide for the packs is [agent/README.md](agent/README.md). + ## How it ships ```mermaid diff --git a/agent/README.md b/agent/README.md new file mode 100644 index 0000000..d631183 --- /dev/null +++ b/agent/README.md @@ -0,0 +1,155 @@ +# Buddy app packs + +How Buddy's tools and skills are built, and how to add a pack for an app. +Every pack is plain ES modules that run in the browser and in Node, so the +unit tests need no browser. The build reads the packs; nothing here is a page. + +## Layout + +- `agent/system/`, `agent/desktop/`, `agent/files/`: the core packs, always on. + The desktop pack drives `window.pcHost` (the desktop installed by + `src/scripts/pc/desktop.js`), the files pack the Files store. +- `agent/apps//tools.js`: the pack for one catalog app, included only when + the app has `enabled: true` in `catalog.yaml`. +- `agent/apps//skills.md`: the skills the wiki serves for that app. +- `agent/shared/`: helpers the packs share, such as `craft.js` (the Craft page + protocol), `inner-app.js` (digging into an app's iframe) and `craft-files.js` + (the Files open path). + +The build is `npm run catalog`, which runs `scripts/catalog/catalog.mjs` (validates +`catalog.yaml` and writes the desktop registry) and then `scripts/agent/build.mjs` +(validates the packs and writes `src/apps/ai-agent/generated/`). For each pack it +checks that `tools.js` exports `pack = { id }` matching its directory, that every +tool has a `run` function and a non-empty `purpose` and `when`, that the param +specs are flat and well-formed, that every `examples` entry passes arg checking, +and that every `call_tool` line in a skill's Steps passes `checkArgs` against the +tool's real params. It writes `catalog.json` (the tool catalog), `skills.json`, +`search-tools.json` and `search-skills.json` (the search indexes), `packs.mjs` +(lazy imports of each pack) and `INDEX.md`. The generated directory is gitignored; +commit nothing from it. Run the build after changing a pack. + +## The tool spec (tools.js) + +```js +{ + name: 'desktop.open_app', + purpose: 'Start an app on the desktop.', + when: 'Use when the user says start, launch or open, naming an app such as Files or GridCraft.', + params: { app: APP }, + effect: 'change', + needs: ['host'], + examples: [{ args: { app: 'gridcraft' }, says: 'Launch GridCraft' }], + run: async (args, ctx) => call(ctx, host => host.open(args.app)), +}, +``` + +- `name`: `.`, unique across all packs. +- `purpose`: one line, what the tool does. +- `when`: starts with "Use when", at most 120 characters: the user phrasings that + should reach this tool. +- `params`: a flat object of param specs. Each has a `type` (one of the types in + `src/apps/ai-agent/runtime/args.mjs` TYPES: `string`, `text`, `integer`, + `number`, `boolean`, `enum`, `list`, `table`, `path`), a `description`, and + optionally `required`, `values` (for `enum`, or the live `apps` list), + `default`, `min`, `max`. In the excerpt, `APP` is the pack's shared + `{ type: 'enum', values: 'apps', ... }` spec for an app id. +- `effect`: `read`, `change`, `destructive` or `external`. The policy allows + reads and asks before destructive or external calls. +- `effectFor` (optional): a function of the args that returns the effective + effect, for a tool whose danger depends on an argument. The GridCraft pack + marks `file.new` and `sheet.delete` destructive this way. +- `needs` (optional): the capabilities the runtime must provide (`host`, + `files`, `app:`), so the tool is a clean not_available error outside WebPC. +- `examples`: args a user utterance would produce, with the utterance in `says`. + The build validates them against the params. +- `run(args, ctx)`: the body. `ctx.host` is `window.pcHost`, `ctx.files` is the + Files store behind the access policy, and `ctx.craft(id)` is the app's page + API, opened if needed. + +## Teaching errors + +Wrap every failure the model can fix in a ToolError: +`new ToolError(type, message, fix)`, where `fix` is one call line the model can +copy (the signature is in `src/apps/ai-agent/runtime/args.mjs`). Small models +copy call lines. A generic error makes them guess and loop. The open_file +not_found teaching error in `agent/shared/craft-files.js`: + +```js +throw new ToolError('not_found', + `${path} is not in Files. To open ${title} itself, use desktop.open_app; to open a file, find it first with files.find.`, + `call_tool tool=desktop.open_app app=${id}`); +``` + +The message says both ways out; the fix line points the model at the tool that +opens the app itself. + +## skills.md + +One `## ` block per skill. Before the first section come four metadata lines +(all required, and the slug must be unique, lowercase words with hyphens): + +```md +## Open a file from Files +slug: open-a-file-from-files +summary: Open audio, MIDI or a session that is stored in Files in SoundCraft. +keywords: open, load, from files, audio, midi, session, scraftz, import +tools: desktop.open_app, soundcraft.open_file + +When: the user wants to open audio, MIDI or a SoundCraft session that is stored in Files. +Steps: +1. call_tool tool=desktop.open_app app=soundcraft +2. call_tool tool=soundcraft.open_file path=/SoundCraft/session.scraftz +Check: soundcraft.status shows the wrapper opened the file; the session or audio appears in the editor. +Gotchas: change path= to the Files path of an audio, MIDI or .scraftz session file; SoundCraft stays silent until the wrapper's Enable audio button is clicked. +``` + +Then the sections: `When:` one line, the user intent. `Steps:` numbered +`call_tool` lines, the exact calls in order. The build checks every line against +the real tool, so a renamed param breaks the build. `Check:` how to verify the +end state. `Gotchas:` what the model gets wrong and how to stay out of it. +`parseSkills` and `checkSkills` in `src/apps/ai-agent/runtime/skills.mjs` are +the parsers and validators. + +## Rules learned live + +- Never put a realistic example value in a param description: `describe_tool` shows descriptions verbatim and the model copies them into its calls. Examples and skill steps reach the model as templates (`key=`), but teaching-error fix lines are built from the first example's values, so keep those neutral too. +- Read the live app state, not a cached view. +- Most apps run in an inner iframe of their wrapper page: use the dig-in and poll from `agent/shared/inner-app.js`. +- Messages from another frame arrive in that frame's realm, so do not use `instanceof ArrayBuffer` on them. +- Wait for the app to finish (open, debounce) before you read. + +## Testing + +One test file per pack: `tests/agent-pack-.test.mjs`, run with +`node --test tests/agent-pack-.test.mjs`. The test builds a fake window +(the wrapper window, the `#editor` frame, the app's page API) and drives the +real `tools.js` against it, and it runs the real build validators +(`specErrors`, `checkArgs`, `parseSkills`, `checkSkills`) over the pack's spec +and skills. List every API name the fake assumes in a comment at the bottom of the +test, and check each tool on the real page before merging: a fake that mirrors +your own assumptions proves only the code path. + +## The eval + +`scripts/agent/eval.mjs` runs the task suite in `tests/agent-eval/tasks.yaml` +(60 tasks: A desktop and files, B ArtCraft, C other apps, D cross-app) against a +running preview. It starts no server: a preview must already be serving the +desktop at `--base` (default `http://127.0.0.1:4333`), and the prepared +`app.js` must carry the `?eval=1` trace hook (run the build, then restart the +preview). Usage: + +``` +node scripts/agent/eval.mjs --model lfm3-1.7b --set A [--limit N] [--prefetch on|off] [--base URL] +``` + +`--model` is the key from `src/apps/ai-agent/models.js` (default `lfm3-1.7b`); +`--set` runs one set and `--task ` one task; `--limit` caps the count; +`--prefetch on` loads the Buddy document with `?prefetch=1`, the eval-only +switch that puts the best skill's steps in the turn (Buddy's default is off). +Chrome runs headless with WebGPU and a persistent profile +(`/tmp/webpc-eval-profile`), so model downloads are cached across runs. +Results go to `tests/agent-eval/results/--.json`: +per-task the tools seen, the end-state check, seconds and rounds, plus a +summary with the success rate, the tool accuracy and the median seconds. +A task passes when its end-state check holds and every expected tool was seen, +in order (a subsequence match, so extra calls in between do not fail it). diff --git a/agent/apps/beepbox/skills.md b/agent/apps/beepbox/skills.md new file mode 100644 index 0000000..11d8cb8 --- /dev/null +++ b/agent/apps/beepbox/skills.md @@ -0,0 +1,78 @@ +## Get the song link +slug: get-the-song-link +summary: Get the current BeepBox song hash (its share URL) and tempo. +keywords: song link, share, hash, copy, tempo, bpm, song data +tools: desktop.open_app, beepbox.get_song + +When: the user asks for the song link, or before loading a different song. +Steps: +1. call_tool tool=desktop.open_app app=beepbox +2. call_tool tool=beepbox.get_song +Check: the result has the hash (the part after # in a share URL) and the tempo in BPM. +Gotchas: the hash is the live song, so it is fresh after any edit; give the hash to the user as the part after # in a BeepBox URL. + +## Load a song from a link +slug: load-a-song-from-a-link +summary: Open a BeepBox song from a share URL or a bare hash. +keywords: load, open, import, paste link, song url, share url, song +tools: desktop.open_app, beepbox.load_song + +When: the user has a BeepBox song link or hash and wants it opened. +Steps: +1. call_tool tool=desktop.open_app app=beepbox +2. call_tool tool=beepbox.load_song hash=sJ3mR8k2q +Check: beepbox.get_song returns the same hash. +Gotchas: change hash=; a full URL is fine, the part after # is what matters; loading replaces the current song in the editor. + +## Start a new song +slug: start-a-new-song +summary: Clear the editor to a blank song; the current song is lost unless its hash was saved. +keywords: new song, blank, fresh, start over, clear, reset +tools: desktop.open_app, beepbox.new_song + +When: the user wants a fresh BeepBox song and agreed to lose the current one. +Steps: +1. call_tool tool=desktop.open_app app=beepbox +2. call_tool tool=beepbox.get_song +3. call_tool tool=beepbox.new_song +Check: beepbox.get_song returns a different hash (the blank song). +Gotchas: call get_song first and keep the old hash in the reply so the user can get the previous song back; this tool cannot undo. + +## Change the tempo +slug: change-the-tempo +summary: Set the song tempo in beats per minute. +keywords: tempo, bpm, speed up, slow down, faster, slower, beats per minute +tools: desktop.open_app, beepbox.set_tempo + +When: the user wants the song played faster or slower. +Steps: +1. call_tool tool=desktop.open_app app=beepbox +2. call_tool tool=beepbox.set_tempo bpm=180 +Check: the result reports the new tempo and beepbox.get_song agrees. +Gotchas: change bpm=; the app allows 30 to 300 BPM; tempo affects playback speed, not the notes. + +## Play the song +slug: play-the-song +summary: Play the current song from the start position. +keywords: play, listen, hear, start playback, audition, sound +tools: desktop.open_app, beepbox.play + +When: the user wants to hear the song. +Steps: +1. call_tool tool=desktop.open_app app=beepbox +2. call_tool tool=beepbox.play +Check: the result says playing is true. +Gotchas: if the app muted the audio (the WebPC audio guard), tell the user to check the speaker in the BeepBox window; playing can be stopped with beepbox.stop. + +## Stop the song +slug: stop-the-song +summary: Stop the song that is playing. +keywords: stop, pause, halt, quiet, silence, end playback +tools: desktop.open_app, beepbox.stop + +When: the user wants playback to stop. +Steps: +1. call_tool tool=desktop.open_app app=beepbox +2. call_tool tool=beepbox.stop +Check: the result says playing is false. +Gotchas: stopping is a no-op with a clear result when nothing is playing; the song position is kept for the next play. diff --git a/agent/apps/beepbox/tools.js b/agent/apps/beepbox/tools.js new file mode 100644 index 0000000..18ce0a2 --- /dev/null +++ b/agent/apps/beepbox/tools.js @@ -0,0 +1,185 @@ +// BeepBox pack: drive the vendored BeepBox editor (public/pc/vendor/beepbox, v4.2.2) inside the +// app's inner iframe. The vendored index.html (line 253) declares `let editor;` and then sets +// `editor = new beepbox.SongEditor(...)`; as a top-level `let`, the editor is not a window +// property, so the pack reads it through the frame's own realm (win.eval, see app below). +// The editor is a SongEditor (editor/SongEditor.ts): public doc (SongDocument, with public +// song: Song and public synth: Synth) is the live model. The song is the inner frame's URL +// hash, mirrored to localStorage pc:beepbox:song:v1 by the wrapper (src/scripts/pc/apps/ +// beepbox.mjs), which also sets the precedent for the button.playButton / button.pauseButton +// selectors. +import { ToolError } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { innerApi } from '../../shared/inner-app.js'; + +const APP = 'beepbox'; +const NEEDS = ['host', 'app:beepbox']; +const NOT_HERE = 'BeepBox is not available here (Buddy is not running inside WebPC).'; + +// Gate on ctx.host (needs: ['host', 'app:beepbox']), then turn host rejections, which carry a +// code (unknown_app, not_open, not_iframe, timeout, invalid_argument), and innerApi's +// not_available into a ToolError the model can act on. +const call = (ctx, fn) => { + if (!ctx.host) throw new ToolError('not_available', NOT_HERE, ''); + return Promise.resolve() + .then(() => fn(ctx.host)) + .catch(error => { + if (error instanceof ToolError) throw error; + throw new ToolError(error.code || 'app_error', error.message, ''); + }); +}; + +// The app window is the WebPC wrapper page; the real editor window is the #beepbox-frame +// iframe's contentWindow. The vendored index.html builds the editor in an inline classic script +// with a top-level `let editor`, which is NOT a window property, so win.editor is always +// undefined. It is read through the frame's own realm instead: win.eval runs in the inner +// realm's global scope, where the lexical `editor` binding is visible (live-confirmed: the +// inner page has no CSP, and editor.doc/song/synth resolve through it). +const app = async (host, ctx) => innerApi(await host.appWindow(APP), 'beepbox-frame', win => { + try { + const editor = win.eval('typeof editor === "undefined" ? null : editor'); + return editor ? { editor, win } : null; + } catch { return null; } +}, { sleep: ctx.sleep, timeoutMs: ctx.timeoutMs }); + +export const pack = { id: APP, title: 'BeepBox' }; + +export const tools = [ + { + name: 'beepbox.get_song', + purpose: 'Get the current song hash and tempo.', + when: 'Use when the user asks for the song link, or before loading or saving a song.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is the BeepBox song link?' }], + // The live model is the fresh source: editor.doc.song.toBase64String() is the shareable hash + // the app puts after # in URLs (SongEditor file menu copyUrl) and song.tempo is the live BPM + // (synth/synth.ts Song class). + run: async (args, ctx) => call(ctx, async host => { + const { editor } = await app(host, ctx); + return { hash: editor.doc.song.toBase64String(), tempo: editor.doc.song.tempo }; + }), + }, + { + name: 'beepbox.load_song', + purpose: 'Load a song from a BeepBox hash or share URL.', + when: 'Use when the user has a BeepBox song link or hash and wants it opened.', + params: { hash: { type: 'string', required: true, description: 'The song hash (the part after # in a share URL), or the full URL' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { hash: 'sJ3mR8k2q' }, says: 'Open this song' }], + // The editor listens for hashchange (SongDocument _whenHistoryStateChanged): when + // history.state is null and the hash is non-empty it loads the song from the hash via + // ChangeSong. The app keeps its own history state after boot, so clear it first + // (history.replaceState(null, '')) and set the hash; if the same song is already loaded, an + // empty-hash round trip first, so the hashchange that loads it actually fires. + run: async (args, ctx) => call(ctx, async host => { + const { win } = await app(host, ctx); + const value = String(args.hash).trim(); + const at = value.lastIndexOf('#'); + const raw = at >= 0 ? value.slice(at + 1) : value; + // A share URL without # has no hash to load; real hashes are base64 and never contain "://". + if (!raw || raw.includes('://')) throw new ToolError('invalid_argument', 'no song hash in the value (the hash is the part after # in a BeepBox share URL)', ''); + const target = '#' + raw; + win.history.replaceState(null, ''); + if (win.location.hash === target) { + win.location.hash = ''; + await new Promise(resolve => setTimeout(resolve, 50)); // let the empty hash settle before loading + } + win.location.hash = target; + return { hash: raw }; + }), + }, + { + name: 'beepbox.new_song', + purpose: 'Start a blank song; the current one is lost unless its hash was saved.', + when: 'Use when the user wants a fresh BeepBox song and agreed to lose the current one.', + params: {}, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: {}, says: 'Start a new BeepBox song' }], + // The app's own File menu action "+ New Blank Song" (SongEditor _fileMenuHandler case "new"): + // set the menu value to "new" and fire change; the handler resets the song through the normal + // change and undo machinery. The menu is the select inside .beepboxEditor that has a "new" + // option (option value "new", SongEditor file menu definition). + run: async (args, ctx) => call(ctx, async host => { + const { editor, win } = await app(host, ctx); + const menus = [...win.document.querySelectorAll('.beepboxEditor select')]; + const fileMenu = menus.find(menu => [...menu.options].some(option => option.value === 'new')); + if (!fileMenu) throw new ToolError('app_error', 'the BeepBox file menu was not found in the app', ''); + fileMenu.value = 'new'; + fileMenu.dispatchEvent(new Event('change', { bubbles: true })); + return { hash: editor.doc.song.toBase64String() }; + }), + }, + { + name: 'beepbox.set_tempo', + purpose: 'Set the song tempo in BPM.', + when: 'Use when the user wants the song faster or slower.', + params: { bpm: { type: 'integer', required: true, min: 30, max: 300, description: 'Tempo in beats per minute (the app allows 30 to 300)' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { bpm: 180 }, says: 'Speed the song up to 180 BPM' }], + // The app's own tempo stepper (SongEditor line 589: the stepper's change listener records + // ChangeTempo with the exact BPM): the stepper is the number input next to the tempo slider + // (the range input with min 0 max 14), so set its value and fire change. + run: async (args, ctx) => call(ctx, async host => { + const { editor, win } = await app(host, ctx); + const slider = win.document.querySelector('input[type="range"][min="0"][max="14"]'); + const stepper = slider?.closest('.selectRow')?.querySelector('input[type="number"]'); + if (!stepper) throw new ToolError('app_error', 'the tempo control was not found in the app', ''); + stepper.value = String(args.bpm); + stepper.dispatchEvent(new Event('change', { bubbles: true })); + return { tempo: editor.doc.song.tempo }; + }), + }, + { + name: 'beepbox.play', + purpose: 'Play the current song.', + when: 'Use when the user wants to hear the song.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Play the song' }], + // The app's own Play button (class playButton, visible while not playing; the wrapper's + // pcBeforeClose uses the sibling button.pauseButton selector). doc.synth.playing (the Synth + // playing getter, live-confirmed on the real editor) is the live state. Playback starts + // through the app's handler, so the state is re-read after a short settle: if it did not + // start, the audio context is likely suspended (the browser autoplay policy and the WebPC + // audio guard suspend it when the window was closed; a programmatic click is not a user + // gesture that can resume it), and the result says so. + run: async (args, ctx) => call(ctx, async host => { + const { editor, win } = await app(host, ctx); + if (editor.doc.synth.playing) return { playing: true }; + const button = win.document.querySelector('button.playButton'); + if (!button || button.style.display === 'none') throw new ToolError('app_error', 'the play button is not visible; the app may still be loading', ''); + button.click(); + await new Promise(resolve => setTimeout(resolve, 200)); // let the app's handler start playback + const playing = editor.doc.synth.playing; + return playing + ? { playing: true } + : { playing: false, note: 'the app did not start playing; the audio context may be suspended (autoplay policy or the WebPC audio guard), so click Play once in the app window to unlock audio' }; + }), + }, + { + name: 'beepbox.stop', + purpose: 'Stop the song that is playing.', + when: 'Use when the user wants playback stopped.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Stop the music' }], + // The stop is decided from the live state, never from button visibility (live check: right + // after play, the pause button's style.display was not a reliable signal). editor.doc.synth. + // playing (the Synth playing getter, live-confirmed) is the source of truth; stopping goes + // through the app's own pause button (class pauseButton; the wrapper's pcBeforeClose clicks + // exactly this selector). Stopping an already stopped song is a success, not an error. + run: async (args, ctx) => call(ctx, async host => { + const { editor, win } = await app(host, ctx); + if (!editor.doc.synth.playing) return { playing: false }; + const button = win.document.querySelector('button.pauseButton'); + if (button) button.click(); + await new Promise(resolve => setTimeout(resolve, 200)); // let the app's handler stop playback + return { playing: editor.doc.synth.playing }; + }), + }, +]; diff --git a/agent/apps/cadcraft/skills.md b/agent/apps/cadcraft/skills.md new file mode 100644 index 0000000..e5ab421 --- /dev/null +++ b/agent/apps/cadcraft/skills.md @@ -0,0 +1,135 @@ +## Draw a circle +slug: draw-a-circle +summary: Draw a circle at a point with a radius, straight from the command line. +keywords: circle, draw, radius, geometry, shape +tools: desktop.open_app, cadcraft.command_line, cadcraft.inspect + +When: the user wants a circle drawn in the drawing. +Steps: +1. call_tool tool=desktop.open_app app=cadcraft +2. call_tool tool=cadcraft.inspect +3. call_tool tool=cadcraft.command_line text=circle 0,0 5 +Check: cadcraft.inspect with entities=true lists the new circle. +Gotchas: change the center and radius; spaces act as Enter, so the whole command runs in one call; step 2 checks the drawing is open and its error names cadcraft.new_drawing when it is not. + +## Draw a line +slug: draw-a-line +summary: Draw a line between two points with the line command. +keywords: line, draw, segment, points, geometry +tools: desktop.open_app, cadcraft.command_line, cadcraft.inspect + +When: the user wants a line or segment drawn. +Steps: +1. call_tool tool=desktop.open_app app=cadcraft +2. call_tool tool=cadcraft.inspect +3. call_tool tool=cadcraft.command_line text=line +4. call_tool tool=cadcraft.command_line text=0,0 +5. call_tool tool=cadcraft.command_line text=10,0 +Check: cadcraft.inspect with entities=true lists the new line. +Gotchas: answer the active prompt one point at a time; a relative point is @dx,dy and a polar one @dist craftApi(await ctx.host.appWindow(id), id) (plan 9). +import { ToolError, callLine, closest } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { teachApp } from '../../shared/craft.js'; +import { filesCall, openAndAwait, readOpenFile, saveBytesCopy } from '../../shared/craft-files.js'; +import { releases } from '../../../scripts/pc/craft/releases.mjs'; + +const APP = 'cadcraft'; +const NEEDS = ['host', 'app:cadcraft']; +// run_command ids that replace the open drawing: the web app holds one drawing, so +// `new` replaces it (the lead probe confirms `new` as the only data-destroying id). +const DESTRUCTIVE = ['new']; +// The web app holds one drawing; with none open the app says "no drawing open" +// (engine cmd.rs:168) in a rejection (the control protocol ok:false, craft-libs +// page.rs request_promise_outcome) or in the result error field (control.rs:335/367, +// cmdline.input/key). teachApp turns that wording into the teaching error below. +const NO_DOC = { message: 'CadCraft has no drawing open.', fix: callLine('cadcraft.new_drawing') }; + +/** tools.rs pick(): copy the listed keys (when present) into a params object. */ +const pick = (args, keys) => { + const out = {}; + for (const key of keys) if (args[key] !== undefined) out[key] = args[key]; + return out; +}; + +// The window [[x0, y0], [x1, y1]] of query_entities and find_text as flat params. +const windowOf = args => ([args.window_x0, args.window_y0, args.window_x1, args.window_y1].every(value => value !== undefined) ? [[args.window_x0, args.window_y0], [args.window_x1, args.window_y1]] : undefined); + +// key=value lines -> object, with number and boolean coercion (the generic long-tail tool). +const parseParams = text => { + const out = {}; + for (const line of String(text ?? '').split('\n')) { + const row = line.trim(); + if (!row) continue; + const eq = row.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad params line "${row}": use key=value`, ''); + const raw = row.slice(eq + 1).trim(); + out[row.slice(0, eq).trim()] = /^(true|false)$/i.test(raw) ? raw.toLowerCase() === 'true' : /^-?\d+(\.\d+)?$/.test(raw) ? Number(raw) : raw; + } + return out; +}; + +export const pack = { id: APP, title: 'CADCraft' }; + +export const tools = [ + { + name: 'cadcraft.command_line', + purpose: 'Type one line at the command line, exactly as a user would.', + when: 'Use when the user wants to type a command or point at the AutoCAD-style prompt.', + params: { text: { type: 'string', required: true, description: 'The line: a command (LINE, CIRCLE, MOVE, ZOOM), a point x,y, @dx,dy, a keyword, or empty for Enter' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { text: 'circle 0,0 5' }, says: 'Draw a circle at the origin with radius 5' }], + // tools.rs:119 cmdline.input (spaces act as Enter, so a full command works in one call); + // the reply carries an in-band error field when the input is refused (control.rs:335) + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).request('cmdline.input', pick(args, ['text'])), + }, + { + name: 'cadcraft.script', + purpose: 'Run a multi-line command-line script, one input per line.', + when: 'Use when the user wants several command-line inputs run in sequence.', + params: { text: { type: 'string', required: true, description: 'Script text: one or more inputs per line, blank line = Enter' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { text: 'line\n0,0\n10,0\n' }, says: 'Draw a line from 0,0 to 10,0' }], + // tools.rs:120 cmdline.script + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).request('cmdline.script', pick(args, ['text'])), + }, + { + name: 'cadcraft.inspect', + purpose: 'Summarize the drawing: entities, extents, layers, selection.', + when: 'Use when the user asks what is in the drawing, or before planning changes.', + params: { + entities: { type: 'boolean', description: 'Also list entities with handles and geometry' }, + limit: { type: 'integer', description: 'Most entities to list when entities=true' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is in this drawing?' }, { args: { entities: true, limit: 50 }, says: 'List the first 50 entities' }], + // tools.rs:132 drawing.inspect + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).request('drawing.inspect', pick(args, ['entities', 'limit'])), + }, + { + name: 'cadcraft.query_entities', + purpose: 'List entities filtered by type, layer, selection or a window.', + when: 'Use when the user wants to find geometry, e.g. all circles on a layer.', + params: { + type: { type: 'string', description: 'Entity type: Line, Circle, Polyline, Text, ...' }, + layer: { type: 'string', description: 'Layer name' }, + selected: { type: 'boolean', description: 'Only the current selection' }, + window_x0: { type: 'number', description: 'Window corner x0 (all four set the window)' }, + window_y0: { type: 'number', description: 'Window corner y0' }, + window_x1: { type: 'number', description: 'Window corner x1' }, + window_y1: { type: 'number', description: 'Window corner y1' }, + crossing: { type: 'boolean', description: 'false = only entities entirely inside the window' }, + limit: { type: 'integer', min: 0, description: 'Page size (default 500)' }, + offset: { type: 'integer', min: 0, description: 'Page offset' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { type: 'Circle', limit: 10 }, says: 'Show me the circles' }], + // tools.rs:133 engine.execute entities; the window box is rebuilt from the flat params + run: async (args, ctx) => { + const params = pick(args, ['type', 'layer', 'selected', 'crossing', 'limit', 'offset']); + const window = windowOf(args); + if (window !== undefined) params.window = window; + return teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).execute('entities', params); + }, + }, + { + name: 'cadcraft.find_text', + purpose: "Read the drawing's texts: labels, notes, block attributes.", + when: 'Use when the user wants to find room names, sheet titles or notes in the drawing.', + params: { + contains: { type: 'string', description: 'Substring of the text (any case)' }, + layer: { type: 'string', description: 'Layer name' }, + window_x0: { type: 'number', description: 'Window corner x0 around the insertion points' }, + window_y0: { type: 'number', description: 'Window corner y0' }, + window_x1: { type: 'number', description: 'Window corner x1' }, + window_y1: { type: 'number', description: 'Window corner y1' }, + limit: { type: 'integer', min: 0, description: 'Page size (default 200)' }, + offset: { type: 'integer', min: 0, description: 'Page offset' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { contains: 'Room' }, says: 'Find the room name labels' }], + // tools.rs:134 engine.execute texts + run: async (args, ctx) => { + const params = pick(args, ['contains', 'layer', 'limit', 'offset']); + const window = windowOf(args); + if (window !== undefined) params.window = window; + return teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).execute('texts', params); + }, + }, + { + name: 'cadcraft.new_drawing', + purpose: 'Create a new drawing (imperial by default, or metric).', + when: 'Use when the user wants a blank drawing to start from.', + params: { metric: { type: 'boolean', description: 'Metric units instead of imperial' } }, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: { metric: true }, says: 'Start a new metric drawing' }], + // tools.rs:135 engine.execute new. Destructive: the web app holds one drawing, so + // this replaces the open one (upstream desktop drawings coexist). + run: async (args, ctx) => (await ctx.craft(APP)).execute('new', pick(args, ['metric'])), + }, + { + name: 'cadcraft.cancel', + purpose: 'Press Escape: cancel the running command or clear the selection.', + when: 'Use when a command is stuck or the user wants to stop entering values.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Cancel the running command' }], + // tools.rs:138 cmdline.key with key escape; a refused Enter echoes an in-band error + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).request('cmdline.key', { key: 'escape' }), + }, + { + name: 'cadcraft.list_commands', + purpose: 'Find drawing commands by a word in the id, label or alias.', + when: 'Use when the user wants a command and its id or parameter doc is unknown.', + params: { query: { type: 'string', description: 'Substring of a command id, label or alias, e.g. zoom or layer' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { query: 'layer' }, says: 'Which commands manage layers?' }], + // Generic tool (plan 9): the top 10 of the live commands() filtered as tools.rs:125-131 + // (id, label or any alias, case-insensitive); trimmed like the pilot. + run: async (args, ctx) => { + const all = await (await ctx.craft(APP)).commands(); + const q = String(args.query ?? '').trim().toLowerCase(); + return all.filter(command => !q || [command.id, command.label, ...(command.aliases ?? [])].some(part => String(part ?? '').toLowerCase().includes(q))) + .slice(0, 10).map(command => ({ id: command.id, label: command.label, params: command.params })); + }, + }, + { + name: 'cadcraft.run_command', + purpose: 'Run any CADCraft command by id with JSON parameters.', + when: `Use when a menu action is wanted by id; ${DESTRUCTIVE.join(', ')} replaces the drawing, so ask first.`, + params: { + command: { type: 'string', required: true, description: 'Command id from cadcraft.list_commands, e.g. line, circle, layer.new, move, zoom' }, + params: { type: 'text', description: 'Parameters as key=value lines, one per line; omit for the defaults' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.includes(String(args.command ?? '')) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { command: 'zoom', params: 'mode=extents' }, says: 'Zoom to extents' }], + // Generic tool (plan 9): unknown ids get invalid_argument with the 3 closest ids + run: async (args, ctx) => { + const app = teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix); + const all = await app.commands(); + if (!all.some(command => command.id === args.command)) { + const near = closest(args.command, all.map(command => command.id), 3); + const fix = near.length > 0 ? callLine('cadcraft.run_command', { command: near[0] }) : ''; + throw new ToolError('invalid_argument', `unknown command "${args.command}"${near.length > 0 ? `; closest: ${near.join(', ')}` : ''}`, fix); + } + return app.execute(args.command, parseParams(args.params)); + }, + }, + { + name: 'cadcraft.open_file', + purpose: 'Open a drawing from Files in CADCraft.', + when: 'Use when the user wants a drawing from Files. Not for opening the app itself; that is desktop.open_app.', + params: { path: { type: 'path', required: false, description: 'A Files path to a drawing file (.dxf, .dwg or .shx)' } }, + effect: 'change', + needs: ['host', 'app:cadcraft', 'files'], + examples: [{ args: { path: '/CadCraft/plan.dxf' }, says: 'Open the plan drawing from Files' }], + // Drives the wrapper's own #file input (app.mjs:38), so the open posts from the wrapper + // realm, as the app's host bridge requires (craft-libs web-host web.rs:106). The drawing + // opens alongside the open ones (engine session/files.rs open_drawing appends + activates), + // so a change; the wrapper's own unsaved-changes confirm still applies (app.mjs:35). + // openAndAwait waits until the app's inspect stops saying "no drawing open", so the + // result confirms the drawing actually loaded. + run: async (args, ctx) => { + const file = await readOpenFile(ctx, args.path, { id: APP, title: 'CadCraft' }); + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + return openAndAwait(craft, { id: APP, title: 'CadCraft', wrapperWindow: wrapper, name: file.name, bytes: file.bytes, accept: releases[APP].accept }); + }, + }, + { + name: 'cadcraft.save_copy', + purpose: 'Save the active drawing as a file in Files.', + when: 'Use when the user wants to keep a copy of the drawing in Files.', + params: { + path: { type: 'path', required: true, description: 'The Files path to write the copy to, e.g. /CadCraft/plan.dxf' }, + overwrite: { type: 'boolean', description: 'Replace the file when the path already exists; false when omitted' }, + }, + effect: 'change', + effectFor: args => (args.overwrite ? 'destructive' : 'change'), + needs: ['host', 'app:cadcraft', 'files'], + examples: [{ args: { path: '/CadCraft/plan.dxf' }, says: 'Save a copy of the drawing to Files' }], + // No path is ever passed (the browser has no file system). CADCraft has no + // file.saveBytes, so the bytes come inline from document.bytes (lead live check: + // execute('document.bytes', {}) -> { bytes: , data: }; the web build + // refuses DWG, so .dxf is the only native format and a .dwg target is refused by the + // guard with the .dxf fix). The result name is the inspect title + .dxf (a new + // drawing is Drawing1). teachApp turns a "no drawing open" rejection into the + // new_drawing teaching error. + run: async (args, ctx) => { + const wrapper = await ctx.host.appWindow(APP); + const craft = teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix); + const save = await saveBytesCopy(craft, { + id: APP, title: 'CadCraft', wrapperWindow: wrapper, target: args.path, + tool: 'cadcraft.save_copy', nativeExt: '.dxf', inlineCommand: { command: 'document.bytes', params: {} }, + }); + const written = await filesCall( + ctx, + files => files.writeBytes(args.path, save.bytes, { overwrite: Boolean(args.overwrite) }), + error => (error.code === 'exists' ? callLine('cadcraft.save_copy', { path: args.path, overwrite: true }) : ''), + ); + return { path: written.path, name: save.name, size: written.size, created: written.created, ...(save.note ? { note: save.note } : {}) }; + }, + }, +]; + +// Live-check exports (brief): every command id the curated tools pass to execute, +// and every control method passed to request. run_command also passes arbitrary +// ids from the live commands() list. +export const usesCommands = ['entities', 'texts', 'new', 'document.bytes']; +export const usesMethods = ['cmdline.input', 'cmdline.script', 'drawing.inspect', 'cmdline.key']; diff --git a/agent/apps/cyberchef/skills.md b/agent/apps/cyberchef/skills.md new file mode 100644 index 0000000..5b40c41 --- /dev/null +++ b/agent/apps/cyberchef/skills.md @@ -0,0 +1,77 @@ +## Encode text in Base64 +slug: base64-encode +summary: Turn plain text into its Base64 encoding with a single CyberChef operation. +keywords: base64, encode, base 64, b64, to base64, convert to +tools: desktop.open_app, cyberchef.bake + +When: the user wants to Base64-encode some text. +Steps: +1. call_tool tool=desktop.open_app app=cyberchef +2. call_tool tool=cyberchef.bake recipe=To_Base64 input=hello world +Check: the result output is the Base64 string and type says string. +Gotchas: change input=; underscores in recipe become spaces, so To_Base64 means the "To Base64" operation; the result also shows up in CyberChef's output pane. + +## Decode text from Base64 +slug: base64-decode +summary: Turn a Base64 string back into the text it encodes. +keywords: base64, decode, from base64, b64 decode, convert back, dode +tools: desktop.open_app, cyberchef.bake + +When: the user has a Base64 string and wants the original text. +Steps: +1. call_tool tool=desktop.open_app app=cyberchef +2. call_tool tool=cyberchef.bake recipe=From_Base64 input=aGVsbG8gd29ybGQ= +Check: the result output is the decoded text; ask the user to confirm it looks right if it is binary. +Gotchas: change input=; if the input is not valid Base64 the bake fails and the error message is returned. + +## Encode text in Hex +slug: hex-encode +summary: Turn plain text into its hexadecimal representation. +keywords: hex, hexadecimal, encode hex, to hex, byte dump +tools: desktop.open_app, cyberchef.bake + +When: the user wants to see the hex (byte) form of some text. +Steps: +1. call_tool tool=desktop.open_app app=cyberchef +2. call_tool tool=cyberchef.bake recipe=To_Hex input=hello +Check: the result output is the hex string, two characters per byte. +Gotchas: change input=; use the From_Hex operation to go the other way; hex is one byte per two characters. + +## Run a multi-step pipeline +slug: multi-step-pipeline +summary: Chain several CyberChef operations, each reading the previous output. +keywords: pipeline, chain, sequence, multiple, then, decode and +tools: desktop.open_app, cyberchef.bake + +When: the user wants several transformations applied in order. +Steps: +1. call_tool tool=desktop.open_app app=cyberchef +2. call_tool tool=cyberchef.bake recipe=From_Hex,To_Upper_case input=48656c6c6f +Check: the result output is the final step's output (here HELLO) and ops lists the operations run. +Gotchas: change recipe= and input=; operations run left to right, comma-separated, so From_Hex,To_Upper_case decodes first then uppercases; every name must be a real operation. + +## Hash the text +slug: hash-text +summary: Compute a digest (MD5 by default) of the input text. +keywords: hash, digest, md5, checksum, fingerprint, signature, sha256 +tools: desktop.open_app, cyberchef.bake + +When: the user wants a hash or digest of some text. +Steps: +1. call_tool tool=desktop.open_app app=cyberchef +2. call_tool tool=cyberchef.bake recipe=MD5 input=hello world +Check: the result output is the hash digest in hex. +Gotchas: change input= and recipe=; MD5 is shown as the example; for SHA-256 use recipe=SHA256 (UNVERIFIED until the live bake of "abc" confirms the digest) and likewise SHA224, SHA384 or SHA512; use cyberchef.list_operations for the other hash operations (SHA, CRC). + +## Find an operation +slug: find-an-operation +summary: Search the CyberChef operation list by name to learn the right recipe name. +keywords: operation, op, list, find, search, what can, which op +tools: desktop.open_app, cyberchef.list_operations + +When: the user is not sure of the exact operation name, or asks what CyberChef can do. +Steps: +1. call_tool tool=desktop.open_app app=cyberchef +2. call_tool tool=cyberchef.list_operations query=base64 +Check: the result lists matching operations with their names; use a returned name in cyberchef.bake recipe=. +Gotchas: change query= or drop it to list more; names use spaces (To Base64), so in a recipe write them with underscores (To_Base64); the list is capped at the top 10 matches. diff --git a/agent/apps/cyberchef/tools.js b/agent/apps/cyberchef/tools.js new file mode 100644 index 0000000..f86a3f9 --- /dev/null +++ b/agent/apps/cyberchef/tools.js @@ -0,0 +1,162 @@ +// CyberChef pack: the CyberChef app tools (bake a recipe, list operations). +// Every tool drives the CyberChef app the vendored release installs as window.app +// (public/pc/vendor/cyberchef/assets/main.js, v11.5.0; set on DOMContentLoaded, grep marker +// "window.app=new Ud("). The app runs recipes in a chef web worker, so the main-thread +// app.bake() is fire-and-forget (it posts to the worker and returns undefined); the result is +// delivered to the callback passed to the background worker's bake +// (app.manager.background.bake(input, recipeConfig, options, progress, step, callback)), which +// the worker answers with bakeComplete {dish, result, type, ...} or bakeError {error}. +// app.operations is the operation registry keyed by name (grep marker key:"filterOperations"). +import { ToolError, closest } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { innerApi } from '../../shared/inner-app.js'; + +const APP = 'cyberchef'; +const FRAME = 'cyberchef-frame'; +const NEEDS = ['host', 'app:cyberchef']; +const NOT_HERE = 'CyberChef is not available here (Buddy is not running inside WebPC).'; + +// Gate on ctx.host (needs: ['host', 'app:cyberchef']), then turn host rejections, which carry a +// code (unknown_app, not_open, not_iframe, timeout, invalid_argument), into a ToolError. +const call = (ctx, fn) => { + if (!ctx.host) throw new ToolError('not_available', NOT_HERE, ''); + return Promise.resolve() + .then(() => fn(ctx.host)) + .catch(error => { + if (error instanceof ToolError) throw error; + throw new ToolError(error.code || 'app_error', error.message, ''); + }); +}; + +// The real app runs in the #cyberchef-frame iframe of the wrapper page that appWindow returns +// (src/pages/pc/apps/cyberchef/index.astro:10); window.app is set on that inner window on +// DOMContentLoaded (main.js, grep marker "window.app=new Ud("). Dig in and poll until the app has +// the operation registry and the background bake worker (app.manager.background) is wired up. +const getApi = async (host, ctx) => innerApi(await host.appWindow(APP), FRAME, win => { + const app = win?.app; + return app && app.operations && typeof app.bake === 'function' && typeof app.manager?.background?.bake === 'function' ? app : null; +}, { sleep: ctx.sleep, timeoutMs: ctx.timeoutMs }); + +// A recipe is a comma-separated list of operation names; underscores become spaces, so +// "To_Base64" and "From_Hex,To_Upper_case" both parse. Operation names use spaces. +const parseRecipe = text => { + const names = String(text ?? '').split(',').map(name => name.trim().replace(/_/g, ' ')).filter(Boolean); + if (names.length === 0) throw new ToolError('invalid_argument', 'recipe is empty; give at least one operation, e.g. "To_Base64"', ''); + return names; +}; + +// Strip HTML tags and cap the length, for the one-line description shown to the model. +const brief = (html, max = 140) => String(html ?? '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').replace(/ +([.,;])/g, '$1').trim().slice(0, max); + +// A recipe bakes each operation with explicit args; when the recipe text names an operation +// without args, fill each from that operation's defaults the way the CyberChef UI does. An +// option, editableOption or list arg takes its first option (value[defaultIndex]): a plain +// string option is the value itself, while a {name, value} option uses the label (name) for +// option args and the editable value string for editableOption args (the op's run() calls +// .replace on the alphabet, so it must be a string, not the option list). An argSelector arg +// takes value[defaultIndex].name; every other type (string, number, boolean) takes the raw +// value, or the type's zero value when value is absent. +const defaultArg = (arg) => { + const value = arg?.value; + const index = arg?.defaultIndex ?? 0; + if (Array.isArray(value) && ['option', 'editableOption', 'list'].includes(arg?.type)) { + const opt = value[index]; + if (opt && typeof opt === 'object') return arg.type === 'editableOption' ? opt.value : opt.name; + return opt; + } + if (arg?.type === 'argSelector') return Array.isArray(value) ? (value[index]?.name ?? '') : value; + if (value !== undefined && value !== null) return value; + if (arg?.type === 'number') return 0; + if (arg?.type === 'boolean') return false; + if (arg?.type === 'string') return ''; + return null; +}; + +export const pack = { id: APP, title: 'CyberChef' }; + +export const tools = [ + { + name: 'cyberchef.bake', + purpose: 'Run a CyberChef recipe of operations on some input text and return the result.', + when: 'Use when the user wants to encode, decode, hash, cipher or otherwise transform text.', + params: { + recipe: { type: 'text', required: true, description: 'Comma-separated operation names, underscores for spaces: "To_Base64" or "From_Hex,To_Upper_case"' }, + input: { type: 'text', description: 'The text to run through the recipe; empty when the operation makes its own input' }, + }, + effect: 'change', + needs: NEEDS, + examples: [ + { args: { recipe: 'To_Base64', input: 'hello world' }, says: 'Base64 encode this' }, + { args: { recipe: 'From_Hex,To_Upper_case', input: '48656c6c6f' }, says: 'Decode the hex and uppercase it' }, + ], + // The main-thread app.bake() is fire-and-forget, so bake through the background chef worker + // (app.manager.background.bake(input, recipeConfig, options, progress, step, callback)): + // recipeConfig is an array of {op, args} (the Flow _parseConfig shape, grep marker + // key:"_parseConfig"); options.returnType 1 is DishType.STRING (grep marker I.STRING=1) so the + // result comes back as text; the worker answers bakeComplete {dish, result, type, ...} or + // bakeError {error}, both delivered to the callback + run: async (args, ctx) => call(ctx, async host => { + const app = await getApi(host, ctx); + const names = parseRecipe(args.recipe); + const known = Object.keys(app.operations); + const ops = []; + const bad = []; + // Hash aliases: SHA256, SHA-256 or SHA_256 (case-insensitive; 224, 384, 512 likewise) are + // not operations - they bake the SHA2 operation with its Size arg at that size. MD5 and + // SHA1 are their own operations and are never aliased. + for (const name of names) { + const alias = name.match(/^SHA[\s_-]?(224|256|384|512)$/i); + const opName = alias ? 'SHA2' : name; + if (!known.includes(opName)) { bad.push(name); continue; } + // Fill each arg from the operation's defaults so the op runs as if added via the UI; an + // alias overrides only the SHA2 Size arg (UNVERIFIED arg layout: Size first, then two + // Rounds args - read from the vendored v11.5.0 definition, the lead bakes "abc" live). + ops.push({ op: opName, args: (app.operations[opName].args ?? []).map(arg => alias && arg.name === 'Size' ? alias[1] : defaultArg(arg)) }); + } + if (bad.length) { + const close = [...new Set(bad.flatMap(name => closest(name, known, 3)))]; + throw new ToolError('invalid_argument', `unknown operation(s) ${bad.join(', ')}${close.length ? `; closest: ${close.join(', ')}` : ''}`, ''); + } + const worker = app.manager?.background; + if (!worker?.chefWorker) throw new ToolError('not_available', 'the CyberChef bake worker is not ready; try again shortly', ''); + const out = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new ToolError('app_error', 'the recipe did not finish in time', '')), ctx.timeoutMs ?? 30000); + worker.bake(String(args.input ?? ''), ops, { returnType: 1 }, 0, false, (data) => { + clearTimeout(timer); + if (data?.error) { + const err = data.error; + const message = typeof err === 'string' ? err : err?.displayStr ?? err?.message ?? 'the recipe failed'; + reject(new ToolError('app_error', String(message), '')); + } else resolve({ output: data?.result, type: data?.type, ops: names }); + }); + }); + return out; + }), + }, + { + name: 'cyberchef.list_operations', + purpose: 'List the CyberChef operations available, filtered by a name substring.', + when: 'Use when the user asks what CyberChef can do, or to find the right operation name.', + params: { query: { type: 'string', description: 'Substring to match operation names against (case-insensitive); every operation when omitted' } }, + effect: 'read', + needs: NEEDS, + examples: [ + { args: { query: 'base64' }, says: 'What base64 operations are there?' }, + { args: { query: 'hash' }, says: 'Find the hashing operations' }, + ], + // app.operations is the registry keyed by operation name (main.js key:"filterOperations" iterates + // it; the wrapper reads .description/.args and Flow reads .module, grep markers key:"filterOperations" + // and key:"_parseConfig"); trimmed to the fields the model can act on, top 10 + run: async (args, ctx) => call(ctx, async host => { + const app = await getApi(host, ctx); + const needle = String(args.query ?? '').toLowerCase(); + const rows = Object.keys(app.operations) + .filter(name => needle === '' || name.toLowerCase().includes(needle)) + .slice(0, 10) + .map(name => { + const def = app.operations[name]; + return { name, module: def?.module, args: (def?.args ?? []).map(arg => arg.name), description: brief(def?.description) }; + }); + return { count: rows.length, operations: rows }; + }), + }, +]; diff --git a/agent/apps/deckcraft/skills.md b/agent/apps/deckcraft/skills.md new file mode 100644 index 0000000..1086917 --- /dev/null +++ b/agent/apps/deckcraft/skills.md @@ -0,0 +1,136 @@ +## Start a new presentation +slug: start-a-new-presentation +summary: Start a new themed or blank presentation, then add the first slides. +keywords: new presentation, new deck, start, theme, blank, slides +tools: desktop.open_app, deckcraft.new_presentation, deckcraft.add_slide, deckcraft.inspect + +When: the user wants a new presentation or deck to start building. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.new_presentation theme=Harbor +3. call_tool tool=deckcraft.add_slide layout=titleAndContent title=Q1 Plan +Check: deckcraft.inspect lists the new slides. +Gotchas: new_presentation replaces the open presentation (destructive), so ask the user first when it has unsaved work; change theme= and the slide layout and title. + +## Build a slide with text and a shape +slug: build-a-slide +summary: Add a slide, then fill it with a text box and a colored shape. +keywords: slide, build, text box, shape, layout, fill, heading +tools: desktop.open_app, deckcraft.add_slide, deckcraft.add_text_box, deckcraft.add_shape + +When: the user wants a slide built with a heading and a visual element. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.add_slide layout=titleAndContent title=Q1 Plan +3. call_tool tool=deckcraft.add_text_box x=40 y=260 w=500 text=Key numbers size=24 +4. call_tool tool=deckcraft.add_shape preset=rect x=40 y=420 w=300 h=80 fill=#3B5BDB +Check: deckcraft.inspect_slide shows the shapes with their ids. +Gotchas: change the coordinates and text; add_shape fills with fill= and outlines with line= (line=none removes the outline). + +## Change text on a slide +slug: change-slide-text +summary: Read a slide, find the shape id, and replace its text. +keywords: change text, edit text, replace, shape text, title +tools: desktop.open_app, deckcraft.inspect_slide, deckcraft.set_text + +When: the user wants to change the text of a shape or the title on a slide. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.inspect_slide index=0 +3. call_tool tool=deckcraft.set_text id=7 text=Updated title +Check: deckcraft.inspect_slide shows the new text on the shape. +Gotchas: set_text takes the shape id from inspect_slide; leading tabs in text= set bullet levels. + +## Add a table to a slide +slug: add-a-table +summary: Insert a table with rows and columns, filled with cell text. +keywords: table, grid, rows, columns, data, spreadsheet +tools: desktop.open_app, deckcraft.insert_table + +When: the user wants a table of values on a slide. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.insert_table rows=3 cols=2 data=[["Item","Cost"],["Rent","1200"],["Food","400"]] +Check: deckcraft.inspect_slide lists the table on the current slide. +Gotchas: change rows= and cols=; data= rows must match cols; x, y, w, h place the table when all four are given. + +## Add a chart to a slide +slug: add-a-chart +summary: Insert a chart with categories and one or more series. +keywords: chart, graph, plot, column, pie, data +tools: desktop.open_app, deckcraft.insert_chart + +When: the user wants a chart or graph on a slide. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.insert_chart type=column title=Sales categories=Q1, Q2 series=[["Sales",12,18]] +Check: deckcraft.inspect_slide lists the chart on the current slide. +Gotchas: change type= (column, bar, line, pie, doughnut, area, scatter, stackedColumn); each series row is the name then its values. + +## Select and format shapes +slug: select-and-format-shapes +summary: Select shapes by id and press the formatting shortcuts. +keywords: select, shape, format, bold, shortcut, style +tools: desktop.open_app, deckcraft.inspect_slide, deckcraft.select, deckcraft.key + +When: the user wants to select shapes and apply a formatting shortcut. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.inspect_slide +3. call_tool tool=deckcraft.select ids=3, 4 +4. call_tool tool=deckcraft.key key=B cmd=true +Check: deckcraft.inspect_slide shows the new formatting on the shapes. +Gotchas: ids= comes from inspect_slide; key= is a letter or name with shift, alt, cmd, ctrl modifiers. + +## Find and run any menu command +slug: run-any-menu-command +summary: Look up a ribbon or menu command by name, then run it with parameters. +keywords: menu, ribbon, command, run action, toolbar, what can it do +tools: desktop.open_app, deckcraft.list_commands, deckcraft.run_command + +When: the user wants a ribbon or menu action that has no dedicated tool. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.list_commands query=format +3. call_tool tool=deckcraft.run_command command=format.bold params=ids=3 +Check: deckcraft.inspect_slide shows the action took effect. +Gotchas: run_command takes key=value lines in params=; ids starting with file.new, file.close or slide.delete are destructive, so ask the user first. + +## Do several slide edits at once +slug: do-several-slide-edits +summary: Run several slide commands in order in one batch call. +keywords: batch, several, at once, multiple edits, sequence +tools: desktop.open_app, deckcraft.batch + +When: the user wants several slide changes applied in one go. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.batch commands="slide.new layout=title title=Q1, go_to_slide index=1" +Check: deckcraft.inspect lists the new slide and the current one. +Gotchas: each batch item is the command id then key=value tokens without spaces in values; keepGoing=true continues past a failing step. + +## Open a presentation from Files +slug: open-a-presentation-from-files +summary: Open a presentation that is stored in Files in DeckCraft. +keywords: open, load, from files, deck, pptx, presentation +tools: desktop.open_app, deckcraft.open_file + +When: the user wants to open a presentation that is stored in Files. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.open_file path=/DeckCraft/talk.pptx +Check: the result's opened field names the deck and its slide count; deckcraft.inspect shows the opened presentation. +Gotchas: change path= to the Files path of a deck (.deckcraft, .pptx, .potx, .ppsx, or an outline); the deck opens alongside the open ones; while the open deck has unsaved changes the app asks first whether to keep them. + +## Save a copy of the deck to Files +slug: save-a-deck-copy-to-files +summary: Save the active presentation as a file in Files. +keywords: save, copy, to files, export, keep, pptx, write +tools: desktop.open_app, deckcraft.save_copy + +When: the user wants to keep a copy of the active presentation in Files. +Steps: +1. call_tool tool=desktop.open_app app=deckcraft +2. call_tool tool=deckcraft.save_copy path=/DeckCraft/talk.deckcraft +Check: the result has the saved Files path and size; files.info on that path shows the same size. +Gotchas: change path=; DeckCraft saves its own .deckcraft format, so a .pptx (or other) target is refused with the .deckcraft path as the fix; if the path exists the tool errors, so choose another name or pass overwrite=true (which is destructive); when the app saves through the capture path it also downloads the file, and the result says so. diff --git a/agent/apps/deckcraft/tools.js b/agent/apps/deckcraft/tools.js new file mode 100644 index 0000000..042687f --- /dev/null +++ b/agent/apps/deckcraft/tools.js @@ -0,0 +1,431 @@ +// Ported from storytold/deckcraft@v0.18.1 crates/mcp/src/tools.rs (MIT OR Apache-2.0). Tool names, descriptions and the control-method mapping follow that table; arguments are flattened for small models. +// The tools run in Buddy's frame and drive the DeckCraft page API through ctx.craft, +// which the runtime wires as id => craftApi(await ctx.host.appWindow(id), id) (plan 9). +import { ToolError, callLine, closest } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { filesCall, openAndAwait, readOpenFile, saveBytesCopy } from '../../shared/craft-files.js'; +import { releases } from '../../../scripts/pc/craft/releases.mjs'; + +const APP = 'deckcraft'; +const NEEDS = ['host', 'app:deckcraft']; +// run_command/batch ids that destroy or replace data: effectFor marks those calls +// destructive. file.new replaces the open presentation (the web app holds one document). +const DESTRUCTIVE = ['file.new', 'file.close', 'slide.delete']; + +/** tools.rs pick(): copy the listed keys (when present) into a params object. */ +const pick = (args, keys) => { + const out = {}; + for (const key of keys) if (args[key] !== undefined) out[key] = args[key]; + return out; +}; + +// key=value coercion: booleans and numbers, everything else a string. +const coerce = raw => (/^(true|false)$/i.test(raw) ? raw.toLowerCase() === 'true' : /^-?\d+(\.\d+)?$/.test(raw) ? Number(raw) : raw); + +// run_command params: key=value lines -> object (plan 9, the generic long-tail tool). +const parseParams = text => { + const out = {}; + for (const line of String(text ?? '').split('\n')) { + const row = line.trim(); + if (!row) continue; + const eq = row.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad params line "${row}": use key=value`, ''); + out[row.slice(0, eq).trim()] = coerce(row.slice(eq + 1).trim()); + } + return out; +}; + +// A batch step "id k=v k2=v2": the id, then space-separated key=value tokens (no spaces in values). +const parseStep = line => { + const text = String(line ?? '').trim(); + const out = { command: '', params: {} }; + if (!text) return null; + const sp = text.indexOf(' '); + out.command = sp < 0 ? text : text.slice(0, sp); + for (const token of sp < 0 ? [] : text.slice(sp + 1).split(/\s+/)) { + const eq = token.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad batch step "${text}": params are key=value tokens`, ''); + out.params[token.slice(0, eq)] = coerce(token.slice(eq + 1)); + } + return out; +}; + +// tools.rs add_shape/add_text_box: follow-up calls that fail do not fail the tool. +const silently = promise => promise.catch(() => {}); + +export const pack = { id: APP, title: 'DeckCraft' }; + +export const tools = [ + { + name: 'deckcraft.inspect', + purpose: 'Show the open presentation: slides, sections, theme, selection.', + when: 'Use when the user asks what is in the deck, or before planning slide changes.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What does this presentation contain?' }], + // tools.rs:399 document.inspect + run: async (args, ctx) => (await ctx.craft(APP)).inspect(), + }, + { + name: 'deckcraft.inspect_slide', + purpose: 'Show one slide: shapes with ids, text, tables, charts, notes.', + when: 'Use when the user asks about one slide, or before changing its shapes.', + params: { index: { type: 'integer', description: 'Slide index; the current slide when omitted' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { index: 1 }, says: 'What is on the second slide?' }], + // tools.rs:400 slide.inspect + run: async (args, ctx) => (await ctx.craft(APP)).execute('slide.inspect', pick(args, ['index'])), + }, + { + name: 'deckcraft.new_presentation', + purpose: 'Start a new presentation with one title slide.', + when: 'Use when the user wants a blank or themed deck to start from.', + params: { + theme: { type: 'string', description: 'Theme name: DeckCraft, Harbor, Ember, Meadow, Nocturne, Paper, Coral Reef or Slate' }, + blank: { type: 'boolean', description: 'No first slide' }, + }, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: { theme: 'Harbor' }, says: 'Start a new deck with the Harbor theme' }], + // tools.rs:395 file.new. Destructive: the web app holds one presentation, so this replaces the open one. + run: async (args, ctx) => (await ctx.craft(APP)).execute('file.new', pick(args, ['theme', 'blank'])), + }, + { + name: 'deckcraft.add_slide', + purpose: 'Add a slide after the current one with a layout and text.', + when: 'Use when the user wants a new slide in the deck.', + params: { + layout: { type: 'string', description: 'Layout name or kind, e.g. title, titleAndContent, sectionHeader, blank' }, + title: { type: 'string', description: 'Title text' }, + body: { type: 'string', description: 'Body text, one paragraph per line; leading tabs indent' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { layout: 'titleAndContent', title: 'Q1 Plan' }, says: 'Add a slide titled Q1 Plan' }], + // tools.rs:410 slide.new + run: async (args, ctx) => (await ctx.craft(APP)).execute('slide.new', pick(args, ['layout', 'title', 'body'])), + }, + { + name: 'deckcraft.go_to_slide', + purpose: 'Make a slide current; shape commands act on the current slide.', + when: 'Use when the user wants to jump to or work on a specific slide.', + params: { index: { type: 'integer', required: true, description: 'Slide index' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { index: 2 }, says: 'Go to the third slide' }], + // tools.rs:411 slide.go + run: async (args, ctx) => (await ctx.craft(APP)).execute('slide.go', pick(args, ['index'])), + }, + { + name: 'deckcraft.add_shape', + purpose: 'Insert a preset shape with size, text and colors.', + when: 'Use when the user wants a shape: rectangle, ellipse, arrow, star, line.', + params: { + preset: { type: 'string', required: true, description: 'Preset name: rect, roundRect, ellipse, triangle, diamond, rightArrow, chevron, star5, heart, cloud, line' }, + x: { type: 'number', required: true, description: 'Left, in points' }, + y: { type: 'number', required: true, description: 'Top, in points' }, + w: { type: 'number', required: true, description: 'Width, in points' }, + h: { type: 'number', required: true, description: 'Height, in points' }, + text: { type: 'string', description: 'Text inside the shape' }, + fill: { type: 'string', description: 'Fill color #RRGGBB or accent1..6' }, + line: { type: 'string', description: 'Outline color #RRGGBB, or none' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { preset: 'rect', x: 40, y: 100, w: 300, h: 120, fill: '#3B5BDB' }, says: 'Add a blue box near the top left' }], + // tools.rs:412-432 shape.insert, then optional shape.fill and shape.line on the new id + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const result = await app.execute('shape.insert', pick({ preset: args.preset, rect: [args.x, args.y, args.w, args.h], text: args.text }, ['preset', 'rect', 'text'])); + if (args.fill !== undefined) await app.execute('shape.fill', { id: result.id, color: args.fill }); + if (args.line !== undefined) await app.execute('shape.line', args.line === 'none' ? { id: result.id, none: true } : { id: result.id, color: args.line }); + return result; + }, + }, + { + name: 'deckcraft.add_text_box', + purpose: 'Insert a text box with optional size, color and alignment.', + when: 'Use when the user wants free text on a slide.', + params: { + x: { type: 'number', required: true, description: 'Left, in points' }, + y: { type: 'number', required: true, description: 'Top, in points' }, + w: { type: 'number', required: true, description: 'Width, in points' }, + text: { type: 'string', required: true, description: 'Text, one paragraph per line' }, + h: { type: 'number', description: 'Height in points; 30 when omitted' }, + size: { type: 'number', description: 'Font size, in points' }, + color: { type: 'string', description: 'Text color #RRGGBB or a name' }, + align: { type: 'enum', values: ['left', 'center', 'right', 'justify'], description: 'Alignment' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { x: 40, y: 260, w: 500, text: 'Key numbers', size: 24, align: 'left' }, says: 'Add a heading text box' }], + // tools.rs:433-450 insert.textBox, then text.exit, edit.select and the format.* calls + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const result = await app.execute('insert.textBox', { rect: [args.x, args.y, args.w, args.h ?? 30], text: args.text }); + const id = result.id; + await silently(app.execute('text.exit', {})); + await silently(app.execute('edit.select', { ids: [id] })); + if (args.size !== undefined) await silently(app.execute('format.size', { size: args.size })); + if (args.color !== undefined) await silently(app.execute('format.color', { color: args.color })); + if (args.align !== undefined) await silently(app.execute('format.align', { align: args.align })); + return result; + }, + }, + { + name: 'deckcraft.set_text', + purpose: "Replace a shape's text, keeping its first run's formatting.", + when: 'Use when the user wants to change the text of a shape on the current slide.', + params: { + id: { type: 'integer', required: true, description: 'Shape id from deckcraft.inspect_slide' }, + text: { type: 'string', required: true, description: 'New text; leading tabs set bullet levels' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { id: 7, text: 'Updated title' }, says: 'Change the title text' }], + // tools.rs:451 text.set + run: async (args, ctx) => (await ctx.craft(APP)).execute('text.set', pick(args, ['id', 'text'])), + }, + { + name: 'deckcraft.insert_table', + purpose: 'Insert a table with rows and columns, optionally filled.', + when: 'Use when the user wants a table on the slide.', + params: { + rows: { type: 'integer', required: true, description: 'Rows' }, + cols: { type: 'integer', required: true, description: 'Columns' }, + data: { type: 'table', description: 'Rows of cell text' }, + x: { type: 'number', description: 'Left (pt); all four set the box' }, + y: { type: 'number', description: 'Top (pt)' }, + w: { type: 'number', description: 'Width (pt)' }, + h: { type: 'number', description: 'Height (pt)' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { rows: 3, cols: 2, data: [['Item', 'Cost'], ['Rent', '1200'], ['Food', '400']] }, says: 'Add a small cost table' }], + // tools.rs:459-465 insert.table; rect is sent only when all four box values are given + run: async (args, ctx) => { + const params = pick(args, ['rows', 'cols', 'data']); + if ([args.x, args.y, args.w, args.h].every(value => value !== undefined)) params.rect = [args.x, args.y, args.w, args.h]; + return (await ctx.craft(APP)).execute('insert.table', params); + }, + }, + { + name: 'deckcraft.insert_chart', + purpose: 'Insert a chart with categories and series.', + when: 'Use when the user wants a chart, graph or plot on the slide.', + params: { + type: { type: 'string', description: 'Chart type: column, bar, line, pie, doughnut, area, scatter, stackedColumn' }, + title: { type: 'string', description: 'Chart title' }, + categories: { type: 'list', description: 'Category names, e.g. Q1, Q2' }, + series: { type: 'table', description: 'Series as rows: [name, value, value, ...]' }, + x: { type: 'number', description: 'Left (pt); all four set the box' }, + y: { type: 'number', description: 'Top (pt)' }, + w: { type: 'number', description: 'Width (pt)' }, + h: { type: 'number', description: 'Height (pt)' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { type: 'column', title: 'Sales', categories: ['Q1', 'Q2'], series: [['Sales', 12, 18]] }, says: 'Add a column chart of sales' }], + // tools.rs:466-472 insert.chart; series rows [name, values...] become {name, values} + run: async (args, ctx) => { + const params = pick(args, ['type', 'title', 'categories']); + if (args.series !== undefined) params.series = args.series.map(row => ({ name: row[0], values: row.slice(1) })); + if ([args.x, args.y, args.w, args.h].every(value => value !== undefined)) params.rect = [args.x, args.y, args.w, args.h]; + return (await ctx.craft(APP)).execute('insert.chart', params); + }, + }, + { + name: 'deckcraft.select', + purpose: 'Select shapes by id; formatting commands then act on them.', + when: 'Use when the user wants to select shapes before formatting or moving them.', + params: { ids: { type: 'list', required: true, description: 'Shape ids from deckcraft.inspect_slide' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { ids: [3, 4] }, says: 'Select those two shapes' }], + // tools.rs:473 edit.select; ids arrive as strings from flat calls, the engine wants numbers + run: async (args, ctx) => { + const ids = args.ids.map(value => { + const n = Number(value); + if (!Number.isFinite(n)) throw new ToolError('invalid_argument', `ids must be numbers, got "${value}"`, ''); + return n; + }); + return (await ctx.craft(APP)).execute('edit.select', { ids }); + }, }, + { + name: 'deckcraft.select_tool', + purpose: 'Pick the pointer tool: select, textBox, shape, pen, highlighter, eraser.', + when: 'Use when the user wants the app to switch to a drawing or editing tool.', + params: { + tool: { type: 'string', required: true, description: 'Tool name: select, textBox, shape, pen, highlighter, eraser, or a preset name' }, + preset: { type: 'string', description: 'Shape preset for the shape tool' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { tool: 'shape', preset: 'ellipse' }, says: 'Switch to the shape tool for ellipses' }], + // tools.rs:475 ui.tool.select + run: async (args, ctx) => (await ctx.craft(APP)).request('ui.tool.select', pick(args, ['tool', 'preset'])), + }, + { + name: 'deckcraft.key', + purpose: 'Press a key: editing keys, nudges and shortcuts like cmd+b.', + when: 'Use when the user wants a keyboard shortcut or nudge in the deck.', + params: { + key: { type: 'string', required: true, description: 'Key name or character, e.g. Enter, Backspace, B' }, + shift: { type: 'boolean', description: 'Shift held' }, + alt: { type: 'boolean', description: 'Alt/Option held' }, + cmd: { type: 'boolean', description: 'Cmd/Ctrl held' }, + ctrl: { type: 'boolean', description: 'Ctrl held (the Control key on macOS)' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { key: 'B', cmd: true }, says: 'Bold the selection with the shortcut' }], + // tools.rs:476-480 ui.key with the mods object plus key + run: async (args, ctx) => (await ctx.craft(APP)).request('ui.key', { key: args.key, ...pick(args, ['shift', 'alt', 'cmd', 'ctrl']) }), + }, + { + name: 'deckcraft.type_text', + purpose: 'Type text into the text being edited or the selected shape.', + when: 'Use when the user wants to type into an active text box.', + params: { text: { type: 'string', required: true, description: 'Text to type' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { text: 'Hello' }, says: 'Type Hello into the text box' }], + // tools.rs:481 ui.text + run: async (args, ctx) => (await ctx.craft(APP)).request('ui.text', pick(args, ['text'])), + }, + { + name: 'deckcraft.batch', + purpose: 'Run several commands in order; stops at the first error.', + when: 'Use when several slide edits should happen in one go.', + params: { + commands: { type: 'list', required: true, description: 'One command per item: the id then key=value params, e.g. slide.new layout=title title=Q1' }, + keepGoing: { type: 'boolean', description: 'Continue after errors' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(id => (args.commands ?? []).some(line => String(line ?? '').trim().startsWith(id))) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { commands: ['slide.new layout=title title=Q1', 'go_to_slide index=1'] }, says: 'Add a slide and jump to it' }], + // tools.rs:359-394: one engine.execute per step, in order, stop on error unless keepGoing + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const out = []; + for (const line of args.commands) { + const step = parseStep(line); + if (!step) continue; + const entry = { command: step.command, ok: true, result: null, error: null }; + try { + entry.result = await app.execute(step.command, step.params); + } catch (error) { + entry.ok = false; + entry.error = error instanceof Error ? error.message : String(error); + } + out.push(entry); + if (!entry.ok && !args.keepGoing) break; + } + return out; + }, + }, + { + name: 'deckcraft.list_commands', + purpose: 'Find deck menu commands by a word in their name.', + when: 'Use when the user wants a ribbon or menu action and its command id is unknown.', + params: { query: { type: 'string', description: 'Substring of the command id or label; omit to list the first 10' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { query: 'transition' }, says: 'Which commands set transitions?' }], + // Generic tool (plan 9): the top 10 of the live commands() by case-insensitive match + run: async (args, ctx) => { + const all = await (await ctx.craft(APP)).commands(); + const q = String(args.query ?? '').trim().toLowerCase(); + return all.filter(command => !q || [command.id, command.label].some(part => String(part ?? '').toLowerCase().includes(q))) + .slice(0, 10).map(command => ({ id: command.id, label: command.label, menu: command.menu, params: command.params })); + }, + }, + { + name: 'deckcraft.run_command', + purpose: 'Run any DeckCraft menu command by id with parameters.', + when: `Use when a menu action is wanted by id; ${DESTRUCTIVE.join(', ')} are destructive, so ask first.`, + params: { + command: { type: 'string', required: true, description: 'Command id from deckcraft.list_commands, e.g. slide.new or format.bold' }, + params: { type: 'text', description: 'Parameters as key=value lines, one per line; omit for the defaults' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(prefix => String(args.command ?? '').startsWith(prefix)) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { command: 'format.bold', params: 'ids=3' }, says: 'Bold the selected shape' }], + // Generic tool (plan 9): unknown ids get invalid_argument with the 3 closest ids + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const all = await app.commands(); + if (!all.some(command => command.id === args.command)) { + const near = closest(args.command, all.map(command => command.id), 3); + const fix = near.length > 0 ? callLine('deckcraft.run_command', { command: near[0] }) : ''; + throw new ToolError('invalid_argument', `unknown command "${args.command}"${near.length > 0 ? `; closest: ${near.join(', ')}` : ''}`, fix); + } + return app.execute(args.command, parseParams(args.params)); + }, + }, + { + name: 'deckcraft.open_file', + purpose: 'Open a presentation from Files in DeckCraft.', + when: 'Use when the user wants to open a deck stored in Files. Not for opening the app itself; that is desktop.open_app.', + params: { path: { type: 'path', required: false, description: 'A Files path to a deck file (.deckcraft or a .txt/.md outline)' } }, + effect: 'change', + needs: ['host', 'app:deckcraft', 'files'], + examples: [{ args: { path: '/DeckCraft/talk.pptx' }, says: 'Open the talk deck from Files' }], + // Drives the wrapper's own #file input (app.mjs:38), so the open posts from the wrapper + // realm, as the app's host bridge requires (craft-libs web-host web.rs:106). The deck opens + // via file.adopt alongside the open ones (engine cmd/file.rs add_opened), so a change; the + // wrapper's own unsaved-changes confirm still applies (app.mjs:35). openAndAwait waits + // until the app's inspect changes, so the result confirms the deck actually loaded. + run: async (args, ctx) => { + const file = await readOpenFile(ctx, args.path, { id: APP, title: 'DeckCraft' }); + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + return openAndAwait(craft, { id: APP, title: 'DeckCraft', wrapperWindow: wrapper, name: file.name, bytes: file.bytes, accept: releases[APP].accept }); + }, + }, + { + name: 'deckcraft.save_copy', + purpose: 'Save the active presentation as a file in Files.', + when: 'Use when the user wants to keep a copy of the presentation in Files.', + params: { + path: { type: 'path', required: true, description: 'The Files path to write the copy to, e.g. /DeckCraft/talk.pptx' }, + overwrite: { type: 'boolean', description: 'Replace the file when the path already exists; false when omitted' }, + }, + effect: 'change', + effectFor: args => (args.overwrite ? 'destructive' : 'change'), + needs: ['host', 'app:deckcraft', 'files'], + examples: [{ args: { path: '/DeckCraft/talk.pptx' }, says: 'Save a copy of the deck to Files' }], + // No path is ever passed (the browser has no file system). saveBytesCopy takes the bytes + // inline from file.saveBytes when the live command list has it (no download), else from + // the no-path file.save the wrapper captures as deckcraft:save (app.mjs:29-33); in that + // case the wrapper also downloads the file, and the result says so. The bytes are the + // deck in its own .deckcraft format, so a .pptx (or other) target is refused with a fix. + run: async (args, ctx) => { + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + const save = await saveBytesCopy(craft, { + id: APP, title: 'DeckCraft', wrapperWindow: wrapper, target: args.path, + tool: 'deckcraft.save_copy', nativeExt: '.deckcraft', + }); + const written = await filesCall( + ctx, + files => files.writeBytes(args.path, save.bytes, { overwrite: Boolean(args.overwrite) }), + error => (error.code === 'exists' ? callLine('deckcraft.save_copy', { path: args.path, overwrite: true }) : ''), + ); + return { path: written.path, name: save.name, size: written.size, created: written.created, ...(save.note ? { note: save.note } : {}) }; + }, + }, +]; + +// Live-check exports (brief): every command id the curated tools pass to execute, +// and every control method passed to request. batch and run_command also pass +// arbitrary ids from the live commands() list. +export const usesCommands = [ + 'file.new', 'file.save', 'file.saveBytes', 'slide.inspect', 'slide.new', 'slide.go', 'shape.insert', 'shape.fill', 'shape.line', + 'insert.textBox', 'text.exit', 'edit.select', 'format.size', 'format.color', 'format.align', + 'text.set', 'insert.table', 'insert.chart', +]; +export const usesMethods = ['ui.tool.select', 'ui.key', 'ui.text']; diff --git a/agent/apps/docs/skills.md b/agent/apps/docs/skills.md new file mode 100644 index 0000000..e53ac12 --- /dev/null +++ b/agent/apps/docs/skills.md @@ -0,0 +1,77 @@ +## Read the document +slug: read-the-document +summary: Read the document text with a stable paraId per paragraph for follow-up edits. +keywords: read, show, what is in, document, text, content, document text +tools: desktop.open_app, docs.get_text + +When: the user asks what is in the document, or before planning an edit. +Steps: +1. call_tool tool=desktop.open_app app=docs +2. call_tool tool=docs.get_text +Check: the result has the text and each paragraph with its paraId. +Gotchas: each paragraph carries a stable paraId the edit tools take as para_id; the read reflects the live editor state, so it is fresh right after an edit. + +## Type a paragraph +slug: type-a-paragraph +summary: Insert a new paragraph at the cursor, after a named paragraph, or at the end. +keywords: type, add, insert, paragraph, text, append, write into +tools: desktop.open_app, docs.insert_text + +When: the user wants to add or type a paragraph of text into the document. +Steps: +1. call_tool tool=desktop.open_app app=docs +2. call_tool tool=docs.insert_text text=Second draft notes +Check: docs.get_text shows the new paragraph. +Gotchas: change text=; with no para_id it goes at the cursor or the document end; the insert is applied as accepted text, not a pending suggestion. + +## Make a heading +slug: make-a-heading +summary: Turn a paragraph into a heading of a given level. +keywords: heading, title, subheading, level, make bold heading, format line +tools: desktop.open_app, docs.set_heading + +When: the user wants a line to become a heading, or to change a heading level. +Steps: +1. call_tool tool=desktop.open_app app=docs +2. call_tool tool=docs.set_heading level=1 +Check: docs.get_text shows the paragraph with the Heading style. +Gotchas: change level=; with no para_id it targets the paragraph at the cursor, so ask the user to click into the line first if needed. + +## Find and replace +slug: find-and-replace +summary: Replace occurrences of a phrase across the document; the edits are applied in place. +keywords: find, replace, find and replace, rename word, swap, change every, change it to, instead +tools: desktop.open_app, docs.find_replace + +When: the user wants find and replace across the document. +Steps: +1. call_tool tool=desktop.open_app app=docs +2. call_tool tool=docs.find_replace find=draft replace=final +Check: the result counts the replacements applied. +Gotchas: change find= and replace=; a replace= with no text deletes the phrase; limit= caps how many matches are touched. changing a word in existing text needs docs.find_replace, not docs.insert_text, which only inserts a new paragraph. + +## Bold the selection +slug: bold-the-selection +summary: Bold the current selection, or the whole paragraph under the cursor. +keywords: bold, emphasize, make bold, highlight text, strong +tools: desktop.open_app, docs.bold_selection + +When: the user wants the selected text, or the line under the cursor, made bold. +Steps: +1. call_tool tool=desktop.open_app app=docs +2. call_tool tool=docs.bold_selection +Check: docs.get_text shows the paragraph; ask the user to confirm the bold is where they wanted it. +Gotchas: the user must have a cursor or selection in the document first, so ask them to click into the text if the call reports no selection. + +## Start a new document +slug: start-a-new-document +summary: Replace the document with a fresh one; the current content is lost. +keywords: new document, blank document, start over, fresh doc, clear document +tools: desktop.open_app, docs.new + +When: the user wants to start over with a new document. +Steps: +1. call_tool tool=desktop.open_app app=docs +2. call_tool tool=docs.new +Check: docs.get_text shows the new empty document. +Gotchas: this is destructive and keeps no recover-previous copy, so ask the user to confirm first and offer to export or read the old text first. diff --git a/agent/apps/docs/tools.js b/agent/apps/docs/tools.js new file mode 100644 index 0000000..bacb09d --- /dev/null +++ b/agent/apps/docs/tools.js @@ -0,0 +1,237 @@ +// Docs pack: the Docs app tools (read, insert, heading, find/replace, bold, new document). +// Every tool drives the editor instance the app exposes as window.webpcDocs +// (scripts/pc/docs/editor.jsx:105), a @casualoffice/docs DocxEditorRef (dist/react-ltZBBRVr.d.ts:1215). +// The app autosaves to localStorage on every change (editor.jsx onChange -> save()), so there is +// no save tool: edits are persisted as they happen. +import { ToolError } from '../../../src/apps/ai-agent/runtime/args.mjs'; + +const APP = 'docs'; +const NEEDS = ['host', 'app:docs']; +const AUTHOR = 'Buddy'; +const NOT_HERE = 'Docs is not available here (Buddy is not running inside WebPC).'; + +// Gate on ctx.host (needs: ['host', 'app:docs']), then turn host rejections, which carry a code +// (unknown_app, not_open, not_iframe, timeout, invalid_argument), into a ToolError. +const call = (ctx, fn) => { + if (!ctx.host) throw new ToolError('not_available', NOT_HERE, ''); + return Promise.resolve() + .then(() => fn(ctx.host)) + .catch(error => { + if (error instanceof ToolError) throw error; + throw new ToolError(error.code || 'app_error', error.message, ''); + }); +}; + +// window.webpcDocs is set when the DocxEditor ref mounts; appWindow only resolves once the app +// posted pc:ready (after the mount), so this guards the edge. +const editor = win => { + const ed = win.webpcDocs; + if (!ed) throw Object.assign(new Error('the Docs editor is not ready yet; try again shortly'), { code: 'not_available' }); + return ed; +}; + +// The paraId of the last text paragraph in the live ProseMirror state (the document end), or +// null. Reads the fresh state (getEditorRef().getState().doc), not the stale paged view. +const endParaId = ed => { + const doc = ed.getEditorRef?.()?.getState?.()?.doc; + if (!doc) return null; + let last = null; + doc.descendants(node => { if (node.isTextblock) last = node.attrs?.paraId ?? null; }); + return last; +}; + +// A fresh document is one empty paragraph with no paraId yet (live probe: size 0, paraId null), +// which insertParagraphAfter cannot address. Type the text into that paragraph on the live view +// (getEditorRef().getView(), the same view find_replace edits). False when the last paragraph has text. +const typeIntoEmpty = (ed, text) => { + const view = ed.getEditorRef?.()?.getView?.(); + let last = null; + view?.state?.doc?.descendants((node, pos) => { if (node.isTextblock) last = { node, pos }; }); + if (!last || last.node.content?.size !== 0) return false; + view.dispatch(view.state.tr.insertText(text, last.pos + 1)); + return true; +}; + +// insertParagraphAfter and proposeChange apply the insertion mark, so the new text is a pending +// tracked suggestion, not document text. Accept every tracked change with the editor's own +// "Accept all changes" command, which the UI runs as Zf()(view.state, view.dispatch) on the +// PagedEditorRef view (getEditorRef, react-ltZBBRVr.d.ts:1225; getView, d.ts PagedEditorRef), +// where Zf() = (state, dispatch) => Xw(0, state.doc.content.size, "accept")(state, dispatch). +// Xw removes the insertion mark from marked text and deletes deletion-marked ranges (in reverse +// position order), so the edit lands as accepted text docs.get_text can read back. +const acceptAllChanges = ed => { + const view = ed.getEditorRef?.()?.getView?.(); + const state = view?.state; + if (!state) return false; + const insertion = state.schema.marks.insertion; + const deletion = state.schema.marks.deletion; + if (!insertion && !deletion) return false; + const tr = state.tr; + const doomed = []; + state.doc.nodesBetween(0, state.doc.content.size, (node, pos) => { + if (!node.isText) return; + const from = pos; + const to = pos + node.nodeSize; + if (deletion && node.marks.some(mark => mark.type === deletion)) doomed.push({ from, to }); + if (insertion && node.marks.some(mark => mark.type === insertion)) tr.removeMark(from, to, insertion); + }); + for (const range of doomed.reverse()) tr.delete(range.from, range.to); + if (tr.steps.length === 0) return false; + view.dispatch(tr); + return true; +}; + +export const pack = { id: APP, title: 'Docs' }; + +export const tools = [ + { + name: 'docs.get_text', + purpose: 'Read the document text with a stable paraId per paragraph.', + when: 'Use when the user asks what is in the document, or before planning edits.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is in my document?' }], + // getPageContent (the paged view) lags behind edits and getDocument/getContent return a stale + // model, so read the live ProseMirror state: getEditorRef().getState().doc (react-ltZBBRVr.d.ts + // :1225/:662). Walk the text blocks and take each paragraph's stable paraId from the node attrs + // (Word w14:paraId) so the edit tools can target it. + run: async (args, ctx) => call(ctx, async host => { + const ed = editor(await host.appWindow(APP)); + const doc = ed.getEditorRef?.()?.getState?.()?.doc; + if (!doc) throw new ToolError('not_available', 'the Docs editor is not ready yet; try again shortly', ''); + const paragraphs = []; + doc.descendants(node => { if (node.isTextblock) paragraphs.push({ paraId: node.attrs?.paraId ?? null, text: node.textContent }); }); + return { text: paragraphs.map(p => p.text).join('\n'), paragraphs }; + }), + }, + { + name: 'docs.insert_text', + purpose: 'Insert a new paragraph after the cursor, after a paragraph, or at the end.', + when: 'Use when the user wants to add or type a paragraph of text into the document.', + params: { + text: { type: 'text', required: true, description: 'The paragraph text to insert' }, + para_id: { type: 'string', description: 'Insert after this paragraph (a paraId from docs.get_text); at the cursor or the document end when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { text: 'Second draft notes' }, says: 'Add a paragraph at the end' }, { args: { text: 'Intro', para_id: '1A2B3C4D' }, says: 'Put this after that paragraph' }], + // insertParagraphAfter (react-ltZBBRVr.d.ts:1407) applies the insertion mark, so the new + // paragraph is a pending tracked suggestion. Accept it right after (acceptAllChanges) so it + // lands as accepted document text that docs.get_text and docs.find_replace can read back. + run: async (args, ctx) => call(ctx, async host => { + const ed = editor(await host.appWindow(APP)); + const paraId = args.para_id ?? (ed.getSelection()?.paraId ?? await endParaId(ed)); + if (!paraId) { + if (!typeIntoEmpty(ed, args.text)) throw new ToolError('app_error', 'there is no paragraph to add after; read the paragraphs with docs.get_text and pass one as para_id', 'call_tool tool=docs.get_text'); + acceptAllChanges(ed); + return { insertedAfter: null, text: args.text }; + } + if (!ed.insertParagraphAfter({ paraId, text: args.text, author: AUTHOR })) throw new ToolError('app_error', `could not insert after paragraph ${paraId}`, ''); + acceptAllChanges(ed); + return { insertedAfter: paraId, text: args.text }; + }), + }, + { + name: 'docs.set_heading', + purpose: 'Turn a paragraph into a heading of a given level.', + when: 'Use when the user wants a line to become a heading, or to change its heading level.', + params: { + level: { type: 'integer', required: true, min: 1, max: 9, description: 'Heading level, 1 (largest) to 9' }, + para_id: { type: 'string', description: 'The paragraph (a paraId from docs.get_text); the paragraph at the cursor when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { level: 1 }, says: 'Make this line a top heading' }, { args: { level: 2, para_id: '1A2B3C4D' }, says: 'Make that paragraph a level-2 heading' }], + // DocxEditorRef.setParagraphStyle: styleId "HeadingN" (react-ltZBBRVr.d.ts:1341) + run: async (args, ctx) => call(ctx, async host => { + const ed = editor(await host.appWindow(APP)); + const paraId = args.para_id ?? ed.getSelection()?.paraId; + if (!paraId) throw new ToolError('invalid_argument', 'give para_id or put the cursor in the paragraph first', ''); + const styleId = `Heading${args.level}`; + if (!ed.setParagraphStyle({ paraId, styleId })) throw new ToolError('app_error', `could not set ${styleId} on paragraph ${paraId} (unknown paraId or missing style)`, ''); + return { paraId, styleId }; + }), + }, + { + name: 'docs.find_replace', + purpose: 'Replace occurrences of a phrase; the replacements are applied.', + when: 'Use when the user wants find and replace across the document.', + params: { + find: { type: 'string', required: true, description: 'The phrase to find (case-insensitive)' }, + replace: { type: 'string', required: true, description: 'The replacement text; empty deletes the phrase' }, + limit: { type: 'integer', min: 1, default: 50, description: 'At most this many matches' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { find: 'draft', replace: 'final' }, says: 'Replace draft with final everywhere' }], + // proposeChange plus accept-all inserts at the paragraph level and splits the paragraph, so + // replace directly on the live view instead. Walk the text nodes of view.state.doc for each + // match's from/to (Node.descendants, prosemirror-model:110, the callback carries the absolute + // position), then one tr.insertText(replace, from, to) per match from the last match back to + // the first so the earlier positions stay valid, and view.dispatch(tr) (getEditorRef, + // react-ltZBBRVr.d.ts:1225; getView, d.ts:664; state.tr, prosemirror-state:843; insertText, + // prosemirror-state:627). No tracked change and no accept; an empty replace is a deleteRange. + // A match must sit inside one text node: a phrase split across adjacent nodes (for example by + // a formatting mark) is not matched. + run: async (args, ctx) => call(ctx, async host => { + const ed = editor(await host.appWindow(APP)); + const view = ed.getEditorRef?.()?.getView?.(); + const doc = view?.state?.doc; + if (!doc) throw new ToolError('not_available', 'the Docs editor is not ready yet; try again shortly', ''); + const needle = String(args.find).toLowerCase(); + if (!needle) throw new ToolError('invalid_argument', 'find= must not be empty', ''); + const limit = args.limit ?? 50; + const matches = []; + doc.descendants((node, pos) => { + if (matches.length >= limit || !node.isText) return; + const lower = String(node.text ?? '').toLowerCase(); + let at = lower.indexOf(needle); + while (at >= 0 && matches.length < limit) { + matches.push({ from: pos + at, to: pos + at + needle.length }); + at = lower.indexOf(needle, at + needle.length); + } + }); + if (matches.length === 0) throw new ToolError('app_error', `no occurrences of "${args.find}" in the document`, ''); + const tr = view.state.tr; + for (let i = matches.length - 1; i >= 0; i--) tr.insertText(String(args.replace), matches[i].from, matches[i].to); + view.dispatch(tr); + return { replaced: matches.length }; + }), + }, + { + name: 'docs.bold_selection', + purpose: 'Bold the current selection, or the whole paragraph at the cursor.', + when: 'Use when the user wants the selected text, or the line under the cursor, made bold.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Bold this' }], + // DocxEditorRef.getSelection + applyFormatting (react-ltZBBRVr.d.ts:1290): a direct edit; + // search is the selected phrase when there is one, the whole paragraph when not + run: async (args, ctx) => call(ctx, async host => { + const ed = editor(await host.appWindow(APP)); + const selection = ed.getSelection(); + if (!selection?.paraId) throw new ToolError('invalid_argument', 'there is no cursor or selection in Docs; open it and click into the text first', ''); + if (!ed.applyFormatting({ paraId: selection.paraId, search: selection.selectedText || undefined, marks: { bold: true } })) throw new ToolError('app_error', 'could not apply bold (the selection is not unique in its paragraph?)', ''); + return { bolded: selection.selectedText || 'the whole paragraph' }; + }), + }, + { + name: 'docs.new', + purpose: 'Replace the document with a fresh one; the current content is lost.', + when: 'Use when the user wants to start over with a new document and agreed to lose the current one.', + params: { title: { type: 'string', description: 'Title of the new document; Untitled document when omitted' } }, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: { title: 'Weekly report' }, says: 'Start a new document' }], + // DocxEditorRef.createDocument (react-ltZBBRVr.d.ts:1420): "DESTRUCTIVE" per its doc comment; + // unlike the app's New button it keeps no recover-previous copy + run: async (args, ctx) => call(ctx, async host => { + const ed = editor(await host.appWindow(APP)); + const title = String(args.title ?? 'Untitled document'); + if (!ed.createDocument({ title, sections: [] })) throw new ToolError('app_error', 'the editor is not ready; try again shortly', ''); + return { title }; + }), + }, +]; diff --git a/agent/apps/effectcraft/skills.md b/agent/apps/effectcraft/skills.md new file mode 100644 index 0000000..a44d617 --- /dev/null +++ b/agent/apps/effectcraft/skills.md @@ -0,0 +1,132 @@ +## Open the demo project +slug: open-a-demo-project +summary: Open the built-in demo project, or start a new empty one. +keywords: demo, new project, start, example, sample, open +tools: desktop.open_app, effectcraft.project_open, effectcraft.inspect + +When: the user wants to see EffectCraft working or to start over. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.project_open demo=true +Check: effectcraft.inspect lists the project and the active composition. +Gotchas: opening the demo or a new project replaces the open one, so confirm first when there are unsaved edits; new=true starts an empty project instead. + +## Look at the project and the comps +slug: look-at-the-project +summary: Inspect the project, the comps and the layers of a comp. +keywords: inspect, project, comp, layers, composition, what is in +tools: desktop.open_app, effectcraft.project, effectcraft.comp + +When: the user asks what is in the project or what a comp contains. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.project +3. call_tool tool=effectcraft.comp +Check: the project lists comps and items; the comp lists its layers with ids and names. +Gotchas: layer ids and comp names in the replies are what the other tools take as layer= and comp=. + +## Read a layer and its properties +slug: read-a-layer +summary: Show a layer tree and read individual property values. +keywords: layer, property, value, opacity, position, transform, read +tools: desktop.open_app, effectcraft.layer, effectcraft.property_get + +When: the user asks what a layer has or wants a specific property value. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.layer layer=1 +3. call_tool tool=effectcraft.property_get layer=1 path=transform/opacity +Check: the layer tree lists property paths; the reply shows the value at the path. +Gotchas: layer= takes an id, #n (1-based from the top) or a name; path= is match ids joined by / as listed by effectcraft.layer; time= reads the value at a comp time. + +## Change a property +slug: change-a-property +summary: Set a property value or expression, or keyframe it at a time. +keywords: set, change, opacity, position, color, scale, rotation, expression +tools: desktop.open_app, effectcraft.property_set, effectcraft.property_get + +When: the user wants a property changed, like opacity, position or color. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.property_set layer=1 path=transform/opacity value=50 +Check: the reply is the property read back with the new value. +Gotchas: vectors are JSON arrays like value=[960,540]; colors are #rrggbb or [r,g,b,a] 0-1; time= keyframes the value at that time instead of setting it; expression= assigns an expression (empty string removes it). + +## Fade a layer in +slug: fade-a-layer-in +summary: Add keyframes that animate a property over time. +keywords: fade, animation, keyframe, tween, motion, over time +tools: desktop.open_app, effectcraft.keyframe_add, effectcraft.property_get + +When: the user wants a property animated over time. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.keyframe_add layer=1 path=transform/opacity keys=[{"time":0,"value":0},{"time":1,"value":100}] +Check: effectcraft.property_get shows the keys on the property. +Gotchas: keys= is a JSON array of {time, value?} with time in seconds of layer time; timeBase=comp counts comp time instead; transform paths like transform/scale work the same. + +## Blur or grade a layer +slug: add-an-effect +summary: List the effects, then add one to a layer with values. +keywords: effect, blur, glow, color, grade, apply, filter +tools: desktop.open_app, effectcraft.effects_list, effectcraft.effect_add + +When: the user wants an effect on a layer, or the list of effects. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.effects_list filter=blur +3. call_tool tool=effectcraft.effect_add layer=1 effect=Gaussian Blur values={"blurriness":12} +Check: the reply lists the effect index, path, name and its parameters. +Gotchas: step 2 returns the registry when the model needs an effect id or name; values= is a JSON object of parameter id to value; the whole add is one undo step, so effectcraft.undo removes it cleanly. + +## Build a comp in one step +slug: build-a-comp +summary: Run several commands as one undo step with the batch tool. +keywords: batch, multi step, one go, atomic, build, create +tools: desktop.open_app, effectcraft.batch, effectcraft.comp + +When: the user wants several edits that should land as one undo step. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.batch steps=[{"command":"comp.new","params":{"name":"Titles","width":1920,"height":1080}}] +Check: effectcraft.comp shows the new comp. +Gotchas: steps= is a JSON array of {command, params?}; label= names the undo step; atomic=false keeps the steps that ran when one fails; commands that delete data (track.delete, effect.remove, file.newProject, ...) make the call destructive, so ask first. + +## Find and run any command +slug: run-any-effectcraft-command +summary: Look up an EffectCraft command by name, then run it with parameters. +keywords: command, run, menu, what can it do, time, export +tools: desktop.open_app, effectcraft.list_commands, effectcraft.run_command + +When: the user wants an action that has no dedicated tool. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.list_commands query=layer +3. call_tool tool=effectcraft.run_command command=layer.newText params=name=Title +Check: effectcraft.comp or effectcraft.inspect shows the action took effect. +Gotchas: run_command takes key=value lines in params= (a [ ... ] or { ... } value is JSON); command_describe is the registry query command.describe, reachable as run_command command=command.describe; track.delete, edit.purge and file.close are destructive, so ask the user first. +## Open a project or media from Files +slug: open-a-project-from-files +summary: Open an .ecproj project or import media that is stored in Files. +keywords: open, load, from files, ecproj, project, import, media +tools: desktop.open_app, effectcraft.open_file + +When: the user wants to open a project or import media that is stored in Files. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.open_file path=/EffectCraft/ad.ecproj +Check: the result has an opened field confirming the load; effectcraft.project or effectcraft.inspect shows the open project. +Gotchas: change path= to an .ecproj project or media (video, audio, image); opening a project replaces the open one, so ask the user first if the current project has unsaved work. + +## Save a copy of the project to Files +slug: save-a-project-copy-to-files +summary: Save the active EffectCraft project as a .ecproj file in Files. +keywords: save, copy, to files, ecproj, export, keep, write +tools: desktop.open_app, effectcraft.save_copy + +When: the user wants to keep a copy of the active project in Files. +Steps: +1. call_tool tool=desktop.open_app app=effectcraft +2. call_tool tool=effectcraft.save_copy path=/EffectCraft/ad.ecproj +Check: the result has the saved Files path and size; files.info on that path shows the same size. +Gotchas: change path=; EffectCraft saves .ecproj files, so a target with another extension is refused with the .ecproj path as the fix; if the path exists the tool errors, so choose another name or pass overwrite=true (which is destructive); a fresh project with no saved path yet makes the app refuse the save. diff --git a/agent/apps/effectcraft/tools.js b/agent/apps/effectcraft/tools.js new file mode 100644 index 0000000..6904a66 --- /dev/null +++ b/agent/apps/effectcraft/tools.js @@ -0,0 +1,595 @@ +// Ported from storytold/effectcraft@v0.24.1 crates/automation/src/tools.rs (the tool +// catalogue and dispatch bodies). Tool names, descriptions and the control-method mapping +// follow those tables; arguments are flattened for small models. +// The tools run in Buddy's frame and drive the EffectCraft page API through ctx.craft, which +// the runtime wires as id => craftApi(await ctx.host.appWindow(id), id) (plan 9). The page +// (public/pc/vendor/effectcraft/index.html) installs request/execute/commands/inspect/ +// screenshot, with inspect the page's own ui.inspect. +import { ToolError, callLine, closest } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { filesCall, openAndAwait, readOpenFile, saveBytesCopy } from '../../shared/craft-files.js'; +import { releases } from '../../../scripts/pc/craft/releases.mjs'; + +const APP = 'effectcraft'; +const NEEDS = ['host', 'app:effectcraft']; +// run_command/batch ids that destroy or replace data, from the engine command registry +// (grep of the cmd! ids in crates/engine/src/cmd): effectFor marks those calls destructive, +// so the policy asks. file.newProject and file.openDemoProject replace the open project +// (the web app holds one project), so they are destructive though the registry does not flag +// them. +const DESTRUCTIVE = [ + 'file.newProject', 'file.openDemoProject', 'file.close', 'file.revert', + 'edit.clear', 'edit.purge', 'keys.delete', 'markers.delete', + 'track.delete', 'track.reset', 'effect.remove', 'effect.reset', 'essential.remove', + 'layer.mask.remove', 'layer.style.remove', 'mask.remove', 'storage.clear', 'templates.delete', +]; + +/** tools.rs obj(): copy the listed keys (when present and not null) into a params object. */ +const pick = (args, keys) => { + const out = {}; + for (const key of keys) if (args[key] !== undefined && args[key] !== null) out[key] = args[key]; + return out; +}; + +// A key=value value: booleans, numbers, a [ ... ] or { ... } JSON value, else a string. +const parseValue = raw => { + if (/^(true|false)$/i.test(raw)) return raw.toLowerCase() === 'true'; + if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw); + if (raw.startsWith('[') || raw.startsWith('{')) { + try { return JSON.parse(raw); } catch { /* not JSON: keep as text */ } + } + return raw; +}; + +// key=value lines -> object (the generic long-tail form for params). +const parseParams = text => { + const out = {}; + for (const line of String(text ?? '').split('\n')) { + const row = line.trim(); + if (!row) continue; + const eq = row.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad params line "${row}": use key=value`, ''); + out[row.slice(0, eq).trim()] = parseValue(row.slice(eq + 1).trim()); + } + return out; +}; + +// A batch step "id k=v k2=v2": the id, then space-separated key=value tokens (no spaces in values). +const parseStep = line => { + const text = String(line ?? '').trim(); + const out = { command: '', params: {} }; + if (!text) return null; + const sp = text.indexOf(' '); + out.command = sp < 0 ? text : text.slice(0, sp); + for (const token of sp < 0 ? [] : text.slice(sp + 1).split(/\s+/)) { + const eq = token.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad batch step "${text}": params are key=value tokens`, ''); + out.params[token.slice(0, eq)] = parseValue(token.slice(eq + 1)); + } + return out; +}; + +// A layer tree property subtree -> [{path, type, value, ...}] (tools.rs flatten). +const flatten = node => { + if (node?.truncated === true) return [{ path: node.path, type: 'group', name: node.name, truncated: true }]; + if (Array.isArray(node?.children)) return node.children.flatMap(flatten); + const out = { path: node.path, type: node.type, value: node.value }; + if (Array.isArray(node?.keys)) out.keys = node.keys.length; + if (node?.expression !== undefined) out.expression = node.expression; + if (node?.options !== undefined) out.options = node.options; + return [out]; +}; + +// The `effects` group of a layer.tree reply (tools.rs effects_group). +const effectsChildren = tree => tree?.properties?.children?.find(child => child.path === 'effects')?.children ?? null; + +export const pack = { id: APP, title: 'EffectCraft' }; + +export const tools = [ + { + name: 'effectcraft.inspect', + purpose: 'Show the project overview and the active composition.', + when: 'Use when the user asks what is in the project, or before planning edits.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is in this project?' }], + // tools.rs:1006 doc_inspect: project.summary + comp.info (null when no comp is active) + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const project = await app.execute('project.summary', {}); + let activeComp = null; + try { + activeComp = await app.execute('comp.info', {}); + } catch { /* doc_inspect swallows this: the comp is null */ } + return { project, activeComp }; + }, + }, + { + name: 'effectcraft.project', + purpose: 'Show the project summary: comps, items, paths, undo history.', + when: 'Use when the user asks what compositions and items exist.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'List the compositions' }], + // tools.rs:280 get_project: project.summary + run: async (args, ctx) => (await ctx.craft(APP)).execute('project.summary', {}), + }, + { + name: 'effectcraft.comp', + purpose: 'Show a composition: size, duration, frame rate, layers with ids.', + when: 'Use when the user asks about a comp, or before editing its layers.', + params: { comp: { type: 'string', description: 'Composition id or name; the active comp when omitted' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'Tell me about the active comp' }], + // tools.rs:284 get_comp: comp.info + run: async (args, ctx) => (await ctx.craft(APP)).execute('comp.info', pick(args, ['comp'])), + }, + { + name: 'effectcraft.layer', + purpose: 'Show a layer tree: properties with paths to read and set.', + when: 'Use when the user asks what a layer has, or for property paths.', + params: { + layer: { type: 'string', required: true, description: 'Layer id (from effectcraft.comp), #n (1-based) or layer name' }, + comp: { type: 'string', description: 'Composition id or name; the active comp when omitted' }, + depth: { type: 'integer', description: 'Property tree depth' }, + time: { type: 'number', description: 'Comp time in seconds (values at that time)' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { layer: '1' }, says: 'What properties does layer 1 have?' }], + // tools.rs:313 get_layer: layer.tree; the flat client-side list is omitted (report) + run: async (args, ctx) => (await ctx.craft(APP)).execute('layer.tree', pick(args, ['layer', 'comp', 'depth', 'time'])), + }, + { + name: 'effectcraft.property_get', + purpose: 'Read one property value at a layer and path.', + when: 'Use when the user asks for a specific property value.', + params: { + layer: { type: 'string', required: true, description: 'Layer id, #n or name' }, + path: { type: 'string', required: true, description: 'Property path from effectcraft.layer, e.g. transform/opacity, effects/#1/blurriness' }, + comp: { type: 'string', description: 'Composition id or name; the active comp when omitted' }, + time: { type: 'number', description: 'Comp time in seconds' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { layer: '1', path: 'transform/opacity' }, says: 'What is the opacity?' }], + // tools.rs:324 get_property: prop.get + run: async (args, ctx) => (await ctx.craft(APP)).execute('prop.get', pick(args, ['layer', 'path', 'comp', 'time'])), + }, + { + name: 'effectcraft.property_set', + purpose: 'Set a property value or expression (or keyframe it at a time).', + when: 'Use when the user wants a property changed, e.g. opacity, position, color.', + params: { + layer: { type: 'string', required: true, description: 'Layer id, #n or name' }, + path: { type: 'string', required: true, description: 'Property path from effectcraft.layer' }, + value: { type: 'text', description: 'Number for 1-D properties, a [ ... ] JSON array for vectors, a #rrggbb color or [r,g,b,a]; as text' }, + expression: { type: 'string', description: 'Expression text; empty string removes the expression' }, + comp: { type: 'string', description: 'Composition id or name; the active comp when omitted' }, + time: { type: 'number', description: 'Keyframe the value at this comp time in seconds instead of setting it' }, + timeBase: { type: 'string', description: 'What time counts: layer (default) or comp' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { layer: '1', path: 'transform/opacity', value: '50' }, says: 'Set layer 1 opacity to 50' }], + // tools.rs:329 set_property: value -> prop.set (or prop.addKey with time), expression -> + // prop.setExpression, then prop.get to read the result back + run: async (args, ctx) => { + const app = await ctx.craft(APP); + if (args.value === undefined && args.expression === undefined) { + throw new ToolError('invalid_argument', 'give value and/or expression', ''); + } + const base = pick(args, ['layer', 'path', 'comp']); + const jsonValue = () => { + if (args.value === undefined) return undefined; + try { return JSON.parse(args.value); } catch { return args.value; } + }; + if (args.value !== undefined) { + const params = { ...base, value: jsonValue() }; + if (args.time !== undefined) { + params.time = args.time; + if (args.timeBase !== undefined) params.timeBase = args.timeBase; + await app.execute('prop.addKey', params); + } else { + await app.execute('prop.set', params); + } + } + if (args.expression !== undefined) { + await app.execute('prop.setExpression', { ...base, expression: args.expression }); + } + return app.execute('prop.get', { ...base, ...(args.time !== undefined ? { time: args.time } : {}) }); + }, + }, + { + name: 'effectcraft.keyframe_add', + purpose: 'Add one or more keyframes to a property.', + when: 'Use when the user wants a property animated over time.', + params: { + layer: { type: 'string', required: true, description: 'Layer id, #n or name' }, + path: { type: 'string', required: true, description: 'Property path from effectcraft.layer' }, + keys: { type: 'text', description: 'JSON array of {time, value?}, one per keyframe; time in seconds (layer time)' }, + comp: { type: 'string', description: 'Composition id or name; the active comp when omitted' }, + timeBase: { type: 'string', description: 'What the key times count: layer (default) or comp' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { layer: '1', path: 'transform/opacity', keys: '[{"time":0,"value":0},{"time":1,"value":100}]' }, says: 'Fade layer 1 in over one second' }], + // tools.rs:360 add_keyframe: one prop.addKey per key, then prop.get; the interpolation + // follow-up (keys.select + keys.interpolation) is omitted (report) + run: async (args, ctx) => { + let keys; + try { + keys = JSON.parse(args.keys); + } catch { + throw new ToolError('invalid_argument', 'keys must be a JSON array of {time, value?}', ''); + } + if (!Array.isArray(keys) || keys.length === 0) { + throw new ToolError('invalid_argument', 'keys needs at least one {time, value?}', ''); + } + const app = await ctx.craft(APP); + const base = pick(args, ['layer', 'path', 'comp']); + for (const key of keys) { + if (key?.time === undefined) throw new ToolError('invalid_argument', 'each key needs a time', ''); + const params = { ...base, time: key.time }; + if (key.value !== undefined) params.value = key.value; + if (args.timeBase !== undefined) params.timeBase = args.timeBase; + await app.execute('prop.addKey', params); + } + return app.execute('prop.get', base); + }, + }, + { + name: 'effectcraft.effect_add', + purpose: 'Add an effect to a layer, with parameter values, in one undo step.', + when: 'Use when the user wants an effect (blur, glow, color, ...) on a layer.', + params: { + layer: { type: 'string', required: true, description: 'Layer id, #n or name' }, + effect: { type: 'string', required: true, description: 'Effect id or name, e.g. Gaussian Blur, Glow, ec.color.levels' }, + values: { type: 'text', description: 'JSON object of parameter id to value, e.g. {"blurriness":12}' }, + comp: { type: 'string', description: 'Composition id or name; the active comp when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { layer: '1', effect: 'Gaussian Blur', values: '{"blurriness":12}' }, says: 'Blur layer 1' }], + // tools.rs:228 add_effect: layer.tree for the index, then ONE engine.batch of effect.apply + // plus prop.set per value (one undo step, labelled "Apply "), then layer.tree for + // the new instance's name and params + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const base = pick(args, ['layer', 'comp']); + const before = await app.execute('layer.tree', base); + const index = (effectsChildren(before)?.length ?? 0) + 1; + const steps = [{ command: 'effect.apply', params: { effect: args.effect, layers: [args.layer], ...(args.comp !== undefined ? { comp: args.comp } : {}) } }]; + let values = {}; + if (args.values !== undefined) { + try { + values = JSON.parse(args.values); + } catch { + throw new ToolError('invalid_argument', 'values must be a JSON object of parameter id to value', ''); + } + const prefix = `effects/#${index}`; + for (const [key, value] of Object.entries(values)) { + steps.push({ command: 'prop.set', params: { layer: args.layer, ...(args.comp !== undefined ? { comp: args.comp } : {}), path: `${prefix}/${key}`, value } }); + } + } + await app.execute('engine.batch', { steps, label: `Apply ${args.effect}` }); + const tree = await app.execute('layer.tree', base); + const children = effectsChildren(tree); + const inst = children?.[index - 1]; + const out = { layer: tree?.id, index, path: `effects/#${index}`, set: Object.keys(values) }; + if (inst) { + out.name = inst.name; + out.params = flatten(inst); + } + return out; + }, + }, + { + name: 'effectcraft.effects_list', + purpose: 'List the effect registry: ids, names, categories, parameters.', + when: 'Use when the user asks what effects exist, or before adding one.', + params: { filter: { type: 'string', description: 'Only effects whose id or name contains this text' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { filter: 'blur' }, says: 'What blur effects are there?' }], + // tools.rs:214 list_effects: effect.list (the compact flag is omitted: the model gets the + // full registry rows) + run: async (args, ctx) => (await ctx.craft(APP)).execute('effect.list', pick(args, ['filter'])), + }, + { + name: 'effectcraft.fonts_list', + purpose: 'List the fonts the app can use, optionally filtered.', + when: 'Use when the user asks what fonts are available.', + params: { query: { type: 'string', description: 'Substring of the font name' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { query: 'mono' }, says: 'List monospace fonts' }], + // tools.rs:222 list_fonts: text.fonts (variable/rescan are omitted: web fonts are the app set) + run: async (args, ctx) => (await ctx.craft(APP)).execute('text.fonts', pick(args, ['query'])), + }, + { + name: 'effectcraft.state', + purpose: 'Show the editor state and the app capabilities.', + when: 'Use when the user asks what the app can do right now.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What can the app do?' }], + // tools.rs:265 get_state: editor.state + app.capabilities + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const [state, app2] = await Promise.all([app.execute('editor.state', {}), app.execute('app.capabilities', {})]); + return { state, app: app2 }; + }, + }, + { + name: 'effectcraft.script_run', + purpose: 'Run a JavaScript script against the project.', + when: 'Use when the user wants a scripted bulk edit.', + params: { + code: { type: 'text', required: true, description: 'JavaScript code (the app exposes the project API to it)' }, + name: { type: 'string', description: 'Script name used in error messages (default script)' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { code: 'comp.layers.forEach(l => l.opacity = 50)' }, says: 'Dim every layer of the active comp' }], + // tools.rs:271 run_script: script.run + run: async (args, ctx) => (await ctx.craft(APP)).execute('script.run', pick(args, ['code', 'name'])), + }, + { + name: 'effectcraft.project_open', + purpose: 'Open the demo project, or start a new empty one (replaces the open one).', + when: 'Use when the user wants the demo project or to start over.', + params: { + demo: { type: 'boolean', description: 'Open the built-in demo project' }, + new: { type: 'boolean', description: 'Start a new empty project' }, + }, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: { demo: true }, says: 'Open the demo project' }], + // tools.rs:426 open_project: demo -> file.openDemoProject, new -> file.newProject, then + // project.summary; the path variant (file.open) is omitted (web has no file paths). Both + // are destructive: the web app holds one project, so this replaces the open one + run: async (args, ctx) => { + const app = await ctx.craft(APP); + if (args.demo === true) await app.execute('file.openDemoProject', {}); + else if (args.new === true) await app.execute('file.newProject', {}); + else throw new ToolError('invalid_argument', 'give demo: true or new: true', ''); + return app.execute('project.summary', {}); + }, + }, + { + name: 'effectcraft.project_save', + purpose: 'Save the project (in place).', + when: 'Use when the user wants to save the work.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Save the project' }], + // tools.rs:439 save_project: file.save (in place; the saveAs path variant is omitted), then + // project.summary -> {path, dirty} + run: async (args, ctx) => { + const app = await ctx.craft(APP); + await app.execute('file.save', {}); + const summary = await app.execute('project.summary', {}); + return { path: summary?.path, dirty: summary?.dirty }; + }, + }, + { + name: 'effectcraft.undo', + purpose: 'Undo one or more of the last changes.', + when: 'Use when the user wants to undo the last change.', + params: { steps: { type: 'integer', description: 'How many steps to undo (default 1)' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Undo that' }], + // tools.rs:448 history + :462 undo: N x edit.undo, stopping when one fails, then + // project.summary -> {steps, undoStack} + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const steps = Math.max(1, Math.round(args.steps ?? 1)); + let done = 0; + for (let i = 0; i < steps; i++) { + try { + await app.execute('edit.undo', {}); + done += 1; + } catch (error) { + if (done === 0) throw new ToolError('app_error', error instanceof Error ? error.message : String(error), ''); + break; + } + } + const summary = await app.execute('project.summary', {}); + return { steps: done, undoStack: summary?.undo }; + }, + }, + { + name: 'effectcraft.redo', + purpose: 'Redo one or more of the last undone changes.', + when: 'Use when the user wants to redo the change they just undid.', + params: { steps: { type: 'integer', description: 'How many steps to redo (default 1)' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Bring that back' }], + // tools.rs:467 redo: N x edit.redo, same shape as undo + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const steps = Math.max(1, Math.round(args.steps ?? 1)); + let done = 0; + for (let i = 0; i < steps; i++) { + try { + await app.execute('edit.redo', {}); + done += 1; + } catch (error) { + if (done === 0) throw new ToolError('app_error', error instanceof Error ? error.message : String(error), ''); + break; + } + } + const summary = await app.execute('project.summary', {}); + return { steps: done, undoStack: summary?.undo }; + }, + }, + { + name: 'effectcraft.history', + purpose: 'List the undo/redo history, optionally jump to a state.', + when: 'Use when the user asks what happened, or wants to jump back.', + params: { goto: { type: 'string', description: 'State index or id to jump to (edit.history.goto)' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Show the edit history' }], + // tools.rs:484 history_tool: goto -> edit.history.goto {id or index}, then + // edit.history.list + run: async (args, ctx) => { + const app = await ctx.craft(APP); + if (args.goto !== undefined) { + const params = /^-?\d+$/.test(String(args.goto)) ? { index: Number(args.goto) } : { id: String(args.goto) }; + await app.execute('edit.history.goto', params); + } + return app.execute('edit.history.list', {}); + }, + }, + { + name: 'effectcraft.batch', + purpose: 'Run several commands as one undo step (atomic by default).', + when: 'Use when several edits should land as a single undo step.', + params: { + steps: { type: 'text', required: true, description: 'JSON array of {command, params?}, e.g. [{"command":"layer.newText","params":{"name":"Title"}}]' }, + label: { type: 'string', description: 'Undo step name (default Batch)' }, + atomic: { type: 'boolean', description: 'Roll everything back when a step fails (default true)' }, + }, + effect: 'change', + effectFor: args => { + let steps = args.steps; + if (typeof steps === 'string') { try { steps = JSON.parse(steps); } catch { return 'change'; } } + return (Array.isArray(steps) ? steps : []).some(step => DESTRUCTIVE.some(id => String(step?.command ?? '').startsWith(id))) ? 'destructive' : 'change'; + }, + needs: NEEDS, + examples: [{ args: { steps: '[{"command":"comp.new","params":{"name":"Titles","width":1920,"height":1080}}]' }, says: 'Create a Titles comp' }], + // tools.rs:496 batch_tool: ONE engine.batch {steps, label?, atomic?} (the engine applies the + // atomic default; engine.batch cannot nest itself, engine/cmd/batch.rs:14) + run: async (args, ctx) => { + let steps; + try { + steps = JSON.parse(args.steps); + } catch { + throw new ToolError('invalid_argument', 'steps must be a JSON array of {command, params?}', ''); + } + if (!Array.isArray(steps) || steps.length === 0 || steps.some(step => typeof step?.command !== 'string')) { + throw new ToolError('invalid_argument', 'steps must be a non-empty JSON array of {command, params?}', ''); + } + return (await ctx.craft(APP)).execute('engine.batch', { steps, ...pick(args, ['label', 'atomic']) }); + }, + }, + { + name: 'effectcraft.list_commands', + purpose: 'Find commands by a word in the id, label or menu.', + when: 'Use when the user wants an action and its command id is unknown.', + params: { query: { type: 'string', description: 'Substring of the command id, label or menu path; omit to list the first 10' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { query: 'layer.new' }, says: 'Which commands create layers?' }], + // tools.rs:179 list_commands runs the engine command command.list; the page's commands() + // (the engine.commands control method, ui-egui control.rs:236) runs that same command and + // is cached by the adapter, so the pack uses it like the other packs + run: async (args, ctx) => { + const all = await (await ctx.craft(APP)).commands(); + const q = String(args.query ?? '').trim().toLowerCase(); + return all.filter(command => !q || [command.id, command.label, command.menu].some(part => String(part ?? '').toLowerCase().includes(q))) + .slice(0, 10).map(command => ({ id: command.id, label: command.label, menu: command.menu, params: command.params, enabled: command.enabled })); + }, + }, + { + name: 'effectcraft.run_command', + purpose: 'Run any EffectCraft command by id with parameters.', + when: `Use when a menu action is wanted by id; ${DESTRUCTIVE.join(', ')} are destructive, so ask first.`, + params: { + command: { type: 'string', required: true, description: 'Command id from effectcraft.list_commands, e.g. comp.new, layer.newText, prop.set' }, + params: { type: 'text', description: 'Parameters as key=value lines, one per line; a [ ... ] or { ... } value is JSON; omit for the defaults' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(prefix => String(args.command ?? '').startsWith(prefix)) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { command: 'time.set', params: 'seconds=5' }, says: 'Jump to 5 seconds' }], + // tools.rs:202 execute_command: run(id, params) against the live command list; unknown ids + // get invalid_argument with the 3 closest. The command_list/command_run aliases + // (:937/:954) and the sequential command_batch (:986) are deduped here; describe_command + // (:576) is the registry query command.describe, reachable as run_command + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const all = await app.commands(); + if (!all.some(command => command.id === args.command)) { + const near = closest(args.command, all.map(command => command.id), 3); + const fix = near.length > 0 ? callLine('effectcraft.run_command', { command: near[0] }) : ''; + throw new ToolError('invalid_argument', `unknown command "${args.command}"${near.length > 0 ? `; closest: ${near.join(', ')}` : ''}`, fix); + } + return app.execute(args.command, parseParams(args.params)); + }, + }, + { + name: 'effectcraft.open_file', + purpose: 'Open a project or import media from Files into EffectCraft.', + when: 'Use when the user wants a project or media from Files. Not for opening the app itself; that is desktop.open_app.', + params: { path: { type: 'path', required: false, description: 'A Files path to an .ecproj project or media (video, audio or image)' } }, + effect: 'destructive', + needs: ['host', 'app:effectcraft', 'files'], + examples: [{ args: { path: '/EffectCraft/ad.ecproj' }, says: 'Open the ad project from Files' }], + // EffectCraft is a standalone wrapper (releases.mjs), so the open rides the bootstrap's + // open path: drive the wrapper's own #file input (app.mjs:38) so the wrapper posts + // effectcraft:open (app.mjs:35-36) and the bootstrap (bootstrap.js:52-89, openMethod + // addFile) hands the bytes to window.effectcraft.addFile, which opens a .ecproj or + // imports media. Opening a project replaces the open one (the web app holds one project), + // so this is destructive. openAndAwait waits until the page's inspect changes. + run: async (args, ctx) => { + const file = await readOpenFile(ctx, args.path, { id: APP, title: 'EffectCraft' }); + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + return openAndAwait(craft, { id: APP, title: 'EffectCraft', wrapperWindow: wrapper, name: file.name, bytes: file.bytes, accept: releases[APP].accept }); + }, + }, + { + name: 'effectcraft.save_copy', + purpose: 'Save the active project as a .ecproj file in Files.', + when: 'Use when the user wants to keep a copy of the project in Files.', + params: { + path: { type: 'path', required: true, description: 'The Files path to write the copy to, e.g. /EffectCraft/ad.ecproj' }, + overwrite: { type: 'boolean', description: 'Replace the file when the path already exists; false when omitted' }, + }, + effect: 'change', + effectFor: args => (args.overwrite ? 'destructive' : 'change'), + needs: ['host', 'app:effectcraft', 'files'], + examples: [{ args: { path: '/EffectCraft/ad.ecproj' }, says: 'Save a copy of the project to Files' }], + // No path is ever passed (the browser has no file system). EffectCraft has no file.saveBytes, + // so the no-path file.save {} (engine cmd/file.rs:793) is the trigger; in standalone mode the + // app's own download is captured by the bootstrap's anchor-click hook (bootstrap.js:92-98, + // nativeSource .ecproj) and posted to the wrapper as effectcraft:save (app.mjs:29-33), which + // the saveCopy capture reads. The bytes are the native .ecproj format, so a target with + // another extension is refused with a fix. A fresh project with no saved path yet makes the + // app refuse ("no path: use file.saveAs {path}"), which surfaces as the tool error. + run: async (args, ctx) => { + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + const save = await saveBytesCopy(craft, { + id: APP, title: 'EffectCraft', wrapperWindow: wrapper, target: args.path, + tool: 'effectcraft.save_copy', nativeExt: '.ecproj', + }); + const written = await filesCall( + ctx, + files => files.writeBytes(args.path, save.bytes, { overwrite: Boolean(args.overwrite) }), + error => (error.code === 'exists' ? callLine('effectcraft.save_copy', { path: args.path, overwrite: true }) : ''), + ); + return { path: written.path, name: save.name, size: written.size, created: written.created, ...(save.note ? { note: save.note } : {}) }; + }, + }, +]; + +// Live-check exports (brief): every command id the pack passes to execute (the fixed ids of +// the effect_add batch included) and every control method passed to request. batch and +// run_command also pass arbitrary ids from the live commands() list. +export const usesCommands = [ + 'project.summary', 'comp.info', 'layer.tree', 'prop.get', 'prop.set', 'prop.addKey', 'prop.setExpression', + 'engine.batch', 'effect.apply', 'effect.list', 'text.fonts', 'editor.state', 'app.capabilities', + 'script.run', 'file.openDemoProject', 'file.newProject', 'file.save', + 'edit.undo', 'edit.redo', 'edit.history.goto', 'edit.history.list', +]; +export const usesMethods = []; // nothing goes through request(); the page inspect() is not used (the packs read via engine queries) diff --git a/agent/apps/excalidraw/skills.md b/agent/apps/excalidraw/skills.md new file mode 100644 index 0000000..f04c6f7 --- /dev/null +++ b/agent/apps/excalidraw/skills.md @@ -0,0 +1,78 @@ +## Draw a diagram +slug: draw-a-diagram +summary: Add shapes, labels, lines and arrows to the canvas from a one-shape-per-line spec. +keywords: draw, diagram, flowchart, sketch, shapes, boxes, canvas, picture +tools: desktop.open_app, excalidraw.add_shapes + +When: the user wants a diagram, flowchart or sketch drawn on the canvas. +Steps: +1. call_tool tool=desktop.open_app app=excalidraw +2. call_tool tool=excalidraw.add_shapes spec="rectangle 100 100 200 80 Start\nrectangle 400 100 200 80 End\narrow 1 2" +Check: excalidraw.list_elements shows the new shapes; the user sees them on the canvas. +Gotchas: change the spec; one shape per line (rectangle/ellipse/diamond x y w h [label], text x y label, line x1 y1 x2 y2, arrow A B); arrow numbers are 1-based shape line numbers and must come after the lines they join. + +## Add a label +slug: add-a-label +summary: Add a free text label at a canvas position. +keywords: label, caption, text, note, title, write on canvas +tools: desktop.open_app, excalidraw.add_text + +When: the user wants a caption, note or standalone label on the canvas. +Steps: +1. call_tool tool=desktop.open_app app=excalidraw +2. call_tool tool=excalidraw.add_text text=Q3 roadmap x=20 y=20 +Check: excalidraw.list_elements shows the new text element. +Gotchas: change text=, x= and y=; canvas coordinates, not screen pixels; use add_shapes instead when the text should sit inside a shape. + +## See what is on the canvas +slug: see-the-canvas +summary: List the elements on the canvas with their type and position. +keywords: what is on, list, elements, canvas, contents, show drawing +tools: desktop.open_app, excalidraw.list_elements + +When: the user asks what is on the canvas, or before drawing more on top of it. +Steps: +1. call_tool tool=desktop.open_app app=excalidraw +2. call_tool tool=excalidraw.list_elements +Check: the result has count and one row per element (id, type, x, y, width, height; text for labels). +Gotchas: read-only; the rows are the anchor for what to draw next, so use them before add_shapes. + +## Fit everything in view +slug: fit-everything-in-view +summary: Zoom the canvas so all content fits in view. +keywords: zoom to fit, fit view, show everything, zoom out, see all +tools: desktop.open_app, excalidraw.fit_view + +When: the user says zoom to fit, show everything or fit the view. +Steps: +1. call_tool tool=desktop.open_app app=excalidraw +2. call_tool tool=excalidraw.fit_view +Check: the user sees the whole drawing in the viewport. +Gotchas: changes only the viewport, not the drawing; it is a no-op on an empty canvas. + +## Connect two shapes with an arrow +slug: connect-shapes-with-an-arrow +summary: Draw an arrow between two existing or new shapes in one spec. +keywords: arrow, connect, link, point from, join, flow between +tools: desktop.open_app, excalidraw.add_shapes, excalidraw.list_elements + +When: the user wants an arrow from one shape to another. +Steps: +1. call_tool tool=desktop.open_app app=excalidraw +2. call_tool tool=excalidraw.list_elements +3. call_tool tool=excalidraw.add_shapes spec="rectangle 100 100 200 80 First\nrectangle 400 100 200 80 Second\narrow 1 2" +Check: excalidraw.list_elements shows an arrow element whose position runs between the two shapes. +Gotchas: change the spec; arrow line numbers are 1-based shape line numbers within the same spec, so for shapes already on the canvas draw them in the same spec first. + +## Clear the canvas +slug: clear-the-canvas +summary: Delete every element on the canvas; undo is lost too. +keywords: clear, empty, wipe, delete everything, blank canvas, reset drawing +tools: desktop.open_app, excalidraw.clear + +When: the user wants the whole canvas emptied. +Steps: +1. call_tool tool=desktop.open_app app=excalidraw +2. call_tool tool=excalidraw.clear +Check: excalidraw.list_elements shows count 0. +Gotchas: this is destructive and also clears the undo history, so ask the user to confirm first and offer to list or export the drawing before clearing. diff --git a/agent/apps/excalidraw/tools.js b/agent/apps/excalidraw/tools.js new file mode 100644 index 0000000..e23ce92 --- /dev/null +++ b/agent/apps/excalidraw/tools.js @@ -0,0 +1,200 @@ +// Excalidraw pack: the drawing canvas tools (add shapes, add text, list, fit view, clear). +// Every tool drives the imperative API the app exposes as window.webpcExcalidraw.api +// (scripts/pc/excalidraw/main.jsx:106), the @excalidraw/excalidraw ExcalidrawImperativeAPI +// (dist/types/excalidraw/types.d.ts:603): getSceneElements, updateScene, resetScene, scrollToContent. +// The scene autosaves to localStorage, so edits persist; resetScene also clears the undo history. +import { ToolError } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { innerApi } from '../../shared/inner-app.js'; + +const APP = 'excalidraw'; +const FRAME = 'excalidraw-frame'; +const NEEDS = ['host', 'app:excalidraw']; +const NOT_HERE = 'Excalidraw is not available here (Buddy is not running inside WebPC).'; + +// Gate on ctx.host (needs: ['host', 'app:excalidraw']), then turn host rejections, which carry a +// code (unknown_app, not_open, not_iframe, timeout, invalid_argument), into a ToolError. +const call = (ctx, fn) => { + if (!ctx.host) throw new ToolError('not_available', NOT_HERE, ''); + return Promise.resolve() + .then(() => fn(ctx.host)) + .catch(error => { + if (error instanceof ToolError) throw error; + throw new ToolError(error.code || 'app_error', error.message, ''); + }); +}; + +// The real app runs in the #excalidraw-frame iframe of the wrapper page that appWindow returns +// (src/pages/pc/apps/excalidraw/index.astro:10); webpcExcalidraw.api is set on that inner window +// once the api callback fires (scripts/pc/excalidraw/main.jsx:106). Dig in and poll. +const getApi = async (host, ctx) => innerApi(await host.appWindow(APP), FRAME, win => win.webpcExcalidraw?.api, { sleep: ctx.sleep, timeoutMs: ctx.timeoutMs }); + +// Element builders. updateScene replaces the scene array without normalizing new elements, so +// every element carries the full ExcalidrawElement base shape (dist/types/excalidraw/element/ +// types.d.ts _ExcalidrawElementBase). +const stamp = () => Math.floor(Math.random() * 2 ** 31).toString(36); +const base = type => ({ + id: `buddy-${stamp()}${stamp()}`, + type, x: 0, y: 0, width: 100, height: 100, angle: 0, + strokeColor: '#1e1e1e', backgroundColor: 'transparent', fillStyle: 'hachure', + strokeWidth: 2, strokeStyle: 'solid', roundness: null, roughness: 1, opacity: 100, + groupIds: [], frameId: null, boundElements: null, index: null, isDeleted: false, + seed: Math.floor(Math.random() * 2 ** 31), version: 1, versionNonce: Math.floor(Math.random() * 2 ** 31), + updated: Date.now(), link: null, locked: false, +}); +const lines = text => Math.max(1, String(text).split('\n').length); +// shortcut: text width/height are estimates (12px per char at fontSize 20); Excalidraw re-measures +// text on load and when the element is first edited. +const makeText = (text, x, y) => ({ ...base('text'), x, y, text, originalText: text, fontSize: 20, fontFamily: 1, textAlign: 'left', verticalAlign: 'top', containerId: null, autoResize: true, lineHeight: 1.25, width: Math.max(20, String(text).length * 12), height: 25 * lines(text) }); +// A labeled shape: the shape plus a bound text element centred on it (ROUNDNESS.PROPORTIONAL_RADIUS = 2). +const makeLabeled = (type, x, y, width, height, label) => { + const shape = { ...base(type), x, y, width, height, roundness: type === 'rectangle' ? { type: 2 } : null }; + if (!label) return [shape]; + const text = { ...makeText(label, x + width / 2 - (label.length * 12) / 2, y + height / 2 - 12), containerId: shape.id, textAlign: 'center', autoResize: false, width, height }; + shape.boundElements = [{ id: text.id, type: 'text' }]; + return [shape, text]; +}; +const linear = (type, x1, y1, x2, y2, endArrowhead) => ({ ...base(type), x: x1, y: y1, width: Math.abs(x2 - x1), height: Math.abs(y2 - y1), points: [[0, 0], [x2 - x1, y2 - y1]], lastCommittedPoint: null, startBinding: null, endBinding: null, startArrowhead: null, endArrowhead }); + +// One shape per line: "rectangle 100 100 200 80 Start", "ellipse 10 20 140 60", "text 5 5 Hello", +// "line 0 0 200 0", "arrow 1 2" (an arrow from shape line 1 to shape line 2 of this spec, 1-based; +// a label adds no line of its own). +const parseSpec = text => { + const SHAPES = ['rectangle', 'ellipse', 'diamond', 'line', 'arrow', 'text']; + const spec = String(text ?? '').split('\n').map(line => line.trim()).filter(Boolean); + if (spec.length === 0) throw new ToolError('invalid_argument', 'spec is empty; one shape per line, e.g. "rectangle 100 100 200 80 Start"', ''); + const built = []; + const shapes = []; // one entry per shape line (a label never counts); arrow targets + const errors = []; + spec.forEach((line, i) => { + const words = line.split(/\s+/); + const kind = words[0]; + if (!SHAPES.includes(kind)) { errors.push(`line ${i + 1}: unknown shape "${kind}" (use ${SHAPES.join(', ')})`); return; } + if (kind === 'text') { + const nums = words.slice(1, 3).map(Number); + const label = words.slice(3).join(' '); + if (nums.length < 2 || nums.some(Number.isNaN) || !label) { errors.push(`line ${i + 1}: text needs x, y and a label, e.g. "text 5 5 Hello world"`); return; } + const el = makeText(label, nums[0], nums[1]); + built.push(el); + shapes.push(el); + return; + } + if (kind === 'line') { + const nums = words.slice(1).map(Number); + if (nums.length !== 4 || nums.some(Number.isNaN)) { errors.push(`line ${i + 1}: line needs x1, y1, x2 and y2`); return; } + const el = linear('line', nums[0], nums[1], nums[2], nums[3], null); + built.push(el); + shapes.push(el); + return; + } + if (kind === 'arrow') { + const nums = words.slice(1).map(Number); + if (nums.length !== 2 || nums.some(Number.isNaN)) { errors.push(`line ${i + 1}: arrow takes two shape line numbers (1-based), e.g. "arrow 1 2"`); return; } + const from = shapes[nums[0] - 1]; + const to = shapes[nums[1] - 1]; + if (!from || !to) { errors.push(`line ${i + 1}: shape lines ${nums[0]} and ${nums[1]} must be listed before the arrow`); return; } + const ax = from.x + from.width / 2, ay = from.y + from.height / 2, bx = to.x + to.width / 2, by = to.y + to.height / 2; + built.push(linear('arrow', ax, ay, bx, by, 'arrow')); + return; + } + // rectangle, ellipse and diamond: x, y, width, height then an optional label word. + const nums = words.slice(1, 5).map(Number); + const label = words.slice(5).join(' '); + if (nums.length < 4 || nums.some(Number.isNaN)) { errors.push(`line ${i + 1}: ${kind} needs x, y, width and height`); return; } + const els = makeLabeled(kind, nums[0], nums[1], nums[2], nums[3], label); + built.push(...els); + shapes.push(els[0]); + }); + if (errors.length) throw new ToolError('invalid_argument', errors.join('; '), ''); + return built; +}; + +export const pack = { id: APP, title: 'Excalidraw' }; + +export const tools = [ + { + name: 'excalidraw.add_shapes', + purpose: 'Add shapes, labels, lines and arrows to the canvas, one per line of a spec.', + when: 'Use when the user wants a diagram, flowchart or sketch drawn on the canvas.', + params: { spec: { type: 'text', required: true, description: 'One shape per line: "rectangle 100 100 200 80 Start", "ellipse 10 20 140 60", "text 5 5 Hello", "line 0 0 200 0", "arrow 1 2" (shape line numbers, 1-based)' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { spec: 'rectangle 100 100 200 80 Start\nrectangle 400 100 200 80 End\narrow 1 2' }, says: 'Draw a Start to End flow' }], + // getSceneElements + updateScene (types.d.ts:603-611); captureUpdate "IMMEDIATELY" makes the + // add undoable (store.d.ts:16) + run: async (args, ctx) => call(ctx, async host => { + const ex = await getApi(host, ctx); + const elements = parseSpec(args.spec); + ex.updateScene({ elements: [...ex.getSceneElements(), ...elements], captureUpdate: 'IMMEDIATELY' }); + return { added: elements.length }; + }), + }, + { + name: 'excalidraw.add_text', + purpose: 'Add a free text label at a canvas position.', + when: 'Use when the user wants a caption, note or standalone label on the canvas.', + params: { + text: { type: 'text', required: true, description: 'The label text' }, + x: { type: 'integer', required: true, description: 'Left edge in canvas coordinates' }, + y: { type: 'integer', required: true, description: 'Top edge in canvas coordinates' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { text: 'Q3 roadmap', x: 20, y: 20 }, says: 'Add a title to the drawing' }], + // Same updateScene path as add_shapes, for a single text element + run: async (args, ctx) => call(ctx, async host => { + const ex = await getApi(host, ctx); + const element = makeText(args.text, args.x, args.y); + ex.updateScene({ elements: [...ex.getSceneElements(), element], captureUpdate: 'IMMEDIATELY' }); + return { added: 1 }; + }), + }, + { + name: 'excalidraw.list_elements', + purpose: 'List the elements on the canvas with their type and position.', + when: 'Use when the user asks what is on the canvas, or before drawing more on top of it.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is on the canvas?' }], + // getSceneElements (types.d.ts:611), trimmed to the fields the model can act on + run: async (args, ctx) => call(ctx, async host => { + const ex = await getApi(host, ctx); + const elements = [...ex.getSceneElements()].map(el => { + const row = { id: el.id, type: el.type, x: Math.round(el.x), y: Math.round(el.y), width: Math.round(el.width), height: Math.round(el.height) }; + if (el.type === 'text') row.text = el.text; + return row; + }); + return { count: elements.length, elements }; + }), + }, + { + name: 'excalidraw.fit_view', + purpose: 'Zoom the canvas so all content fits in view.', + when: 'Use when the user says zoom to fit, show everything or fit the view.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Fit everything in view' }], + // scrollToContent with no target and fitToContent (App.d.ts:335) + run: async (args, ctx) => call(ctx, async host => { + const ex = await getApi(host, ctx); + ex.scrollToContent(undefined, { fitToContent: true, animate: true }); + return { fitted: true }; + }), + }, + { + name: 'excalidraw.clear', + purpose: 'Delete every element on the canvas; undo is lost too.', + when: 'Use when the user wants the whole canvas emptied and agreed to lose the drawing and its undo history.', + params: {}, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: {}, says: 'Clear the canvas' }], + // resetScene (types.d.ts:606): resets scene and history (App.d.ts:281-285) + run: async (args, ctx) => call(ctx, async host => { + const ex = await getApi(host, ctx); + ex.resetScene(); + return { cleared: true }; + }), + }, +]; diff --git a/agent/apps/figcraft/skills.md b/agent/apps/figcraft/skills.md new file mode 100644 index 0000000..71d8fff --- /dev/null +++ b/agent/apps/figcraft/skills.md @@ -0,0 +1,156 @@ +## Design a mobile screen +slug: design-a-mobile-screen +summary: Build one mobile app screen in a phone frame with auto layout and real text. +keywords: mobile, phone, screen, app, ui, frame, login, settings +tools: desktop.open_app, figcraft.new_document, figcraft.run_command, figcraft.set_properties, figcraft.create_node, figcraft.inspect_document + +When: the user wants a mobile app screen designed, e.g. login, settings or an order summary. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.new_document +3. call_tool tool=figcraft.run_command command=frame.create params=preset=iPhone 16\nx=0\ny=0\nname=Login +4. call_tool tool=figcraft.set_properties ids=1 props=fill=#FFFFFF\nlayout=vertical\npadding=[64,24,32,24]\ngap=16\nsizingV=fixed +5. call_tool tool=figcraft.create_node parent=1 type=text text=Welcome back props=fontSize=28\nfontStyle=Bold +6. call_tool tool=figcraft.create_node parent=1 type=frame name=Email props=layout=horizontal\npadding=16\ncornerRadius=12\nstroke=#E0E0E0\nsizingH=fill +Check: figcraft.inspect_document depth=2 shows the frame, the title and the field. +Gotchas: Adapted from figcraft@v0.18.1 prompts.rs mobile_screen. Change the screen name and colors (brand default #3B5BDB); keep spacing on an 8-point grid and text left-aligned; the frame id from step 3 is the parent for the content. + +## Start a design system +slug: start-a-design-system +summary: Create color variables, paint and text styles, and a button component. +keywords: design system, styles, variables, component, brand, tokens +tools: desktop.open_app, figcraft.new_document, figcraft.run_command, figcraft.create_node, figcraft.inspect_document + +When: the user wants to set up a design system with colors and a button component. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.new_document +3. call_tool tool=figcraft.run_command command=variable.createCollection params=name=Core colours\nmodes=[Light,Dark] +4. call_tool tool=figcraft.run_command command=variable.create params=name=color/primary\nvalues={"Light":"#3B5BDB","Dark":"#2F4BC0"} +5. call_tool tool=figcraft.create_node type=frame name=Button props=layout=horizontal\nmainAlign=center\npadding=[12,20,12,20]\ncornerRadius=8\nfill=#3B5BDB +6. call_tool tool=figcraft.run_command command=component.create params=id=2 +Check: figcraft.inspect_document shows the collection, the styles and the component. +Gotchas: Adapted from figcraft@v0.18.1 prompts.rs design_system. Make the swatch or text layers first, then style.create from their ids; make a secondary variant, then component.combineVariants; figcraft.list_commands query=variable shows the exact params. + +## Design a landing page +slug: design-a-landing-page +summary: Build a desktop marketing page: nav, hero, features, CTA and footer. +keywords: landing page, website, marketing, hero, nav, footer, section +tools: desktop.open_app, figcraft.new_document, figcraft.create_node, figcraft.set_properties, figcraft.batch, figcraft.inspect_document + +When: the user wants a landing page or marketing website designed. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.new_document +3. call_tool tool=figcraft.create_node type=frame x=0 y=0 width=1440 height=2400 name=Landing props=fill=#FFFFFF\nlayout=vertical\ngap=0 +4. call_tool tool=figcraft.create_node parent=1 type=frame name=Nav props=layout=horizontal\nmainAlign=spaceBetween\npadding=[20,80,20,80]\nsizingH=fill +5. call_tool tool=figcraft.create_node parent=1 type=frame name=Hero props=layout=vertical\nmainAlign=center\npadding=120\ngap=24\nsizingH=fill +6. call_tool tool=figcraft.set_properties ids=1 props=sizingV=hug +Check: figcraft.inspect_document depth=2 shows the sections under the Landing frame. +Gotchas: Adapted from figcraft@v0.18.1 prompts.rs landing_page. Features cards: cornerRadius=16, padding=32, a soft dropShadow effect, each sizingH=fill; a CTA band filled with the accent (default #7048E8) and white text; use figcraft.batch to style several cards in one undo step. + +## Wire a prototype flow +slug: wire-a-prototype-flow +summary: Connect screens with click interactions and add a flow start. +keywords: prototype, flow, interaction, click, navigate, transition, screens +tools: desktop.open_app, figcraft.new_document, figcraft.run_command, figcraft.get_node, figcraft.inspect_document + +When: the user wants screens connected into a clickable prototype. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.new_document +3. call_tool tool=figcraft.run_command command=frame.create params=preset=iPhone 16\nx=0\ny=0\nname=Home +4. call_tool tool=figcraft.run_command command=proto.interaction.add params=id=5\ntrigger={"type":"onClick"}\naction={"type":"navigate","dest":9}\ntransition={"type":"smartAnimate"}\ndurationMs=300 +5. call_tool tool=figcraft.run_command command=proto.flow.add params=start=1\nname=Main flow +6. call_tool tool=figcraft.get_node id=5 depth=1 +Check: step 6 shows the interactions on the button; figcraft.inspect_document shows the page flows. +Gotchas: Adapted from figcraft@v0.18.1 prompts.rs prototype_flow. id and dest are layer ids from inspect; transitions: instant, dissolve, smartAnimate, moveIn, push, slideIn; add a back button on later screens with action {"type":"back"}. + +## Fix the open comments +slug: fix-open-comments +summary: Read the open comment threads, fix each one, reply and resolve it. +keywords: comments, feedback, review, resolve, reply, fix notes +tools: desktop.open_app, figcraft.inspect_document, figcraft.run_command, figcraft.get_node, figcraft.set_properties, figcraft.batch + +When: the user wants the open review comments addressed in the design. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.inspect_document +3. call_tool tool=figcraft.run_command command=comment.list params=page=all\nfilter=open +4. call_tool tool=figcraft.get_node id=7 depth=2 +5. call_tool tool=figcraft.set_properties ids=7 props=fontSize=24 +6. call_tool tool=figcraft.run_command command=comment.reply params=id=12\ntext=Increased the title size to 24\nauthor=AI +7. call_tool tool=figcraft.run_command command=comment.resolve params=id=12 +Check: figcraft.comment.list via run_command shows the thread resolved and the fix in the layer. +Gotchas: Adapted from figcraft@v0.18.1 prompts.rs fix_comments. Reply before resolving (a reply reopens the thread); verify with get_node (this pack has no screenshot tool); put one thread's edits in one figcraft.batch; leave ambiguous threads open with a question, never resolved. + +## Create a shape layer +slug: create-a-shape-layer +summary: Create a rectangle, ellipse or other shape, styled in one pass. +keywords: shape, rectangle, box, ellipse, circle, corner radius, fill +tools: desktop.open_app, figcraft.inspect_document, figcraft.create_node, figcraft.set_properties, figcraft.get_node + +When: the user wants a simple shape added to the design. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.inspect_document +3. call_tool tool=figcraft.create_node type=rectangle x=40 y=40 width=200 height=120 name=Card props=cornerRadius=12 +4. call_tool tool=figcraft.set_properties ids=5 props=fill=#3B5BDB\nopacity=0.9 +5. call_tool tool=figcraft.get_node id=5 depth=1 +Check: step 5 shows the fill and corner radius on the new layer. +Gotchas: change the type, position and size; ids in step 4 is the id from step 3; text= on a text layer types its characters. + +## Style the selection +slug: style-the-selection +summary: Style the selected layers: fill, stroke, corner radius, layout. +keywords: style, fill, color, stroke, layout, spacing, selection +tools: desktop.open_app, figcraft.inspect_document, figcraft.select, figcraft.set_properties, figcraft.undo + +When: the user wants the selected layers restyled in one call. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.inspect_document +3. call_tool tool=figcraft.select ids=3, 4 +4. call_tool tool=figcraft.set_properties props=fill=#3B5BDB\ncornerRadius=8 +Check: figcraft.inspect_document shows the new properties on both layers. +Gotchas: set_properties acts on the selection when ids= is omitted; auto layout keys like layout and gap only apply to frames, components and instances; figcraft.undo takes back the step. + +## Export the design +slug: export-the-design +summary: Export the selection or the page as png, svg or the file as fig. +keywords: export, png, svg, download, image, share +tools: desktop.open_app, figcraft.export, figcraft.select + +When: the user wants an image or svg of the design, or the file itself. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.select ids=1 +3. call_tool tool=figcraft.export format=svg +Check: the result carries the svg text (or base64 data for raster formats) plus the format. +Gotchas: ids= exports those layers composited; scale= multiplies raster output (default 1); format=fig exports the whole file; without a file path the data comes back in the result. + +## Open a document from Files +slug: open-a-document-from-files +summary: Open a FigCraft document that is stored in Files in the editor. +keywords: open, load, from files, figcraft, document, import, fig +tools: desktop.open_app, figcraft.open_file + +When: the user wants to open a FigCraft document that is stored in Files. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.open_file path=/FigCraft/app.figcraft +Check: the result's opened field names the document; figcraft.inspect_document shows the open document. +Gotchas: change path= to the Files path of a .figcraft document; the document opens alongside the open ones; while the open document has unsaved changes the app asks first whether to keep them. + +## Save a copy of the design to Files +slug: save-a-design-copy-to-files +summary: Save the active FigCraft document as a .figcraft file in Files. +keywords: save, copy, to files, figcraft, export, keep, fig, write +tools: desktop.open_app, figcraft.save_copy + +When: the user wants to keep a copy of the active design in Files. +Steps: +1. call_tool tool=desktop.open_app app=figcraft +2. call_tool tool=figcraft.save_copy path=/FigCraft/app.figcraft +Check: the result has the saved Files path and size; files.info on that path shows the same size. +Gotchas: change path=; FigCraft saves .figcraft files, so a target with another extension is refused with the .figcraft path as the fix; if the path exists the tool errors, so choose another name or pass overwrite=true (which is destructive). diff --git a/agent/apps/figcraft/tools.js b/agent/apps/figcraft/tools.js new file mode 100644 index 0000000..ea45d95 --- /dev/null +++ b/agent/apps/figcraft/tools.js @@ -0,0 +1,400 @@ +// Ported from storytold/figcraft@v0.18.1 crates/mcp/src/tools.rs (MIT OR Apache-2.0). Tool names, descriptions and the control-method mapping follow that table; arguments are flattened for small models (props and params are key=value lines). +// The tools run in Buddy's frame and drive the FigCraft page API through ctx.craft, +// which the runtime wires as id => craftApi(await ctx.host.appWindow(id), id) (plan 9). +import { ToolError, callLine, closest } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { teachApp } from '../../shared/craft.js'; +import { filesCall, openAndAwait, readOpenFile, saveBytesCopy } from '../../shared/craft-files.js'; +import { releases } from '../../../scripts/pc/craft/releases.mjs'; + +const APP = 'figcraft'; +const NEEDS = ['host', 'app:figcraft']; +// run_command/batch ids that destroy or replace data, from the engine command registry +// (crates/engine/src/cmd): effectFor marks those calls destructive, so the policy asks. +// file.new is not listed: the web app holds a document list (session docs/active) and the +// new document becomes active while the others stay (lead live gate, destructive=false). +const DESTRUCTIVE = ['file.close', 'edit.delete', 'page.delete', 'style.delete', 'variable.delete', 'comment.delete', 'version.delete']; +// The web app can run with no open document (engine error.rs: "no open document"); with +// none open the engine commands reject with that wording and the page rejects the call +// (the control protocol ok:false, craft-libs page.rs). teachApp turns it into the +// teaching error below, whose fix creates the document. +const NO_DOC = { message: 'FigCraft has no document open.', fix: callLine('figcraft.new_document') }; + +/** tools.rs pick(): copy the listed keys (when present) into a params object. */ +const pick = (args, keys) => { + const out = {}; + for (const key of keys) if (args[key] !== undefined) out[key] = args[key]; + return out; +}; + +// A key=value value: booleans, numbers, a [ ... ] or { ... } JSON value, else a string. +const parseValue = raw => { + if (/^(true|false)$/i.test(raw)) return raw.toLowerCase() === 'true'; + if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw); + if (raw.startsWith('[') || raw.startsWith('{')) { + try { return JSON.parse(raw); } catch { /* not JSON: keep as text */ } + } + return raw; +}; + +// key=value lines -> object (the generic long-tail form for params and props). +const parseParams = text => { + const out = {}; + for (const line of String(text ?? '').split('\n')) { + const row = line.trim(); + if (!row) continue; + const eq = row.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad params line "${row}": use key=value`, ''); + out[row.slice(0, eq).trim()] = parseValue(row.slice(eq + 1).trim()); + } + return out; +}; + +// A batch step "id k=v k2=v2": the id, then space-separated key=value tokens (no spaces in values). +const parseStep = line => { + const text = String(line ?? '').trim(); + const out = { command: '', params: {} }; + if (!text) return null; + const sp = text.indexOf(' '); + out.command = sp < 0 ? text : text.slice(0, sp); + for (const token of sp < 0 ? [] : text.slice(sp + 1).split(/\s+/)) { + const eq = token.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad batch step "${text}": params are key=value tokens`, ''); + out.params[token.slice(0, eq)] = parseValue(token.slice(eq + 1)); + } + return out; +}; + +export const pack = { id: APP, title: 'FigCraft' }; + +export const tools = [ + { + name: 'figcraft.list_commands', + purpose: 'Find design commands by a word in the id, label or menu.', + when: 'Use when the user wants a menu, panel or shortcut action and its id is unknown.', + params: { query: { type: 'string', description: 'Substring of the id, label, menu path or parameter doc; omit to list the first 10' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { query: 'align' }, says: 'Which commands align layers?' }], + // Generic tool (plan 9): the top 10 of the live commands() filtered as tools.rs:584-625 + run: async (args, ctx) => { + const all = await (await ctx.craft(APP)).commands(); + const q = String(args.query ?? '').trim().toLowerCase(); + return all.filter(command => !q || ['id', 'label', 'menu', 'params'].some(key => String(command[key] ?? '').toLowerCase().includes(q))) + .slice(0, 10).map(command => ({ id: command.id, label: command.label, menu: command.menu, params: command.params })); + }, + }, + { + name: 'figcraft.run_command', + purpose: 'Run any FigCraft command by id with parameters.', + when: `Use when a menu, panel or shortcut action is wanted by id; ${DESTRUCTIVE.join(', ')} are destructive, so ask first.`, + params: { + command: { type: 'string', required: true, description: 'Command id from figcraft.list_commands, e.g. node.create, align.left, file.export' }, + params: { type: 'text', description: 'Parameters as key=value lines, one per line; a [ ... ] or { ... } value is JSON; omit for the defaults' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(prefix => String(args.command ?? '').startsWith(prefix)) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { command: 'align.left', params: 'ids=3, 4' }, says: 'Left-align the selected layers' }], + // tools.rs:627-637 engine.execute; unknown ids get invalid_argument with the 3 closest + run: async (args, ctx) => { + const app = teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix); + const all = await app.commands(); + if (!all.some(command => command.id === args.command)) { + const near = closest(args.command, all.map(command => command.id), 3); + const fix = near.length > 0 ? callLine('figcraft.run_command', { command: near[0] }) : ''; + throw new ToolError('invalid_argument', `unknown command "${args.command}"${near.length > 0 ? `; closest: ${near.join(', ')}` : ''}`, fix); + } + return app.execute(args.command, parseParams(args.params)); + }, + }, + { + name: 'figcraft.new_document', + purpose: 'Create a new blank document and switch to it.', + when: 'Use when the user wants a blank design, or when no document is open.', + params: { name: { type: 'string', description: 'Document name' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { name: 'App' }, says: 'Start a blank document called App' }], + // file.new {name?} (engine command registry, edit.rs): the web app holds a document + // list (session docs/active; engine error.rs NoDocument) and the new document becomes + // active while the others stay, so it is not destructive (lead live gate) + run: async (args, ctx) => (await ctx.craft(APP)).execute('file.new', pick(args, ['name'])), + }, + { + name: 'figcraft.batch', + purpose: 'Run several commands in order as one undo step.', + when: 'Use when several edits should be one undo step, or build from earlier results is not needed.', + params: { + commands: { type: 'list', required: true, description: 'One step per item: the command id then key=value tokens, e.g. node.create type=text text=Hi' }, + label: { type: 'string', description: 'Undo history label (default Batch)' }, + on_error: { type: 'enum', values: ['abort', 'continue'], description: 'abort (default) rolls back the whole batch on the first failure; continue runs the rest' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(id => (args.commands ?? []).some(line => String(line ?? '').trim().startsWith(id))) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { commands: ['node.create type=frame width=375 height=812 name=Login', 'node.create type=text text=Hi'], label: 'Login screen' }, says: 'Create a frame and a text as one undo step' }], + // tools.rs:639-666 one engine command.batch (one undo step); the as/$ref step + // references are dropped: later steps cannot use earlier results (note in report). + run: async (args, ctx) => { + const steps = (args.commands ?? []).map(parseStep).filter(step => step !== null); + if (steps.length === 0) throw new ToolError('invalid_argument', 'commands needs at least one step', ''); + const params = { label: args.label ?? 'Batch', commands: steps }; + if (args.on_error !== undefined) params.onError = args.on_error; + return teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).execute('command.batch', params); + }, + }, + { + name: 'figcraft.create_node', + purpose: 'Create a layer: frame, shape, text, section or component.', + when: 'Use when the user wants a new layer added to the design.', + params: { + type: { type: 'enum', required: true, values: ['frame', 'rectangle', 'ellipse', 'polygon', 'star', 'line', 'arrow', 'text', 'vector', 'section', 'component', 'slice'], description: 'Layer type' }, + x: { type: 'number', description: 'Left, relative to the parent frame (default 0)' }, + y: { type: 'number', description: 'Top, relative to the parent frame (default 0)' }, + width: { type: 'number', description: 'Width (default 100)' }, + height: { type: 'number', description: 'Height (default 100)' }, + parent: { type: 'integer', description: 'Parent frame or group id; the current page when omitted' }, + index: { type: 'integer', description: 'Z-index among the parent children; on top when omitted' }, + name: { type: 'string', description: 'Layer name' }, + text: { type: 'string', description: 'Characters, for type text' }, + select: { type: 'boolean', description: 'Select the new layer (default true)' }, + props: { type: 'text', description: 'Properties as key=value lines, e.g. fill=#3366FF cornerRadius=12 fontSize=24 layout=vertical gap=8' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { type: 'frame', width: 375, height: 812, name: 'Login', props: 'fill=#FFFFFF\nlayout=vertical\ngap=16' }, says: 'Create a phone frame called Login' }], + // tools.rs:668-693 node.create, then node.get {id, depth:0} for the new layer + run: async (args, ctx) => { + const app = teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix); + const params = pick(args, ['type', 'x', 'y', 'width', 'height', 'parent', 'index', 'name', 'text', 'select']); + const props = parseParams(args.props); + if (Object.keys(props).length > 0) params.props = props; + const result = await app.execute('node.create', params); + const id = result.id; + if (id === undefined) throw new ToolError('app_error', 'node.create returned no id', ''); + const node = await app.request('node.get', { id, depth: 0 }); + return { id, node }; + }, + }, + { + name: 'figcraft.set_properties', + purpose: 'Set properties on one or more layers: fill, layout, text, effects.', + when: 'Use when the user wants to style, move or resize layers.', + params: { + ids: { type: 'list', description: 'Layer ids; the selection when omitted' }, + props: { type: 'text', required: true, description: 'Properties as key=value lines, e.g. fill=#3366FF cornerRadius=12 x=10 y=20 fontSize=24 layout=vertical gap=8' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { ids: [3, 4], props: 'fill=#3B5BDB\nopacity=0.9' }, says: 'Make both layers blue' }], + // tools.rs:694-720 node.set; ids arrive as strings from flat calls, the engine wants numbers + run: async (args, ctx) => { + const params = { props: parseParams(args.props) }; + if (args.ids !== undefined) params.ids = args.ids.map(value => Number(value)); + return teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).execute('node.set', params); + }, + }, + { + name: 'figcraft.inspect_document', + purpose: 'Show the document: pages, selection, layer tree, styles, undo.', + when: 'Use when the user asks what is in the design, or to verify a change.', + params: { + depth: { type: 'integer', description: 'Layer tree depth for the current page (default 4)' }, + all_pages: { type: 'boolean', description: 'Expand every page, not only the current one' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is in this design?' }, { args: { depth: 2 }, says: 'Show the top two levels of layers' }], + // tools.rs:794-814 document.inspect; upstream always sends depth (default 4) and allPages + run: async (args, ctx) => (await ctx.craft(APP)).request('document.inspect', { depth: args.depth ?? 4, allPages: args.all_pages ?? false }), + }, + { + name: 'figcraft.get_node', + purpose: 'Show one layer as JSON with its children to a depth.', + when: 'Use when the user asks about one layer, or the document tree was too deep.', + params: { + id: { type: 'integer', required: true, description: 'Layer id' }, + depth: { type: 'integer', description: 'Child depth (default 1)' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { id: 4 }, says: 'Show layer 4 and its children' }], + // tools.rs:867 node.get; upstream always sends id and depth (default 1); offset is + // client-side pagination (tools.rs node_at), never sent on the wire + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).request('node.get', { id: args.id, depth: args.depth ?? 1 }), + }, + { + name: 'figcraft.select', + purpose: 'Replace the selection with the given layer ids.', + when: 'Use when the user wants to select layers before styling or deleting them.', + params: { ids: { type: 'list', required: true, description: 'Layer ids to select; empty deselects everything' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { ids: [3, 4] }, says: 'Select layers 3 and 4' }], + // tools.rs:1020-1029 select.set (or select.none), then document.inspect {depth:0} for the selection + run: async (args, ctx) => { + const app = teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix); + const ids = (args.ids ?? []).map(value => Number(value)); + if (ids.length === 0) await app.execute('select.none', {}); + else await app.execute('select.set', { ids }); + const doc = await app.request('document.inspect', { depth: 0 }); + return { selection: doc.selection ?? null }; + }, + }, + { + name: 'figcraft.export', + purpose: 'Export layers as png, svg, pdf or the whole file as fig.', + when: 'Use when the user wants an image or svg of the design.', + params: { + ids: { type: 'list', description: 'Layers to export; the selection, then the page, when omitted' }, + format: { type: 'enum', values: ['png', 'jpg', 'svg', 'webp', 'pdf', 'xml', 'fig'], description: 'Format (default png)' }, + scale: { type: 'number', description: 'Pixel scale for raster formats (default 1)' }, + size: { type: 'string', description: 'Instead of scale: 2x, or a width or height like 512w' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { format: 'svg' }, says: 'Export the selection as SVG' }], + // tools.rs:1031-1075 file.export. Upstream marks it read-only; without a path the + // result comes back as data (raster base64, svg as text) instead of a file. + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).execute('file.export', { ...pick(args, ['format', 'scale', 'size']), ...(args.ids !== undefined ? { ids: args.ids.map(value => Number(value)) } : {}) }), + }, + { + name: 'figcraft.undo', + purpose: 'Undo the last change in the design.', + when: 'Use when the user wants to undo, or take back the last edit.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Undo that' }], + // tools.rs:572 edit.undo + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).execute('edit.undo', {}), + }, + { + name: 'figcraft.redo', + purpose: 'Redo the last undone change.', + when: 'Use when the user wants to redo, or bring back the change they just undid.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Bring that back' }], + // tools.rs:573 edit.redo + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).execute('edit.redo', {}), + }, + { + name: 'figcraft.key', + purpose: 'Press a key or shortcut as if typed on the canvas.', + when: 'Use when the user wants a menu shortcut, a tool key or a nudge.', + params: { + key: { type: 'string', required: true, description: 'Key: a letter/digit, Escape, Delete, Backspace, Enter, ArrowLeft...' }, + shift: { type: 'boolean', description: 'Shift held' }, + alt: { type: 'boolean', description: 'Alt/Option held' }, + cmd: { type: 'boolean', description: 'Cmd/Ctrl held' }, + ctrl: { type: 'boolean', description: 'Ctrl held (the Control key on macOS)' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { key: 'G', cmd: true }, says: 'Group the selection with the shortcut' }], + // tools.rs:1209-1215 ui.key with the key plus the mods + run: async (args, ctx) => teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix).request('ui.key', { key: args.key, ...pick(args, ['shift', 'alt', 'cmd', 'ctrl']) }), + }, + { + name: 'figcraft.type_text', + purpose: 'Type into a text layer, replacing its contents when id is given.', + when: 'Use when the user wants to set or append text on a text layer.', + params: { + text: { type: 'string', required: true, description: 'Text to type (\\n for a new line)' }, + id: { type: 'integer', description: 'Text layer to replace the contents of; the active editor when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { id: 4, text: 'New title' }, says: 'Replace the text in layer 4' }], + // tools.rs:1217-1233: with id, text.edit.begin, ui.type, text.edit.end (always) and node.get; + // without id, ui.type at the caret + run: async (args, ctx) => { + const app = teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix); + if (args.id === undefined) return app.request('ui.type', { text: args.text }); + const id = Number(args.id); + await app.execute('text.edit.begin', { id }); + let typed; + try { + typed = await app.request('ui.type', { text: args.text }); + } finally { + await app.execute('text.edit.end', {}).catch(() => {}); + } + const node = await app.request('node.get', { id, depth: 0 }); + return { ok: true, node, typed }; + }, + }, + { + name: 'figcraft.inspect_ui', + purpose: 'Show the UI state: tool, view, panels, status.', + when: 'Use when the user asks what tool is active or the current zoom.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What tool is selected?' }], + // tools.rs:577 ui.inspect + run: async (args, ctx) => (await ctx.craft(APP)).request('ui.inspect', {}), + }, + { + name: 'figcraft.open_file', + purpose: 'Open a FigCraft document from Files.', + when: 'Use when the user wants a FigCraft file from Files. Not for opening the app itself; that is desktop.open_app.', + params: { path: { type: 'path', required: false, description: 'A Files path to a .figcraft document or an import format (.fig, .json, .svg or image)' } }, + effect: 'change', + needs: ['host', 'app:figcraft', 'files'], + examples: [{ args: { path: '/FigCraft/app.figcraft' }, says: 'Open the app design from Files' }], + // Drives the wrapper's own #file input (app.mjs:38), so the open posts from the wrapper + // realm, as the page's host bridge requires (craft-libs web-host web.rs:106). The + // document opens alongside the open ones (the engine holds a document list), so a + // change. openAndAwait waits until the page's docInspect changes, so the result + // confirms the document loaded. + run: async (args, ctx) => { + const file = await readOpenFile(ctx, args.path, { id: APP, title: 'FigCraft' }); + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + return openAndAwait(craft, { id: APP, title: 'FigCraft', wrapperWindow: wrapper, name: file.name, bytes: file.bytes, accept: releases[APP].accept }); + }, + }, + { + name: 'figcraft.save_copy', + purpose: 'Save the active FigCraft document as a file in Files.', + when: 'Use when the user wants to keep a copy of the design in Files.', + params: { + path: { type: 'path', required: true, description: 'The Files path to write the copy to, e.g. /FigCraft/app.figcraft' }, + overwrite: { type: 'boolean', description: 'Replace the file when the path already exists; false when omitted' }, + }, + effect: 'change', + effectFor: args => (args.overwrite ? 'destructive' : 'change'), + needs: ['host', 'app:figcraft', 'files'], + examples: [{ args: { path: '/FigCraft/app.figcraft' }, says: 'Save a copy of the design to Files' }], + // No path is ever passed (the browser has no file system). file.saveAs {data: true} + // answers with the bytes inline (engine cmd/file/save.rs save_to None: {name, bytes, + // data}); the channel returns that result, and the page's download path (ui-egui + // app/files.rs:42-49) is a UI-only route, so nothing downloads. The bytes are the + // native .figcraft format, so a target with another extension is refused with a fix. + run: async (args, ctx) => { + const wrapper = await ctx.host.appWindow(APP); + const app = teachApp(await ctx.craft(APP), NO_DOC.message, NO_DOC.fix); + const save = await saveBytesCopy(app, { + id: APP, title: 'FigCraft', wrapperWindow: wrapper, target: args.path, + tool: 'figcraft.save_copy', nativeExt: '.figcraft', inlineCommand: { command: 'file.saveAs', params: { data: true } }, + }); + const written = await filesCall( + ctx, + files => files.writeBytes(args.path, save.bytes, { overwrite: Boolean(args.overwrite) }), + error => (error.code === 'exists' ? callLine('figcraft.save_copy', { path: args.path, overwrite: true }) : ''), + ); + return { path: written.path, name: save.name, size: written.size, created: written.created, ...(save.note ? { note: save.note } : {}) }; + }, + }, +]; + +// Live-check exports (brief): every command id the curated tools pass to execute, +// and every control method passed to request. run_command and batch also pass +// arbitrary ids from the live commands() list. +export const usesCommands = [ + 'command.batch', 'file.new', 'node.create', 'node.set', 'file.export', 'edit.undo', 'edit.redo', + 'text.edit.begin', 'text.edit.end', 'select.set', 'select.none', 'file.saveAs', +]; +export const usesMethods = ['node.get', 'document.inspect', 'ui.key', 'ui.type', 'ui.inspect']; diff --git a/agent/apps/filmcraft/skills.md b/agent/apps/filmcraft/skills.md new file mode 100644 index 0000000..f436f9f --- /dev/null +++ b/agent/apps/filmcraft/skills.md @@ -0,0 +1,133 @@ +## Open the demo project +slug: open-a-demo-project +summary: Open the built-in demo project with sample media. +keywords: demo, sample, start, example, project, show me +tools: desktop.open_app, filmcraft.open_demo, filmcraft.inspect + +When: the user wants to see FilmCraft working with media. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.open_demo +Check: filmcraft.inspect lists the demo bins and the active sequence. +Gotchas: opening the demo replaces the open project, so confirm first when there are unsaved edits. + +## Look at the project and the timeline +slug: look-at-the-project +summary: Inspect the bins, the media and what is on the timeline. +keywords: inspect, timeline, bins, clips, media, what is in +tools: desktop.open_app, filmcraft.inspect, filmcraft.sequence_inspect + +When: the user asks what is in the project or on the timeline. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.inspect +3. call_tool tool=filmcraft.sequence_inspect +Check: the project tree lists bins with item ids and the sequence lists tracks and clips. +Gotchas: item ids and clip ids in the reply are what filmcraft.place, filmcraft.move and filmcraft.apply_effect take. + +## Move the playhead +slug: move-the-playhead +summary: Put the playhead at a second, frame or timecode. +keywords: playhead, seek, jump, scrub, time, go to +tools: desktop.open_app, filmcraft.playhead, filmcraft.sequence_inspect + +When: the user wants the playhead at a specific time. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.playhead seconds=3.5 +Check: filmcraft.sequence_inspect shows the playhead at the new time. +Gotchas: frame= and timecode= are alternatives to seconds=; filmcraft.undo takes the playhead back. + +## Cut a clip at the playhead +slug: cut-at-the-playhead +summary: Razor-cut a track or one clip at the playhead or a time. +keywords: razor, cut, split, slice, trim point, cut at +tools: desktop.open_app, filmcraft.playhead, filmcraft.razor + +When: the user wants a cut at the playhead or at a given time. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.playhead seconds=4 +3. call_tool tool=filmcraft.razor track=V1 +Check: the reply says how many cuts were made; filmcraft.sequence_inspect lists the new clips. +Gotchas: clip= cuts one clip instead of whole tracks; the cut time is the playhead when seconds=, frame= and timecode= are all omitted. + +## Put media on the timeline +slug: put-media-on-the-timeline +summary: Place a project item onto a video or audio track at a time. +keywords: place, insert, add clip, media, bin, timeline, drop +tools: desktop.open_app, filmcraft.project_inspect, filmcraft.place + +When: the user wants a clip from the bins onto the timeline. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.project_inspect +3. call_tool tool=filmcraft.place item=3 track=V1 seconds=5 +Check: filmcraft.sequence_inspect lists the new clip on the track at the right start. +Gotchas: track=new or audioTrack=new adds a track; source_in= and duration= skip and limit media; video=false or audio=false places only one stream. + +## Rearrange clips on the timeline +slug: rearrange-clips +summary: Move clips to new track and time positions. +keywords: move, drag, rearrange, reorder, track, reposition +tools: desktop.open_app, filmcraft.move, filmcraft.sequence_inspect + +When: the user wants clips moved around on the timeline. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.move moves=[{"clip":5,"track":"V2","seconds":10}] +Check: filmcraft.sequence_inspect shows the clip on its new track at the new time. +Gotchas: track=new moves a clip to a new track; copy=true moves copies and keeps the originals; linked=true brings linked sound and picture along. + +## Apply an effect to a clip +slug: apply-an-effect +summary: List the effects, then apply one to the selected clips. +keywords: effect, blur, color, grade, transition, apply, filter +tools: desktop.open_app, filmcraft.apply_effect, filmcraft.sequence_inspect + +When: the user wants an effect on a clip, or the list of effects. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.apply_effect +3. call_tool tool=filmcraft.apply_effect effect=Gaussian Blur +Check: filmcraft.sequence_inspect lists the effect on the clip. +Gotchas: step 2 returns the catalogue (kind= narrows it to Video, Audio or a transition kind); effect= takes an id or a display name; clips= names the clips, the selection when omitted. + +## Find and run any command +slug: run-any-editing-command +summary: Look up a FilmCraft command by name, then run it with parameters. +keywords: command, run, menu, what can it do, markers, history +tools: desktop.open_app, filmcraft.list_commands, filmcraft.run_command + +When: the user wants an action that has no dedicated tool. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.list_commands query=marker +3. call_tool tool=filmcraft.run_command command=playhead.set params=seconds=2 +Check: filmcraft.sequence_inspect shows the action took effect. +Gotchas: run_command takes key=value lines in params= (a [ ... ] or { ... } value is JSON); file.newProject, project.delete, sequence.lift and the markers.clear ids are destructive, so ask the user first. +## Open a project or media from Files +slug: open-a-project-from-files +summary: Open a .fcproj project or import media that is stored in Files. +keywords: open, load, from files, fcproj, project, import, media +tools: desktop.open_app, filmcraft.open_file + +When: the user wants to open a project or import media that is stored in Files. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.open_file path=/FilmCraft/talk.fcproj +Check: the result has an opened field confirming the load; filmcraft.inspect shows the open project. +Gotchas: change path= to a .fcproj project or media (video, audio, image); opening a project replaces the open one, so ask the user first if the current project has unsaved work. + +## Save a copy of the project to Files +slug: save-a-project-copy-to-files +summary: Save the active FilmCraft project as a .fcproj file in Files. +keywords: save, copy, to files, fcproj, export, keep, write +tools: desktop.open_app, filmcraft.save_copy + +When: the user wants to keep a copy of the active project in Files. +Steps: +1. call_tool tool=desktop.open_app app=filmcraft +2. call_tool tool=filmcraft.save_copy path=/FilmCraft/talk.fcproj +Check: the result has the saved Files path and size; files.info on that path shows the same size. +Gotchas: change path=; FilmCraft saves .fcproj files, so a target with another extension is refused with the .fcproj path as the fix; if the path exists the tool errors, so choose another name or pass overwrite=true (which is destructive); a fresh project with no saved path yet makes the app refuse the save. diff --git a/agent/apps/filmcraft/tools.js b/agent/apps/filmcraft/tools.js new file mode 100644 index 0000000..15c5296 --- /dev/null +++ b/agent/apps/filmcraft/tools.js @@ -0,0 +1,486 @@ +// Ported from storytold/filmcraft@v0.20.1 crates/automation/src/server.rs (the #[tool] table) +// and crates/engine/src/commands.rs (the command registry, 254016000000 ticks per second). +// Tool names, descriptions and the control-method mapping follow those tables; arguments are +// flattened for small models. +// The tools run in Buddy's frame and drive the FilmCraft page API through ctx.craft, which the +// runtime wires as id => craftApi(await ctx.host.appWindow(id), id) (plan 9). +import { ToolError, callLine, closest } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { filesCall, openAndAwait, readOpenFile, saveBytesCopy } from '../../shared/craft-files.js'; +import { releases } from '../../../scripts/pc/craft/releases.mjs'; + +const APP = 'filmcraft'; +const NEEDS = ['host', 'app:filmcraft']; +// run_command/batch ids that destroy or replace data, from the engine command registry +// (crates/engine/src/commands.rs cmd! table): effectFor marks those calls destructive, so the +// policy asks. file.newProject and file.openDemoProject replace the open project (the web app +// holds one project), so they are destructive though the registry does not flag them. +const DESTRUCTIVE = [ + 'file.newProject', 'file.openDemoProject', 'file.revert', 'file.discardRecovery', + 'project.delete', 'sequence.deleteTrack', 'sequence.lift', 'sequence.extract', + 'edit.rippleDeleteHead', 'markers.clearAll', 'markers.clearCurrent', 'markers.clearIn', + 'markers.clearOut', 'markers.clearInOut', 'sequence.removeTransition', + 'history.clear', 'history.deleteRedoable', 'effects.remove', 'effects.deleteKeyframe', + 'colors.removeCustom', +]; + +/** commands.rs pick(): copy the listed keys (when present) into a params object. */ +const pick = (args, keys) => { + const out = {}; + for (const key of keys) if (args[key] !== undefined) out[key] = args[key]; + return out; +}; + +// A key=value value: booleans, numbers, a [ ... ] or { ... } JSON value, else a string. +const parseValue = raw => { + if (/^(true|false)$/i.test(raw)) return raw.toLowerCase() === 'true'; + if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw); + if (raw.startsWith('[') || raw.startsWith('{')) { + try { return JSON.parse(raw); } catch { /* not JSON: keep as text */ } + } + return raw; +}; + +// key=value lines -> object (the generic long-tail form for params). +const parseParams = text => { + const out = {}; + for (const line of String(text ?? '').split('\n')) { + const row = line.trim(); + if (!row) continue; + const eq = row.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad params line "${row}": use key=value`, ''); + out[row.slice(0, eq).trim()] = parseValue(row.slice(eq + 1).trim()); + } + return out; +}; + +// A batch step "id k=v k2=v2": the id, then space-separated key=value tokens (no spaces in values). +const parseStep = line => { + const text = String(line ?? '').trim(); + const out = { command: '', params: {} }; + if (!text) return null; + const sp = text.indexOf(' '); + out.command = sp < 0 ? text : text.slice(0, sp); + for (const token of sp < 0 ? [] : text.slice(sp + 1).split(/\s+/)) { + const eq = token.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad batch step "${text}": params are key=value tokens`, ''); + out.params[token.slice(0, eq)] = parseValue(token.slice(eq + 1)); + } + return out; +}; + +// The engine's time forms (commands.rs time_p_at): a top-level seconds, frame or timecode. +// Exactly one is given, else the call runs at the playhead. +const timeArgs = args => { + const out = pick(args, ['seconds', 'frame', 'timecode']); + return out; +}; + +// Nested time forms (commands.rs tick_or_time_p): a ticks integer or a {"seconds"|"frame"| +// "timecode"} object. The pack takes seconds only and wraps it in the object form. +const nestedTime = value => (value === undefined ? undefined : { seconds: value }); + +export const pack = { id: APP, title: 'FilmCraft' }; + +export const tools = [ + { + name: 'filmcraft.inspect', + purpose: 'Show the project tree and the active sequence with ids for commands.', + when: 'Use when the user asks what is in the project, or before planning edits.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is in this project?' }], + // server.rs:402 + document() :305-313: project.inspect, then sequence.inspect of the + // activeSequence item; a sequence that fails to read comes back as null (errors swallowed) + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const project = await app.execute('project.inspect', {}); + const active = project?.activeSequence; + let sequence = null; + if (active !== undefined && active !== null) { + try { + sequence = await app.execute('sequence.inspect', { item: active }); + } catch { /* document() swallows this: the sequence is null */ } + } + return { project, sequence }; + }, + }, + { + name: 'filmcraft.project_inspect', + purpose: 'Show the project tree: bins and items with ids, types, durations.', + when: 'Use when the user asks what media is in the bins.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'List the bins and media' }], + // server.rs:420 project.inspect + run: async (args, ctx) => (await ctx.craft(APP)).execute('project.inspect', {}), + }, + { + name: 'filmcraft.sequence_inspect', + purpose: 'Show the active sequence: tracks, clips, markers, playhead, selection.', + when: 'Use when the user asks what is on the timeline.', + params: { item: { type: 'integer', description: 'Sequence item id; the active sequence when omitted' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is on the timeline?' }], + // server.rs:429 sequence.inspect (the engine reads the active sequence when item is absent) + run: async (args, ctx) => (await ctx.craft(APP)).execute('sequence.inspect', pick(args, ['item'])), + }, + { + name: 'filmcraft.ui_inspect', + purpose: 'Show the editor UI state: panels, monitors, transport.', + when: 'Use when the user asks what the app is showing.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What does the app look like right now?' }], + // server.rs:506 ui.inspect; the page installs it as uiInspect (Methods { doc_inspect: + // None, ..default() }, apps/filmcraft-web/src/api.rs:124-125), so the adapter inspect() + // maps to it via the METHODS entry + run: async (args, ctx) => (await ctx.craft(APP)).inspect({}), + }, + { + name: 'filmcraft.playhead', + purpose: 'Move the playhead to a second, frame or timecode.', + when: 'Use when the user wants the playhead at a specific time.', + params: { + seconds: { type: 'number', description: 'Seconds from sequence start (254016000000 ticks per second upstream)' }, + frame: { type: 'integer', description: 'Frame number from sequence start' }, + timecode: { type: 'string', description: 'Timecode string, e.g. 00:01:00:00' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { seconds: 3.5 }, says: 'Jump to 3.5 seconds' }], + // commands.rs:3228 playhead.set {time ticks | frame | seconds | timecode}; the pack takes + // seconds, frame or timecode (raw ticks are not exposed) + run: async (args, ctx) => { + if (args.seconds === undefined && args.frame === undefined && args.timecode === undefined) { + throw new ToolError('invalid_argument', 'give one of seconds, frame or timecode', ''); + } + return (await ctx.craft(APP)).execute('playhead.set', timeArgs(args)); + }, + }, + { + name: 'filmcraft.razor', + purpose: 'Cut a clip or a track at the playhead (or a given time).', + when: 'Use when the user wants a cut at the playhead or at a time.', + params: { + seconds: { type: 'number', description: 'Cut time in seconds; the playhead when omitted' }, + frame: { type: 'integer', description: 'Cut frame; the playhead when omitted' }, + timecode: { type: 'string', description: 'Cut timecode; the playhead when omitted' }, + track: { type: 'string', description: 'Track to cut, e.g. V1; the playhead\'s tracks when a clip is named' }, + clip: { type: 'integer', description: 'Cut this one clip instead of whole tracks' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Cut at the playhead' }], + // commands.rs:3604 timeline.razor {time (default: playhead), track?, clip?}; the clip wins + // over the track when both are given (upstream run body) + run: async (args, ctx) => (await ctx.craft(APP)).execute('timeline.razor', { ...timeArgs(args), ...pick(args, ['track', 'clip']) }), + }, + { + name: 'filmcraft.add_edit', + purpose: 'Add an edit point (marker) at the playhead or a given time.', + when: 'Use when the user wants an edit marked on the timeline.', + params: { + seconds: { type: 'number', description: 'Edit time in seconds; the playhead when omitted' }, + frame: { type: 'integer', description: 'Edit frame; the playhead when omitted' }, + timecode: { type: 'string', description: 'Edit timecode; the playhead when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Mark an edit here' }], + // commands.rs:2708 sequence.addEdit {time (default: playhead)} + run: async (args, ctx) => (await ctx.craft(APP)).execute('sequence.addEdit', timeArgs(args)), + }, + { + name: 'filmcraft.place', + purpose: 'Place a media item from the project onto a track at a time.', + when: 'Use when the user wants a clip from a bin put on the timeline.', + params: { + item: { type: 'integer', required: true, description: 'Project item id (from filmcraft.project_inspect)' }, + track: { type: 'string', description: 'Video track, e.g. V1, or new to add one' }, + audioTrack: { type: 'string', description: 'Audio track for the sound, e.g. A1, or new' }, + seconds: { type: 'number', description: 'Placement time in seconds; the playhead when omitted' }, + frame: { type: 'integer', description: 'Placement frame; the playhead when omitted' }, + timecode: { type: 'string', description: 'Placement timecode; the playhead when omitted' }, + source_in: { type: 'number', description: 'Source in point in seconds (skip media at the start)' }, + duration: { type: 'number', description: 'How many seconds to place' }, + video: { type: 'boolean', description: 'Place the picture (default true)' }, + audio: { type: 'boolean', description: 'Place the sound (default true)' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { item: 3, track: 'V1', seconds: 5 }, says: 'Put item 3 on V1 at 5 seconds' }], + // commands.rs place_one :1230+: timeline.place {item, track?, audioTrack?, time?, sourceIn?, + // duration?, video?, audio?}. timeline.place is an internal command: it is not in the + // command.list registry, so this tool runs it directly (run_command cannot reach it) + run: async (args, ctx) => { + const params = { item: args.item, ...timeArgs(args), ...pick(args, ['track', 'audioTrack', 'video', 'audio']) }; + if (args.source_in !== undefined) params.sourceIn = { seconds: args.source_in }; + if (args.duration !== undefined) params.duration = { seconds: args.duration }; + return (await ctx.craft(APP)).execute('timeline.place', params); + }, + }, + { + name: 'filmcraft.move', + purpose: 'Move clips to new track and time positions on the timeline.', + when: 'Use when the user wants clips rearranged on the timeline.', + params: { + moves: { type: 'text', required: true, description: 'JSON array, one object per move: {"clip": id, "track": "V1"|"A1"|"new", "seconds": n?}' }, + copy: { type: 'boolean', description: 'Move copies instead of the clips (option-drag)' }, + linked: { type: 'boolean', description: 'Bring linked partners along (default: the Linked Selection setting)' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { moves: '[{"clip":5,"track":"V2","seconds":10}]' }, says: 'Move clip 5 to V2 at 10 seconds' }], + // commands.rs move_clips :534+: timeline.move {moves: [{clip, track, time?}], copy?, linked?}. + // Internal command (not in the command.list registry): run directly, not via run_command + run: async (args, ctx) => { + let moves; + try { + moves = JSON.parse(args.moves); + } catch { + throw new ToolError('invalid_argument', 'moves must be a JSON array of {clip, track, seconds?} objects', ''); + } + if (!Array.isArray(moves) || moves.length === 0) { + throw new ToolError('invalid_argument', 'moves needs at least one {clip, track} item', ''); + } + moves = moves.map(entry => { + if (entry?.clip === undefined || entry?.track === undefined) { + throw new ToolError('invalid_argument', 'each move needs a clip and a track', ''); + } + const out = { clip: entry.clip, track: entry.track }; + if (entry.seconds !== undefined) out.time = { seconds: entry.seconds }; + return out; + }); + const params = { moves, ...pick(args, ['copy', 'linked']) }; + return (await ctx.craft(APP)).execute('timeline.move', params); + }, + }, + { + name: 'filmcraft.apply_effect', + purpose: 'Apply an effect (blur, color, transition, ...) to clips.', + when: 'Use when the user wants an effect on a clip, or the list of effects.', + params: { + effect: { type: 'string', description: 'Effect id or display name, e.g. gaussian_blur or Gaussian Blur; omit for the catalogue' }, + clips: { type: 'list', description: 'Clip ids; the selection when omitted' }, + kind: { type: 'string', description: 'Catalogue filter: Video, Audio, VideoTransition or AudioTransition' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { effect: 'Gaussian Blur' }, says: 'Blur the selected clip' }], + // commands.rs:3693 effects.apply {clips?, effect} and :4199 effects.list {kind?}; the + // upstream MCP table has no effect tool, so the catalogue is folded in here (report) + run: async (args, ctx) => { + const app = await ctx.craft(APP); + if (args.effect === undefined) return app.execute('effects.list', pick(args, ['kind'])); + const params = { effect: args.effect, ...pick(args, ['clips']) }; + return app.execute('effects.apply', params); + }, + }, + { + name: 'filmcraft.new_bin', + purpose: 'Create a bin in the project.', + when: 'Use when the user wants media organised into a bin.', + params: { name: { type: 'string', required: true, description: 'Bin name' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { name: 'Interviews' }, says: 'Make an Interviews bin' }], + // commands.rs:1727 file.newBin {name, parent?} + run: async (args, ctx) => (await ctx.craft(APP)).execute('file.newBin', { name: args.name }), + }, + { + name: 'filmcraft.new_project', + purpose: 'Start a new (empty) project, replacing the open one.', + when: 'Use when the user wants to start a new project.', + params: { name: { type: 'string', description: 'Project name (required upstream)' } }, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: { name: 'Reel' }, says: 'Start a new project called Reel' }], + // commands.rs:1593 file.newProject {name}; destructive: the web app holds one project, so + // this replaces the open one + run: async (args, ctx) => { + if (args.name === undefined) throw new ToolError('invalid_argument', 'a new project needs a name', ''); + return (await ctx.craft(APP)).execute('file.newProject', { name: args.name }); + }, + }, + { + name: 'filmcraft.open_demo', + purpose: 'Open the built-in demo project, replacing the open one.', + when: 'Use when the user wants to see the app with sample media.', + params: {}, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: {}, says: 'Show me the demo project' }], + // commands.rs:1611 file.openDemoProject {}; destructive: replaces the open project + run: async (args, ctx) => (await ctx.craft(APP)).execute('file.openDemoProject', {}), + }, + { + name: 'filmcraft.undo', + purpose: 'Undo the last edit in the project.', + when: 'Use when the user wants to undo the last edit.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Undo that cut' }], + // commands.rs:2113 edit.undo + run: async (args, ctx) => (await ctx.craft(APP)).execute('edit.undo', {}), + }, + { + name: 'filmcraft.redo', + purpose: 'Redo the last undone edit.', + when: 'Use when the user wants to redo the change they just undid.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Bring that cut back' }], + run: async (args, ctx) => (await ctx.craft(APP)).execute('edit.redo', {}), // commands.rs:2114 edit.redo + }, + { + name: 'filmcraft.batch', + purpose: 'Run several commands in order; stops at the first error.', + when: 'Use when several timeline edits should happen in one go.', + params: { + commands: { type: 'list', required: true, description: 'One command per item: the id then key=value params, e.g. playhead.set seconds=3.5' }, + stop_on_error: { type: 'boolean', description: 'Stop at the first error (default true)' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(id => (args.commands ?? []).some(line => String(line ?? '').trim().startsWith(id))) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { commands: ['playhead.set seconds=3.5', 'timeline.razor track=V1'] }, says: 'Cut at 3.5 seconds on V1' }], + // server.rs:375-398: N sequential runs, stop on error by default; each edit is its own + // undo step; returns {completed, failed, results: [{ok, result | error}]} + run: async (args, ctx) => { + const app = await ctx.craft(APP); + let completed = 0; + let failed = 0; + const results = []; + for (const line of args.commands) { + const step = parseStep(line); + if (!step) continue; + try { + const result = await app.execute(step.command, step.params); + completed += 1; + results.push({ ok: true, result }); + } catch (error) { + failed += 1; + results.push({ ok: false, error: error instanceof Error ? error.message : String(error) }); + if (args.stop_on_error ?? true) break; + } + } + return { completed, failed, results }; + }, + }, + { + name: 'filmcraft.list_commands', + purpose: 'Find editing commands by a word in the id, label or menu.', + when: 'Use when the user wants an action and its command id is unknown.', + params: { query: { type: 'string', description: 'Substring of the command id, label or menu path; omit to list the first 10' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { query: 'razor' }, says: 'Which command cuts a clip?' }], + // server.rs:341-359 upstream runs the engine command command.list; the page's commands() + // (the engine.commands control method, ui-egui control.rs:504) runs that same command and + // is cached by the adapter, so the pack uses it like the other packs + run: async (args, ctx) => { + const all = await (await ctx.craft(APP)).commands(); + const q = String(args.query ?? '').trim().toLowerCase(); + return all.filter(command => !q || [command.id, command.label, command.menu].some(part => String(part ?? '').toLowerCase().includes(q))) + .slice(0, 10).map(command => ({ id: command.id, label: command.label, menu: command.menu, params: command.params, enabled: command.enabled })); + }, + }, + { + name: 'filmcraft.run_command', + purpose: 'Run any FilmCraft command by id with parameters.', + when: `Use when a menu action is wanted by id; ${DESTRUCTIVE.join(', ')} are destructive, so ask first.`, + params: { + command: { type: 'string', required: true, description: 'Command id from filmcraft.list_commands, e.g. timeline.razor, effects.apply, playhead.set' }, + params: { type: 'text', description: 'Parameters as key=value lines, one per line; a [ ... ] or { ... } value is JSON; omit for the defaults' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(prefix => String(args.command ?? '').startsWith(prefix)) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { command: 'playhead.set', params: 'seconds=2' }, says: 'Jump the playhead to 2 seconds' }], + // server.rs:366 command_run: run(id, params) against the live command list; unknown ids get + // invalid_argument with the 3 closest + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const all = await app.commands(); + if (!all.some(command => command.id === args.command)) { + const near = closest(args.command, all.map(command => command.id), 3); + const fix = near.length > 0 ? callLine('filmcraft.run_command', { command: near[0] }) : ''; + throw new ToolError('invalid_argument', `unknown command "${args.command}"${near.length > 0 ? `; closest: ${near.join(', ')}` : ''}`, fix); + } + return app.execute(args.command, parseParams(args.params)); + }, + }, + { + name: 'filmcraft.open_file', + purpose: 'Open a project or import media from Files into FilmCraft.', + when: 'Use when the user wants a project or media from Files. Not for opening the app itself; that is desktop.open_app.', + params: { path: { type: 'path', required: false, description: 'A Files path to a .fcproj project or media (video, audio or still)' } }, + effect: 'destructive', + needs: ['host', 'app:filmcraft', 'files'], + examples: [{ args: { path: '/FilmCraft/talk.fcproj' }, says: 'Open the talk project from Files' }], + // Drives the wrapper's own #file input (app.mjs:38), so the open posts from the wrapper + // realm, as the page's host bridge requires. A .fcproj is opened as the project, which + // replaces the open one (the web app holds a single project; engine commands.rs + // install_project clean=true), so this is destructive; media is imported like a dropped + // file. The wrapper's own unsaved-changes confirm still applies (app.mjs:35). + // openAndAwait waits until the page's inspect changes, so the result confirms the load. + run: async (args, ctx) => { + const file = await readOpenFile(ctx, args.path, { id: APP, title: 'FilmCraft' }); + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + return openAndAwait(craft, { id: APP, title: 'FilmCraft', wrapperWindow: wrapper, name: file.name, bytes: file.bytes, accept: releases[APP].accept }); + }, + }, + { + name: 'filmcraft.save_copy', + purpose: 'Save the active project as a .fcproj file in Files.', + when: 'Use when the user wants to keep a copy of the project in Files.', + params: { + path: { type: 'path', required: true, description: 'The Files path to write the copy to, e.g. /FilmCraft/talk.fcproj' }, + overwrite: { type: 'boolean', description: 'Replace the file when the path already exists; false when omitted' }, + }, + effect: 'change', + effectFor: args => (args.overwrite ? 'destructive' : 'change'), + needs: ['host', 'app:filmcraft', 'files'], + examples: [{ args: { path: '/FilmCraft/talk.fcproj' }, says: 'Save a copy of the project to Files' }], + // No path is ever passed (the browser has no file system). FilmCraft has no file.saveBytes, + // so the no-path file.save {} (engine commands.rs:1981) is the trigger: it saves the + // project under its own name, and in host mode the page hands the bytes to the wrapper + // (filmcraft-web host.rs wrote/flush_saves), which the saveCopy capture reads as + // filmcraft:save (app.mjs:29-33) and also downloads in the browser, so the result says so. + // A fresh project with no saved path yet makes the app refuse ("no path (use Save As)"), + // which surfaces as the tool error. The bytes are the native .fcproj format, so a target + // with another extension is refused with a fix. + run: async (args, ctx) => { + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + const save = await saveBytesCopy(craft, { + id: APP, title: 'FilmCraft', wrapperWindow: wrapper, target: args.path, + tool: 'filmcraft.save_copy', nativeExt: '.fcproj', + }); + const written = await filesCall( + ctx, + files => files.writeBytes(args.path, save.bytes, { overwrite: Boolean(args.overwrite) }), + error => (error.code === 'exists' ? callLine('filmcraft.save_copy', { path: args.path, overwrite: true }) : ''), + ); + return { path: written.path, name: save.name, size: written.size, created: written.created, ...(save.note ? { note: save.note } : {}) }; + }, + }, +]; + +// Live-check exports (brief): every command id the pack passes to execute (timeline.place and +// timeline.move are internal commands outside the command.list registry, run by their +// dedicated tools only) and every control method passed to request. batch and run_command also +// pass arbitrary ids from the live commands() list. +export const usesCommands = [ + 'project.inspect', 'sequence.inspect', 'playhead.set', 'timeline.razor', 'sequence.addEdit', + 'timeline.place', 'timeline.move', 'effects.apply', 'effects.list', 'file.newBin', + 'file.newProject', 'file.openDemoProject', 'file.save', 'edit.undo', 'edit.redo', +]; +export const usesMethods = []; // nothing goes through request(); ui_inspect uses the adapter inspect() diff --git a/agent/apps/gridcraft/skills.md b/agent/apps/gridcraft/skills.md new file mode 100644 index 0000000..566962b --- /dev/null +++ b/agent/apps/gridcraft/skills.md @@ -0,0 +1,158 @@ +## Type values into cells +slug: type-values-into-cells +summary: Write rows of values into the spreadsheet starting at a cell. +keywords: type, enter, input, cells, values, table, paste +tools: desktop.open_app, gridcraft.set_cells + +When: the user wants to type, enter or paste a block of values into the spreadsheet. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.set_cells start=A1 values=[["Item","Cost"],["Rent",1200]] +Check: gridcraft.read_range on the same range shows the values. +Gotchas: change start= and values=; the first row starts at start; a string starting with = becomes a formula. + +## Read what is in cells +slug: read-cell-values +summary: Read the values of a range, or the whole used range of the sheet. +keywords: read, show, look at, cells, values, range, what is +tools: desktop.open_app, gridcraft.read_range + +When: the user asks what is in some cells or a range of the spreadsheet. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.read_range range=A1:D10 +Check: the result has the rows of cell values; empty cells are null. +Gotchas: change range=; omit it to read the used range; pass formulas=true to see formula text. + +## Add a SUM formula +slug: add-a-sum-formula +summary: Put a SUM or other formula into a cell, and check the result first. +keywords: sum, total, formula, add up, calculate, average +tools: desktop.open_app, gridcraft.evaluate_formula, gridcraft.set_cell, gridcraft.get_cell + +When: the user wants a total, average or other formula typed into a cell. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.evaluate_formula formula==SUM(B2:B9) +3. call_tool tool=gridcraft.set_cell cell=B10 input==SUM(B2:B9) +Check: gridcraft.get_cell on B10 shows the formula and its computed value. +Gotchas: change the range and the target cell; step 2 is optional once the formula is known. + +## Make cells bold or currency +slug: make-cells-bold-or-currency +summary: Bold, color, align or number-format a range of cells in one call. +keywords: bold, italic, currency, format, color, align, highlight +tools: desktop.open_app, gridcraft.format_range + +When: the user wants cells bold, italic, colored, aligned or currency-formatted. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.format_range range=A1:C1 bold=true +3. call_tool tool=gridcraft.format_range range=B2:B9 number_format=Currency +Check: gridcraft.get_cell on a formatted cell shows the style; the values are unchanged. +Gotchas: change range= and the style params; pass at least one of bold, italic, font_color, fill, number_format or align. + +## Make a chart from a range +slug: make-a-chart +summary: Insert a chart from a data range, with the headers as names. +keywords: chart, graph, plot, visualize, column, pie +tools: desktop.open_app, gridcraft.insert_chart + +When: the user wants a chart or graph made from a range of cells. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.insert_chart range=A1:C6 type=column title=Sales +Check: gridcraft.inspect lists the new chart on the sheet. +Gotchas: change range= (include the header row) and type=; the first row and column become series names and categories. + +## Turn a range into a table +slug: make-a-table +summary: Format a range as a table with banded rows and filter buttons. +keywords: table, format as table, banded, filter buttons, header +tools: desktop.open_app, gridcraft.create_table + +When: the user wants to turn a range of cells into a table. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.create_table range=A1:D20 +Check: gridcraft.inspect lists the new table with its name and range. +Gotchas: change range= (include the header row); name= sets the table name, style= the look. + +## Sort rows +slug: sort-rows +summary: Sort the rows of a range by one or more columns. +keywords: sort, order, arrange rows, ascending, descending +tools: desktop.open_app, gridcraft.sort_range + +When: the user wants to sort the rows, or put a column in order. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.sort_range keys=B, A desc range=A1:D20 header=true +Check: gridcraft.read_range on the range shows the rows sorted by column B. +Gotchas: change keys= (a letter, or a letter plus desc for descending) and range=; header=true keeps the first row in place. + +## Filter rows +slug: filter-rows +summary: Keep only the rows that match a column filter. +keywords: filter, hide rows, show only, match, clear filter +tools: desktop.open_app, gridcraft.filter + +When: the user wants to filter rows, or hide the rows that do not match. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.filter column=C values=North, South +Check: gridcraft.read_range shows only the matching rows; gridcraft.filter with clear=true removes the filter. +Gotchas: change column= and values=; custom_op plus custom_value filters by comparison, top_count keeps the top N rows. + +## Start a new workbook +slug: start-a-new-workbook +summary: Create a blank or sample workbook and make it active. +keywords: new workbook, new spreadsheet, blank book, sample, start fresh +tools: desktop.open_app, gridcraft.new_workbook + +When: the user wants a new spreadsheet, or one of the built-in samples. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.new_workbook +Check: gridcraft.inspect shows the new workbook as active. +Gotchas: the open workbook stays open in the app; if it has unsaved work, tell the user before switching; sample= picks budget, sales or grades. + +## Find and run any menu command +slug: run-any-menu-command +summary: Look up a ribbon or menu command by name, then run it with parameters. +keywords: menu, ribbon, command, run action, toolbar, what can it do +tools: desktop.open_app, gridcraft.list_commands, gridcraft.run_command + +When: the user wants a ribbon or menu action that has no dedicated tool. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.list_commands query=border +3. call_tool tool=gridcraft.run_command command=home.borders params=range=A1:C1 +Check: gridcraft.read_range or gridcraft.inspect shows the action took effect. +Gotchas: run_command takes key=value lines in params=; ids starting with file.new, file.close, sheet.delete or edit.clear are destructive, so ask the user first. + +## Open a workbook from Files +slug: open-a-workbook-from-files +summary: Open a workbook that is stored in Files in GridCraft. +keywords: open, load, from files, workbook, xlsx, import file +tools: desktop.open_app, gridcraft.open_file + +When: the user wants to open a workbook that is stored in Files. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.open_file path=/GridCraft/budget.xlsx +Check: the result's opened field names the workbook and its sheets; gridcraft.inspect shows the opened workbook. +Gotchas: change path= to the Files path of a workbook (xlsx, xlsm, xls, ods, csv, tsv, txt, json); the workbook opens alongside the open ones; while the open workbook has unsaved changes the app asks first whether to keep them. + +## Save a copy of the workbook to Files +slug: save-a-workbook-copy-to-files +summary: Save the active workbook as a file in Files. +keywords: save, copy, to files, export, keep, xlsx, write +tools: desktop.open_app, gridcraft.save_copy + +When: the user wants to keep a copy of the active workbook in Files. +Steps: +1. call_tool tool=desktop.open_app app=gridcraft +2. call_tool tool=gridcraft.save_copy path=/GridCraft/budget.xlsx +Check: the result has the saved Files path and size; files.info on that path shows the same size. +Gotchas: change path=; GridCraft saves .xlsx files, so a target with another extension is refused with the .xlsx path as the fix; if the path exists the tool errors, so choose another name or pass overwrite=true (which is destructive); when the app saves through the capture path it also downloads the file, and the result says so. diff --git a/agent/apps/gridcraft/tools.js b/agent/apps/gridcraft/tools.js new file mode 100644 index 0000000..47d480c --- /dev/null +++ b/agent/apps/gridcraft/tools.js @@ -0,0 +1,419 @@ +// Ported from storytold/gridcraft@v0.19.1 crates/mcp/src/tools.rs (MIT OR Apache-2.0). Tool names, descriptions and the control-method mapping follow that table; arguments are flattened for small models. +// The tools run in Buddy's frame and drive the GridCraft page API through ctx.craft, +// which the runtime wires as id => craftApi(await ctx.host.appWindow(id), id) (plan 9). +import { ToolError, callLine, closest } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { filesCall, openAndAwait, readOpenFile, saveBytesCopy } from '../../shared/craft-files.js'; +import { releases } from '../../../scripts/pc/craft/releases.mjs'; + +const APP = 'gridcraft'; +const NEEDS = ['host', 'app:gridcraft']; +// gridcraft.run_command ids that destroy or close data: the when text warns the model to +// ask the user first: effectFor marks those calls destructive, so the policy asks. +const DESTRUCTIVE = ['file.new', 'file.close', 'sheet.delete', 'edit.clear']; +// tools.rs format_range: horizontalAlign -> command (tools.rs:539-546). +const ALIGN = { left: 'home.alignLeft', center: 'home.alignCenter', right: 'home.alignRight', justify: 'home.justify' }; + +/** tools.rs pick(): copy the listed keys (when present) into a params object. */ +const pick = (args, keys) => { + const out = {}; + for (const key of keys) if (args[key] !== undefined) out[key] = args[key]; + return out; +}; + +// gridcraft.run_command params: key=value lines -> object, with number and boolean +// coercion (plan 9, the generic long-tail tool). +const parseParams = text => { + const out = {}; + for (const line of String(text ?? '').split('\n')) { + const row = line.trim(); + if (!row) continue; + const eq = row.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad params line "${row}": use key=value`, ''); + const raw = row.slice(eq + 1).trim(); + out[row.slice(0, eq).trim()] = /^(true|false)$/i.test(raw) ? raw.toLowerCase() === 'true' : /^-?\d+(\.\d+)?$/.test(raw) ? Number(raw) : raw; + } + return out; +}; + +export const pack = { id: APP, title: 'GridCraft' }; + +export const tools = [ + { + name: 'gridcraft.inspect', + purpose: 'Show the open spreadsheet: sheets, ranges, tables, charts, selection.', + when: 'Use when the user asks what is in the workbook, or before planning cell changes.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What does this spreadsheet contain?' }], + // tools.rs:640 document.inspect + run: async (args, ctx) => (await ctx.craft(APP)).inspect(), + }, + { + name: 'gridcraft.read_range', + purpose: 'Read cell values from a range as rows.', + when: 'Use when the user asks what is in some cells or a range of the spreadsheet.', + params: { + range: { type: 'string', description: 'A1-style range, e.g. A1:D10; the used range when omitted' }, + sheet: { type: 'string', description: 'Sheet name; the active sheet when omitted' }, + formulas: { type: 'boolean', description: 'Return formula text instead of computed values' }, + formatted: { type: 'boolean', description: 'Return display text with number formats applied' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { range: 'A1:D4' }, says: 'What is in the first block of numbers?' }, { args: { range: 'B2', formulas: true }, says: 'What formula is in B2?' }], + // tools.rs:641 sheet.read + run: async (args, ctx) => (await ctx.craft(APP)).request('sheet.read', pick(args, ['range', 'sheet', 'formulas', 'formatted'])), + }, + { + name: 'gridcraft.set_cells', + purpose: 'Write rows of values into the spreadsheet starting at a cell.', + when: 'Use when the user wants to type or paste a table of values into cells.', + params: { + start: { type: 'string', required: true, description: 'Top-left cell or range, e.g. A1 or Sheet2!B3' }, + values: { type: 'table', required: true, description: 'Rows of cell values, e.g. [["Item","Cost"],["Rent",1200]]' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { start: 'A1', values: [['Item', 'Cost'], ['Rent', 1200]] }, says: 'Type this table into the sheet' }], + // tools.rs:642 range.setValues; the wire field is range, so start maps onto it + run: async (args, ctx) => (await ctx.craft(APP)).execute('range.setValues', { range: args.start, values: args.values }), + }, + { + name: 'gridcraft.set_cell', + purpose: 'Enter one cell exactly as if typed: number, text or formula.', + when: 'Use when the user wants to set the value of a single cell, or type a formula.', + params: { + cell: { type: 'string', required: true, description: 'Cell, e.g. B7 or Sheet2!C3' }, + input: { type: 'string', required: true, description: 'Typed input: a number, text or a =formula' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { cell: 'A1', input: 'Total' }, says: 'Put the word Total in A1' }, { args: { cell: 'B10', input: '=SUM(B2:B9)' }, says: 'Total column B in B10' }], + // tools.rs:643 cell.set + run: async (args, ctx) => (await ctx.craft(APP)).execute('cell.set', { cell: args.cell, input: args.input }), + }, + { + name: 'gridcraft.get_cell', + purpose: 'Show one cell: value, formula, display text, style, comment.', + when: 'Use when the user asks what is in one cell, or whether it holds a formula.', + params: { cell: { type: 'string', required: true, description: 'Cell, e.g. B7 or Sheet2!C3' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { cell: 'B7' }, says: 'What is in cell B7?' }], + // tools.rs:644 cell.get + run: async (args, ctx) => (await ctx.craft(APP)).execute('cell.get', { cell: args.cell }), + }, + { + name: 'gridcraft.evaluate_formula', + purpose: 'Evaluate a formula against the sheet without changing any cell.', + when: 'Use when the user wants to check a formula result before typing it in.', + params: { + formula: { type: 'string', required: true, description: 'Formula text, with or without the leading =, e.g. =SUM(B2:B10)' }, + cell: { type: 'string', description: 'Evaluate as if in this cell; the active cell when omitted' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { formula: '=SUM(B2:B10)/COUNT(B2:B10)' }, says: 'What is the average of B2 to B10?' }], + // tools.rs:645-652 formulas.evaluate; a leading = is added when missing + run: async (args, ctx) => { + const formula = String(args.formula).startsWith('=') ? args.formula : `=${args.formula}`; + const result = await (await ctx.craft(APP)).execute('formulas.evaluate', pick({ formula, cell: args.cell }, ['formula', 'cell'])); + return { formula, result }; + }, + }, + { + name: 'gridcraft.select', + purpose: 'Set the spreadsheet selection.', + when: 'Use when the user wants to select cells, or aim the next action at a range.', + params: { + range: { type: 'string', required: true, description: 'A1-style range; multiple areas with commas, e.g. A1:B2,D4' }, + active: { type: 'string', description: 'Active cell inside the selection; the top-left when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { range: 'A1:D10' }, says: 'Select the data block' }], + // tools.rs:653 selection.set + run: async (args, ctx) => (await ctx.craft(APP)).execute('selection.set', pick(args, ['range', 'active'])), + }, + { + name: 'gridcraft.format_range', + purpose: 'Bold, color, align or number-format a range in one call.', + when: 'Use when the user wants cells bold, italic, colored, aligned or currency-formatted.', + params: { + range: { type: 'string', required: true, description: 'A1-style range to format, e.g. A1:C1' }, + bold: { type: 'boolean', description: 'Bold on or off' }, + italic: { type: 'boolean', description: 'Italic on or off' }, + font_color: { type: 'string', description: 'Text color "#RRGGBB" or auto' }, + fill: { type: 'string', description: 'Background color "#RRGGBB" or none' }, + number_format: { type: 'string', description: 'Number format name or code, e.g. Currency, Percentage, #,##0.00' }, + align: { type: 'enum', values: ['left', 'center', 'right', 'justify'], description: 'Horizontal alignment' }, + }, + effect: 'change', + needs: NEEDS, + examples: [ + { args: { range: 'A1:C1', bold: true }, says: 'Make the header row bold' }, + { args: { range: 'B2:B9', number_format: 'Currency' }, says: 'Format column B as money' }, + ], + // tools.rs:654 format_range (tools.rs:510): one home.* command per style, tools.rs order + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const steps = []; + if (args.bold !== undefined) steps.push(['home.bold', { on: args.bold }]); + if (args.italic !== undefined) steps.push(['home.italic', { on: args.italic }]); + if (args.font_color !== undefined) steps.push(['home.fontColor', { color: args.font_color }]); + if (args.fill !== undefined) steps.push(['home.fillColor', { color: args.fill }]); + if (args.number_format !== undefined) steps.push(['home.numberFormat', { format: args.number_format }]); + if (args.align !== undefined) steps.push([ALIGN[args.align], {}]); + if (steps.length === 0) throw new ToolError('invalid_argument', 'give at least one of bold, italic, font_color, fill, number_format or align', ''); + const applied = []; + for (const [id, extra] of steps) { + await app.execute(id, { range: args.range, ...extra }); + applied.push(id); + } + return { range: args.range, applied }; + }, + }, + { + name: 'gridcraft.insert_chart', + purpose: 'Insert a chart from a data range, headers as names.', + when: 'Use when the user wants a chart, graph or plot made from a range of cells.', + params: { + range: { type: 'string', required: true, description: 'Source data range including headers, e.g. A1:C6' }, + type: { type: 'enum', required: true, values: ['column', 'bar', 'line', 'pie', 'doughnut', 'area', 'scatter', 'bubble', 'radar', 'combo', 'histogram', 'waterfall', 'funnel', 'treemap', 'sunburst', 'boxWhisker', 'stock'], description: 'Chart type' }, + subtype: { type: 'enum', values: ['clustered', 'stacked', 'stacked100', 'markers'], description: 'Chart variant' }, + title: { type: 'string', description: 'Chart title' }, + at: { type: 'string', description: 'Top-left anchor cell; right of the data when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { range: 'A1:C6', type: 'column', title: 'Sales' }, says: 'Make a column chart of the sales data' }], + // tools.rs:655 insert.chart + run: async (args, ctx) => (await ctx.craft(APP)).execute('insert.chart', pick(args, ['range', 'type', 'subtype', 'title', 'at'])), + }, + { + name: 'gridcraft.create_table', + purpose: 'Format a range as a table with banded rows and filters.', + when: 'Use when the user wants to turn a range into a table, with header row and filters.', + params: { + range: { type: 'string', required: true, description: 'Range including the header row, e.g. A1:D20' }, + style: { type: 'string', description: 'Table style, e.g. TableStyleMedium2; the default when omitted' }, + header: { type: 'boolean', description: 'First row holds headers; true when omitted' }, + name: { type: 'string', description: 'Table name, e.g. Table1; auto-numbered when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { range: 'A1:D20' }, says: 'Turn the range into a table' }], + // tools.rs:656 insert.table + run: async (args, ctx) => (await ctx.craft(APP)).execute('insert.table', pick(args, ['range', 'style', 'header', 'name'])), + }, + { + name: 'gridcraft.sort_range', + purpose: 'Sort a range of rows by one or more columns.', + when: 'Use when the user wants to sort rows, or put a column in ascending or descending order.', + params: { + keys: { type: 'list', required: true, description: 'Sort levels, most significant first: a column letter, or a letter plus desc, e.g. B, A desc' }, + range: { type: 'string', description: 'A1-style range to sort; the region around the selection when omitted' }, + header: { type: 'boolean', description: 'The first row is a header kept in place' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { keys: 'B, A desc', range: 'A1:D20', header: true }, says: 'Sort the table by column B' }], + // tools.rs:657 sort_range (tools.rs:572): keys normalize to {column, order}, then data.sort + run: async (args, ctx) => { + const params = { keys: (args.keys ?? []).map(level => { const [column, order] = String(level).split(/\s+/); return { column, order: /desc/i.test(order ?? '') ? 'desc' : 'asc' }; }) }; + if (args.range !== undefined) params.range = args.range; + if (args.header !== undefined) params.header = args.header; + return (await ctx.craft(APP)).execute('data.sort', params); + }, + }, + { + name: 'gridcraft.filter', + purpose: 'Keep only the rows matching a column filter.', + when: 'Use when the user wants to filter rows, hide non-matching rows or clear a filter.', + params: { + column: { type: 'string', required: true, description: 'Column letter to filter on, e.g. C' }, + range: { type: 'string', description: 'Data range to filter; the region around the selection when omitted' }, + values: { type: 'list', description: 'Values to keep, e.g. North, South' }, + custom_op: { type: 'string', description: 'Custom operator: =, <>, >, >=, <, <=, beginsWith, contains' }, + custom_value: { type: 'string', description: 'Value the custom operator compares against' }, + custom_op2: { type: 'string', description: 'Second operator, for a pair of criteria' }, + custom_value2: { type: 'string', description: 'Value for the second operator' }, + custom_and: { type: 'boolean', description: 'Match both criteria (true) or either (false)' }, + top_count: { type: 'integer', min: 1, description: 'Keep the top N rows by this column' }, + top_bottom: { type: 'boolean', description: 'Keep the bottom N instead of the top' }, + top_percent: { type: 'boolean', description: 'Treat N as a percentage of the rows' }, + blanks: { type: 'boolean', description: 'Also keep blank cells' }, + clear: { type: 'boolean', description: 'Clear this column filter' }, + }, + effect: 'change', + needs: NEEDS, + examples: [ + { args: { column: 'C', values: 'North, South' }, says: 'Show only the North and South rows' }, + { args: { column: 'B', custom_op: '>', custom_value: '100' }, says: 'Keep the rows over 100' }, + ], + // tools.rs:658 filter (tools.rs:603): selection.set for range, then data.filterBy + run: async (args, ctx) => { + const app = await ctx.craft(APP); + if (args.range !== undefined) await app.execute('selection.set', { range: args.range }); + const params = { column: args.column }; + const put = (key, value) => { if (value !== undefined) params[key] = value; }; + put('values', args.values); + const custom = {}; + if (args.custom_op !== undefined) custom.op = args.custom_op; + if (args.custom_value !== undefined) custom.value = args.custom_value; + if (args.custom_op2 !== undefined) custom.op2 = args.custom_op2; + if (args.custom_value2 !== undefined) custom.value2 = args.custom_value2; + if (args.custom_and !== undefined) custom.and = args.custom_and; + if (Object.keys(custom).length > 0) params.custom = custom; + const top = {}; + if (args.top_count !== undefined) top.count = args.top_count; + if (args.top_bottom !== undefined) top.bottom = args.top_bottom; + if (args.top_percent !== undefined) top.percent = args.top_percent; + if (Object.keys(top).length > 0) params.top = top; + put('blanks', args.blanks); + put('clear', args.clear); + return app.execute('data.filterBy', params); + }, + }, + { + name: 'gridcraft.new_workbook', + purpose: 'Create a new workbook and make it active.', + when: 'Use when the user wants a blank spreadsheet, or one of the sample workbooks.', + params: { sample: { type: 'enum', values: ['budget', 'sales', 'grades'], description: 'Built-in sample workbook; blank when omitted' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Start a fresh spreadsheet' }, { args: { sample: 'budget' }, says: 'Start from the budget sample' }], + // tools.rs:661 file.new. Not destructive: it opens a new workbook alongside the open + // one (tools.rs:110 UNTARGETED; control-protocol.md Windows: workbooks coexist). + run: async (args, ctx) => (await ctx.craft(APP)).execute('file.new', pick(args, ['sample'])), + }, + { + name: 'gridcraft.undo', + purpose: 'Undo the last changes in the spreadsheet.', + when: 'Use when the user wants to undo, or take back the last edit or few edits.', + params: { steps: { type: 'integer', min: 0, description: 'Number of steps to undo; 1 when omitted' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Undo that' }, { args: { steps: 2 }, says: 'Undo the last two changes' }], + // tools.rs:662 edit.undo + run: async (args, ctx) => (await ctx.craft(APP)).execute('edit.undo', pick(args, ['steps'])), + }, + { + name: 'gridcraft.redo', + purpose: 'Redo the last undone changes.', + when: 'Use when the user wants to redo, or bring back the change they just undid.', + params: { steps: { type: 'integer', min: 0, description: 'Number of steps to redo; 1 when omitted' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Bring that back' }], + // tools.rs:663 edit.redo + run: async (args, ctx) => (await ctx.craft(APP)).execute('edit.redo', pick(args, ['steps'])), + }, + { + name: 'gridcraft.list_functions', + purpose: 'List spreadsheet functions with signature and description.', + when: 'Use when the user asks which formula function to use, e.g. for a lookup or a date.', + params: { + search: { type: 'string', description: 'Substring of the function name or description' }, + category: { type: 'string', description: 'Category, e.g. Math & Trig, Lookup & Reference' }, + }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { search: 'vlookup' }, says: 'Which function looks a value up?' }], + // tools.rs:665 formulas.functions + run: async (args, ctx) => (await ctx.craft(APP)).execute('formulas.functions', pick(args, ['search', 'category'])), + }, + { + name: 'gridcraft.list_commands', + purpose: 'Find spreadsheet menu commands by a word in their name.', + when: 'Use when the user wants a ribbon or menu action and its command id is unknown.', + params: { query: { type: 'string', description: 'Part of a command id, label or menu path; omit to list the first 10 commands' } }, + effect: 'read', + needs: NEEDS, + examples: [{ args: { query: 'border' }, says: 'Which commands add borders?' }], + // Generic tool (plan 9): the top 10 of the live commands() by case-insensitive match + run: async (args, ctx) => { + const all = await (await ctx.craft(APP)).commands(); + const q = String(args.query ?? '').trim().toLowerCase(); + return all.filter(command => !q || [command.id, command.label, command.menu].some(part => String(part ?? '').toLowerCase().includes(q))) + .slice(0, 10).map(command => ({ id: command.id, label: command.label, params: command.params })); + }, + }, + { + name: 'gridcraft.run_command', + purpose: 'Run any GridCraft menu command by id with parameters.', + when: `Use when a menu action is wanted by id; ${DESTRUCTIVE.join(', ')} are destructive, so ask first.`, + params: { + command: { type: 'string', required: true, description: 'Command id from gridcraft.list_commands, e.g. cell.set or home.bold' }, + params: { type: 'text', description: 'Parameters as key=value lines, one per line; omit for the defaults' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(prefix => String(args.command ?? '').startsWith(prefix)) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { command: 'cell.set', params: 'cell=B2\ninput=Hello' }, says: 'Set B2 to Hello' }], + // Generic tool (plan 9): unknown ids get invalid_argument with the 3 closest ids + run: async (args, ctx) => { + const app = await ctx.craft(APP); + const all = await app.commands(); + if (!all.some(command => command.id === args.command)) { + const near = closest(args.command, all.map(command => command.id), 3); + const fix = near.length > 0 ? callLine('gridcraft.run_command', { command: near[0] }) : ''; + throw new ToolError('invalid_argument', `unknown command "${args.command}"${near.length > 0 ? `; closest: ${near.join(', ')}` : ''}`, fix); + } + return app.execute(args.command, parseParams(args.params)); + }, + }, + { + name: 'gridcraft.open_file', + purpose: 'Open a workbook from Files in GridCraft.', + when: 'Use when the user wants a workbook from Files. Not for opening the app itself; that is desktop.open_app.', + params: { path: { type: 'path', required: false, description: 'A Files path to a workbook file (.xlsx, .csv, .ods or similar)' } }, + effect: 'change', + needs: ['host', 'app:gridcraft', 'files'], + examples: [{ args: { path: '/GridCraft/budget.xlsx' }, says: 'Open the budget workbook from Files' }], + // Drives the wrapper's own #file input (app.mjs:38), so the open posts from the wrapper + // realm, as the app's host bridge requires (craft-libs web-host web.rs:106). The workbook + // opens alongside the open ones (engine cmd/file.rs add_document), so a change; the + // wrapper's own unsaved-changes confirm still applies (app.mjs:35). openAndAwait waits + // until the app's inspect changes, so the result confirms the workbook actually loaded. + run: async (args, ctx) => { + const file = await readOpenFile(ctx, args.path, { id: APP, title: 'GridCraft' }); + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + return openAndAwait(craft, { id: APP, title: 'GridCraft', wrapperWindow: wrapper, name: file.name, bytes: file.bytes, accept: releases[APP].accept }); + }, + }, + { + name: 'gridcraft.save_copy', + purpose: 'Save the active workbook as a file in Files.', + when: 'Use when the user wants to keep a copy of the workbook in Files.', + params: { + path: { type: 'path', required: true, description: 'The Files path to write the copy to, e.g. /GridCraft/budget.xlsx' }, + overwrite: { type: 'boolean', description: 'Replace the file when the path already exists; false when omitted' }, + }, + effect: 'change', + effectFor: args => (args.overwrite ? 'destructive' : 'change'), + needs: ['host', 'app:gridcraft', 'files'], + examples: [{ args: { path: '/GridCraft/budget.xlsx' }, says: 'Save a copy of the workbook to Files' }], + // No path is ever passed (the browser has no file system). saveBytesCopy takes the bytes + // inline from file.saveBytes when the live command list has it (no download), else from + // the no-path file.save the wrapper captures as gridcraft:save (app.mjs:29-33); in that + // case the wrapper also downloads the file, and the result says so. The bytes are the + // native .xlsx format, so a target with another extension is refused with a fix. + run: async (args, ctx) => { + const wrapper = await ctx.host.appWindow(APP); + const craft = await ctx.craft(APP); + const save = await saveBytesCopy(craft, { + id: APP, title: 'GridCraft', wrapperWindow: wrapper, target: args.path, + tool: 'gridcraft.save_copy', nativeExt: '.xlsx', + }); + const written = await filesCall( + ctx, + files => files.writeBytes(args.path, save.bytes, { overwrite: Boolean(args.overwrite) }), + error => (error.code === 'exists' ? callLine('gridcraft.save_copy', { path: args.path, overwrite: true }) : ''), + ); + return { path: written.path, name: save.name, size: written.size, created: written.created, ...(save.note ? { note: save.note } : {}) }; + }, + }, +]; diff --git a/agent/apps/lightcraft/skills.md b/agent/apps/lightcraft/skills.md new file mode 100644 index 0000000..2a4d1ca --- /dev/null +++ b/agent/apps/lightcraft/skills.md @@ -0,0 +1,120 @@ +## Browse the library +slug: browse-the-library +summary: Inspect the library, then filter and sort the view. +keywords: library, browse, filter, sort, view, find, photos +tools: desktop.open_app, lightcraft.library_info, lightcraft.filter, lightcraft.sort + +When: the user asks what is in the library, or wants a different view of it. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.library_info +3. call_tool tool=lightcraft.filter filter={"rating":4} +4. call_tool tool=lightcraft.sort key=captureDate ascending=true +Check: the filter keeps only matching photos in the view; library_info shows the counts. +Gotchas: filter= is a JSON object of filter keys (rating, ratingOp, flag, label, keyword, camera, date, ...); sort key= is captureDate, importDate, editDate, fileName, rating, fileSize or random; lightcraft.library_info also reports free space and worker state. + +## Select photos +slug: select-photos +summary: Select photos by id, or clear the selection. +keywords: select, selection, choose, pick, ids, clear +tools: desktop.open_app, lightcraft.select, lightcraft.library_info + +When: the user wants specific photos selected for an action. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.select ids=3, 7 +Check: the action that follows (rate, rotate, delete) takes the ids it was given. +Gotchas: ids= takes a list of photo ids from the library view; omitting ids= clears the selection; most photo commands act on the selection when ids= is omitted. + +## Rate photos +slug: rate-photos +summary: Rate the selection or given photos 0 to 5 stars. +keywords: rate, rating, stars, pick, reject, 5 star +tools: desktop.open_app, lightcraft.rate, lightcraft.filter + +When: the user wants to rate photos. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.rate rating=4 +3. call_tool tool=lightcraft.filter filter={"rating":4} +Check: the filtered view lists the rated photos. +Gotchas: rating= is 0 to 5; ids= names the photos, the selection when omitted; advance=true moves on when the photo leaves the view; rating 0 unrates. + +## Rotate photos +slug: rotate-photos +summary: Rotate photos 90 degrees left or right. +keywords: rotate, straighten, orientation, turn, sideways +tools: desktop.open_app, lightcraft.rotate, lightcraft.undo + +When: the user wants to rotate photos straight. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.rotate direction=right +Check: the photos show rotated 90 degrees. +Gotchas: direction=left rotates counter-clockwise; ids= names the photos, the selection when omitted; lightcraft.undo takes the rotation back. + +## Delete and restore photos +slug: delete-and-restore-photos +summary: Delete photos to Recently Deleted, and restore them. +keywords: delete, remove, trash, restore, recently deleted, undo +tools: desktop.open_app, lightcraft.delete, lightcraft.restore + +When: the user wants to delete photos, or get a deleted one back. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.delete ids=3 +3. call_tool tool=lightcraft.restore ids=3 +Check: the photo is gone after the delete and back after the restore. +Gotchas: delete moves photos to Recently Deleted (not permanent), so ask the user first and keep the ids for lightcraft.restore; ids= names the photos, the selection when omitted. + +## Reset a photo's edits +slug: reset-photo-edits +summary: Reset the develop edits on a photo, back to the original. +keywords: reset, develop, edits, back to original, clear settings +tools: desktop.open_app, lightcraft.develop_reset, lightcraft.undo + +When: the user wants all edits off a photo. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.develop_reset +Check: the photo shows the original, unedited image. +Gotchas: develop_reset clears the edit history of the photo, so the user should confirm; ids= names the photos, the selection when omitted; a single edit is better undone with lightcraft.undo. + +## Undo and redo changes +slug: undo-and-redo +summary: Step back through and forward through the library's changes. +keywords: undo, redo, back, step back, history +tools: desktop.open_app, lightcraft.undo, lightcraft.redo + +When: the user wants to undo or redo a change. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.undo +3. call_tool tool=lightcraft.redo +Check: the change is gone after undo and back after redo. +Gotchas: undo and redo walk the journal one step at a time; a deleted photo is brought back with lightcraft.restore instead. + +## Run any library command +slug: run-any-lightcraft-command +summary: Run a LightCraft command by id, e.g. presets, masks, albums. +keywords: command, run, preset, mask, album, version, menu +tools: desktop.open_app, lightcraft.run_command, lightcraft.library_info + +When: the user wants an action that has no dedicated tool. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.run_command command=album.setCover params="id=2 photo=9" +Check: lightcraft.library_info or the app UI shows the action took effect. +Gotchas: params= takes key=value lines or a JSON object; the page has no command list, so the id must come from the app's menus (e.g. preset.apply, mask.invert, version.create); photo.delete, preset.delete and develop.reset are destructive, so ask the user first. +## Import a photo from Files +slug: import-a-photo-from-files +summary: Add a photo that is stored in Files to the LightCraft library. +keywords: import, add, from files, photo, library, cr2, raw, load +tools: desktop.open_app, lightcraft.import_file + +When: the user wants to add a photo stored in Files to the LightCraft library. +Steps: +1. call_tool tool=desktop.open_app app=lightcraft +2. call_tool tool=lightcraft.import_file path=/Photos/trip/IMG_0001.cr2 +Check: lightcraft.library_info shows one more photo in the library. +Gotchas: change path= to a photo the app can read (image, dng, nef, cr2, arw, raf, orf, rw2); LightCraft has a library, not documents, so there is no save copy; a file too large to open is refused and the reason shows in the app status line. diff --git a/agent/apps/lightcraft/tools.js b/agent/apps/lightcraft/tools.js new file mode 100644 index 0000000..68d7c73 --- /dev/null +++ b/agent/apps/lightcraft/tools.js @@ -0,0 +1,286 @@ +// Ported from storytold/lightcraft@v0.21.1: the page's automation surface (apps/lightcraft-web +// src/web.rs command(), :824, and src/automation.rs params()) plus the engine command registry +// (crates/engine/src/cmd.rs command_specs() and the cmd! specs per module). +// The page installs only window.lightcraft = { command } (vendor index.html); command(id, +// paramsText) resolves the result as JSON text and rejects with the app's error. There is no +// command list on the page, so this pack has no list_commands and run_command does not check +// the id against a list (report). +// The tools run in Buddy's frame and read the page straight off the app window (no shared +// craft adapter: the page has no request/execute/commands surface). +import { ToolError } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { filesCall, openFromBytes, readOpenFile } from '../../shared/craft-files.js'; + +const APP = 'lightcraft'; +const NEEDS = ['host', 'app:lightcraft']; +// run_command ids that destroy or replace data, from the engine command registry (grep of the +// cmd! ids in crates/engine/src/cmd): effectFor marks those calls destructive, so the policy +// asks. Prefixes: mask.delete covers mask.deleteAll/mask.deleteEffect, develop.reset covers +// develop.resetControl. +const DESTRUCTIVE = [ + 'photo.delete', 'photo.deletePermanently', 'library.emptyRecentlyDeleted', + 'library.removeFolder', 'library.forgetLocal', 'preset.delete', 'profile.deleteImported', + 'mask.delete', 'history.clear', 'keyword.deleteSet', 'label.deleteSet', + 'export.deletePreset', 'filter.deletePreset', 'metadata.deletePreset', + 'album.clearQuick', 'version.delete', 'develop.reset', 'crop.reset', + 'spot.delete', 'redeye.delete', 'pointColor.delete', +]; + +const PAGE_TIMEOUT_MS = 30000; +const sleep = ms => new Promise(done => setTimeout(done, ms)); + +// The page API: wait for window.lightcraft on the editor frame, like the shared adapter polls +// window. (agent/shared/craft.js), but for this page's own command() surface. +async function pageApi(host) { + const wrapper = await host.appWindow(APP); + const win = wrapper?.document?.getElementById?.('editor')?.contentWindow; + if (!win) throw new ToolError('not_available', 'the LightCraft window has no editor frame', ''); + const polls = Math.max(1, Math.ceil(PAGE_TIMEOUT_MS / 100)); + for (let i = 0; i < polls; i++) { + const api = win[APP]; + if (api?.command) return api; + if (i + 1 < polls) await sleep(100); // no wait after the last poll + } + throw new ToolError('not_available', `the lightcraft page did not finish loading (waited ${PAGE_TIMEOUT_MS} ms)`, ''); +} + +// One command: the page's lightcraft.command(id, JSON text) (web.rs:824). Blank params mean +// {} on the page side; here the object is always stringified, so send {} for none. The reply +// is the result as JSON text; parse it back. +async function command(host, id, params = {}) { + const api = await pageApi(host); + const text = await api.command(id, JSON.stringify(params)); + try { + return JSON.parse(text); + } catch { + return text; // the page only sends JSON text; fall through for anything else + } +} + +// A key=value value: booleans, numbers, a [ ... ] or { ... } JSON value, else a string. +const parseValue = raw => { + if (/^(true|false)$/i.test(raw)) return raw.toLowerCase() === 'true'; + if (/^-?\d+(\.\d+)?$/.test(raw)) return Number(raw); + if (raw.startsWith('[') || raw.startsWith('{')) { + try { return JSON.parse(raw); } catch { /* not JSON: keep as text */ } + } + return raw; +}; + +// run_command params: a JSON object (one line) or key=value lines. +const parseCommandParams = text => { + const raw = String(text ?? '').trim(); + if (!raw) return {}; + if (raw.startsWith('{')) { + try { return JSON.parse(raw); } catch { /* fall through to key=value lines */ } + } + const out = {}; + for (const line of raw.split('\n')) { + const row = line.trim(); + if (!row) continue; + const eq = row.indexOf('='); + if (eq <= 0) throw new ToolError('invalid_argument', `bad params line "${row}": use key=value or a JSON object`, ''); + out[row.slice(0, eq).trim()] = parseValue(row.slice(eq + 1).trim()); + } + return out; +}; + +// commands.rs pick(): copy the listed keys (when present) into a params object. +const pick = (args, keys) => { + const out = {}; + for (const key of keys) if (args[key] !== undefined) out[key] = args[key]; + return out; +}; + +export const pack = { id: APP, title: 'LightCraft' }; + +export const tools = [ + { + name: 'lightcraft.library_info', + purpose: 'Show the library: photo counts, folders, space, worker state.', + when: 'Use when the user asks what is in the library, or before planning edits.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is in the library?' }], + // cmd/library/specs.rs:1378 library.info (query, {} params) + run: async (args, ctx) => command(ctx.host, 'library.info'), + }, + { + name: 'lightcraft.select', + purpose: 'Select photos by id (or clear the selection).', + when: 'Use when the user wants specific photos selected.', + params: { ids: { type: 'list', description: 'Photo ids; the selection is cleared when omitted' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { ids: [3, 7] }, says: 'Select these two photos' }], + // cmd/library/specs.rs:331 library.select {ids?} + run: async (args, ctx) => command(ctx.host, 'library.select', pick(args, ['ids'])), + }, + { + name: 'lightcraft.filter', + purpose: 'Filter the library view by rating, flag, label, keyword and more.', + when: 'Use when the user wants to narrow the library view.', + params: { filter: { type: 'text', description: 'JSON object of filter keys: {"rating":4,"flag":"pick","keyword":"trip"}; partial, keys from the app filter bar' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { filter: '{"rating":4}' }, says: 'Show only the 4-star photos' }], + // cmd/library/specs.rs:86 library.filter: a partial Filter {text?, rating?, ratingOp?, flag?, + // flags?, label?, kind?, merged?, edited?, date?, libraryFolder?, keyword?, person?, camera?} + run: async (args, ctx) => { + let filter; + try { + filter = JSON.parse(String(args.filter ?? '').trim() || '{}'); + } catch { + throw new ToolError('invalid_argument', 'filter must be a JSON object, e.g. {"rating":4}', ''); + } + return command(ctx.host, 'library.filter', filter); + }, + }, + { + name: 'lightcraft.sort', + purpose: 'Sort the library view by date, name, rating, size or shuffle.', + when: 'Use when the user wants the library sorted a different way.', + params: { + key: { type: 'string', description: 'captureDate, importDate, editDate, fileName, rating, fileSize or random' }, + ascending: { type: 'boolean', description: 'Sort ascending (default: the app setting)' }, + group: { type: 'string', description: 'Group by auto, none, day, month or year' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { key: 'rating', ascending: false }, says: 'Sort by rating, best first' }], + // cmd/library/specs.rs:232 library.sort {key?, ascending?, group?, seed?} + run: async (args, ctx) => command(ctx.host, 'library.sort', pick(args, ['key', 'ascending', 'group'])), + }, + { + name: 'lightcraft.rate', + purpose: 'Rate the selection or given photos 0 to 5 stars.', + when: 'Use when the user wants to rate photos.', + params: { + rating: { type: 'integer', required: true, description: '0 to 5 stars', min: 0, max: 5 }, + ids: { type: 'list', description: 'Photo ids; the selection when omitted' }, + advance: { type: 'boolean', description: 'Move the selection to the next photo when it no longer matches the view' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { rating: 4 }, says: 'Rate the selection 4 stars' }], + // cmd/library/specs.rs:455 photo.rate {rating: 0..5, ids?, advance?} + run: async (args, ctx) => command(ctx.host, 'photo.rate', pick(args, ['rating', 'ids', 'advance'])), + }, + { + name: 'lightcraft.rotate', + purpose: 'Rotate photos 90 degrees left or right.', + when: 'Use when the user wants to rotate photos straight.', + params: { + direction: { type: 'enum', values: ['left', 'right'], required: true, description: 'Rotate left (counter-clockwise) or right' }, + ids: { type: 'list', description: 'Photo ids; the selection when omitted' }, + }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { direction: 'right' }, says: 'Rotate the selection clockwise' }], + // cmd/library/specs.rs:592 photo.rotateLeft / photo.rotateRight {ids?} + run: async (args, ctx) => command(ctx.host, args.direction === 'left' ? 'photo.rotateLeft' : 'photo.rotateRight', pick(args, ['ids'])), + }, + { + name: 'lightcraft.delete', + purpose: 'Delete photos (they move to Recently Deleted).', + when: 'Use when the user wants to delete photos.', + params: { ids: { type: 'list', description: 'Photo ids; the selection when omitted' } }, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: { ids: [3] }, says: 'Delete this photo' }], + // cmd/library/specs.rs:657 photo.delete {ids?} - moves to Recently Deleted (not permanent) + run: async (args, ctx) => command(ctx.host, 'photo.delete', pick(args, ['ids'])), + }, + { + name: 'lightcraft.restore', + purpose: 'Restore deleted photos from Recently Deleted.', + when: 'Use when the user wants a deleted photo back.', + params: { ids: { type: 'list', description: 'Photo ids; the selection when omitted' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { ids: [3] }, says: 'Restore that photo' }], + // cmd/library/specs.rs:666 photo.restore {ids?} + run: async (args, ctx) => command(ctx.host, 'photo.restore', pick(args, ['ids'])), + }, + { + name: 'lightcraft.develop_reset', + purpose: 'Reset the develop edits on the selection or given photos.', + when: 'Use when the user wants to undo all edits on a photo.', + params: { ids: { type: 'list', description: 'Photo ids; the selection when omitted' } }, + effect: 'destructive', + needs: NEEDS, + examples: [{ args: {}, says: 'Reset all edits on this photo' }], + // cmd/develop.rs:395 develop.reset {ids?} - the edit history is cleared, so it is + // destructive although the registry does not flag it + run: async (args, ctx) => command(ctx.host, 'develop.reset', pick(args, ['ids'])), + }, + { + name: 'lightcraft.undo', + purpose: 'Undo the last change in the library.', + when: 'Use when the user wants to undo the last change.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Undo that' }], + // cmd/edit.rs:7 edit.undo + run: async (args, ctx) => command(ctx.host, 'edit.undo'), + }, + { + name: 'lightcraft.redo', + purpose: 'Redo the last undone change.', + when: 'Use when the user wants to redo the change they just undid.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Bring that back' }], + // edit.redo (the mirror of edit.undo in the cmd/edit.rs specs) + run: async (args, ctx) => command(ctx.host, 'edit.redo'), + }, + { + name: 'lightcraft.run_command', + purpose: 'Run any LightCraft command by id with parameters.', + when: `Use when a menu action is wanted by id; ${DESTRUCTIVE.join(', ')} are destructive, so ask first.`, + params: { + command: { type: 'string', required: true, description: 'Command id, e.g. library.select, photo.rate, preset.apply, mask.invert' }, + params: { type: 'text', description: 'Parameters as key=value lines or a JSON object; omit for the defaults' }, + }, + effect: 'change', + effectFor: args => (DESTRUCTIVE.some(prefix => String(args.command ?? '').startsWith(prefix)) ? 'destructive' : 'change'), + needs: NEEDS, + examples: [{ args: { command: 'preset.apply', params: 'id=9\namount=50' }, says: 'Apply preset 9 at half strength' }], + // web.rs:824 command(id, paramsText): the page has no command list, so the id is not + // checked against one; the page refuses bad params with its own error + run: async (args, ctx) => command(ctx.host, args.command, parseCommandParams(args.params)), + }, + { + name: 'lightcraft.import_file', + purpose: 'Import a photo from Files into the LightCraft library.', + when: 'Use when the user wants to import a photo. Not for opening the app itself; that is desktop.open_app.', + params: { path: { type: 'path', required: false, description: 'A Files path to a photo (an image or camera RAW)' } }, + effect: 'change', + needs: ['host', 'app:lightcraft', 'files'], + examples: [{ args: { path: '/Photos/trip/IMG_0001.cr2' }, says: 'Add this photo to the library' }], + // LightCraft only imports (it has a library, not documents), so it gets import_file and no + // save_copy. Drives the wrapper's own #file input (app.mjs:38); the wrapper posts + // lightcraft:open, which the page's host bridge adds to the library as one dropped on the + // window (apps/lightcraft-web/src/host.rs Incoming::Open, web.rs run_host). The page has no + // inspect, so the result carries no opened field; a refused open (too large) posts + // lightcraft:failed to the wrapper's #error line. + run: async (args, ctx) => { + const file = await readOpenFile(ctx, args.path, { id: APP, title: 'LightCraft' }); + const wrapper = await ctx.host.appWindow(APP); + return openFromBytes(wrapper, APP, file.name, file.bytes); + }, + }, +]; + +// Live-check exports (brief): every engine command id the pack passes to lightcraft.command +// (the fixed ids of the thin tools; run_command passes arbitrary ids from the engine +// registry, which the page has no list for). No control methods: the page surface is +// command() only. +export const usesCommands = [ + 'library.info', 'library.select', 'library.filter', 'library.sort', 'photo.rate', + 'photo.rotateLeft', 'photo.rotateRight', 'photo.delete', 'photo.restore', + 'develop.reset', 'edit.undo', 'edit.redo', +]; +export const usesMethods = []; // the page has no request() surface (no METHODS entry) diff --git a/agent/apps/materialcraft/skills.md b/agent/apps/materialcraft/skills.md new file mode 100644 index 0000000..cba994d --- /dev/null +++ b/agent/apps/materialcraft/skills.md @@ -0,0 +1,37 @@ +## Open a package or bitmap from Files +slug: open-a-package-from-files +summary: Open a .sbs or .mcraft package, or drop in a bitmap, that is stored in Files in MaterialCraft. +keywords: open, load, from files, sbs, mcraft, bitmap, image, shader +tools: desktop.open_app, materialcraft.open_file + +When: the user wants to open a MaterialCraft package or add a bitmap that is stored in Files. +Steps: +1. call_tool tool=desktop.open_app app=materialcraft +2. call_tool tool=materialcraft.open_file path=/MaterialCraft/wood.sbs +Check: materialcraft.status shows the wrapper opened the file; the package or bitmap appears in the editor. +Gotchas: change path= to a .sbs or .mcraft package or an image to use as a bitmap; a new WebPC session starts with an empty graph; if the open package reports unsaved changes the wrapper asks first before opening the new file. + +## Save a copy of the package to Files +slug: save-a-package-copy-to-files +summary: Save a copy of the MaterialCraft package to Files as the editor produces it. +keywords: save, copy, to files, sbs, mcraft, export, keep, write +tools: desktop.open_app, materialcraft.save_copy + +When: the user wants to keep a copy of the MaterialCraft package in Files. +Steps: +1. call_tool tool=desktop.open_app app=materialcraft +2. call_tool tool=materialcraft.save_copy path=/MaterialCraft/wood.sbs +Check: the result has the saved Files path and size; files.info on that path shows the same size. +Gotchas: the tool waits for the user to save in the editor; the package saves as .sbs, .mcraft or a _sbs.zip web transport, so match the target to what the editor produces (a mismatch is refused with the produced extension as the fix); if the path exists the tool errors, so choose another name or pass overwrite=true (which is destructive). + +## Build shader graphs in the editor +slug: build-shader-graphs-in-the-editor +summary: MaterialCraft builds shader graphs for game engines in its native editor; the agent opens the app and the user works the editor. +keywords: shader, graph, material, sbs, node, texture, game engine, build +tools: desktop.open_app, materialcraft.status + +When: the user wants to build or edit a shader graph in MaterialCraft. +Steps: +1. call_tool tool=desktop.open_app app=materialcraft +Check: the editor is open and showing the graph; the user drives the native node editor directly. +Gotchas: the agent has no MaterialCraft editing tools, so it opens the app and the user works the editor; materialcraft.status shows the wrapper status line; other exports download normally and are not saved to Files. diff --git a/agent/apps/materialcraft/tools.js b/agent/apps/materialcraft/tools.js new file mode 100644 index 0000000..d320fcc --- /dev/null +++ b/agent/apps/materialcraft/tools.js @@ -0,0 +1,92 @@ +// MaterialCraft pack (M4 file tier). MaterialCraft is a standalone wrapper app (scripts/pc/craft/ +// releases.mjs mode:'standalone', open:'drop') with no page API: the editor page has no +// window.materialcraft request/execute/commands surface, so these tools drive the WebPC wrapper's +// own mechanisms through the wrapper window (the pcHost.appWindow result) instead of a page API. +// +// Open: drive the wrapper's own #file input (scripts/pc/craft/app.mjs:38, no isTrusted check) +// with a File built from (name, bytes); the wrapper's handler (app.mjs:35-38) posts +// materialcraft:open, and the standalone bootstrap opens it as a drop on the canvas +// (scripts/pc/craft/bootstrap.js:75-84, openMethod 'drop'). A .sbs or .mcraft package opens, an +// image drops in as a bitmap (releases.mjs accept). There is no page API to poll, so open_file +// returns as soon as the file is handed to the wrapper (no opened field). +// +// Save: the user saves in the editor (the package). The app's native download click is captured +// by the bootstrap's anchor hook (bootstrap.js:92-98, the wrapper's nativeSource for materialcraft +// is .sbs / .mcraft / _sbs.zip, releases.mjs) and posted to the wrapper as materialcraft:save +// (app.mjs:29-33). save_copy waits on that message and writes the bytes to Files; the target +// extension is checked against the captured name, so the save matches whatever the package +// produced (.sbs, .mcraft or a _sbs.zip web transport). +import { callLine } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { filesCall, openFromBytes, readOpenFile, saveBytesCopy } from '../../shared/craft-files.js'; + +const APP = 'materialcraft'; +const TITLE = 'MaterialCraft'; +const NEEDS = ['host', 'app:materialcraft']; + +export const pack = { id: APP, title: TITLE }; + +export const tools = [ + { + name: 'materialcraft.open_file', + purpose: 'Open a package or drop in a bitmap from Files in MaterialCraft.', + when: 'Use when the user wants a package or bitmap. Not for opening the app itself; that is desktop.open_app.', + params: { path: { type: 'path', required: false, description: 'A Files path to a .sbs/.mcraft package or an image' } }, + effect: 'change', + needs: ['host', 'app:materialcraft', 'files'], + examples: [{ args: { path: '/MaterialCraft/wood.sbs' }, says: 'Open the material package from Files' }], + // Drives the wrapper's own #file input (app.mjs:38); the wrapper posts materialcraft:open and + // the standalone bootstrap drops it on the canvas (bootstrap.js:75-84). A .sbs or .mcraft + // package opens, an image drops in as a bitmap. No page API to confirm the load, so the + // result has the file name and size but no opened field. + run: async (args, ctx) => { + const file = await readOpenFile(ctx, args.path, { id: APP, title: 'MaterialCraft' }); + const wrapper = await ctx.host.appWindow(APP); + return openFromBytes(wrapper, APP, file.name, file.bytes); + }, + }, + { + name: 'materialcraft.save_copy', + purpose: 'Save a copy of the MaterialCraft package to Files.', + when: 'Use when the user wants to keep a copy of the package in Files.', + params: { + path: { type: 'path', required: true, description: 'The Files path to write the copy to, e.g. /MaterialCraft/wood.sbs' }, + overwrite: { type: 'boolean', description: 'Replace the file when the path already exists; false when omitted' }, + }, + effect: 'change', + effectFor: args => (args.overwrite ? 'destructive' : 'change'), + needs: ['host', 'app:materialcraft', 'files'], + examples: [{ args: { path: '/MaterialCraft/wood.sbs' }, says: 'Save a copy of the package to Files' }], + // No page API to start the save: the user saves in the editor (the package) and the bootstrap + // captures the download click (bootstrap.js:92-98; the wrapper's nativeSource for materialcraft + // is .sbs / .mcraft / _sbs.zip, releases.mjs). craft is null, so saveBytesCopy uses the + // capture path only; the target extension is checked against the captured name. + run: async (args, ctx) => { + const wrapper = await ctx.host.appWindow(APP); + const save = await saveBytesCopy(null, { id: APP, title: TITLE, wrapperWindow: wrapper, target: args.path, tool: 'materialcraft.save_copy' }); + const written = await filesCall( + ctx, + files => files.writeBytes(args.path, save.bytes, { overwrite: Boolean(args.overwrite) }), + error => (error.code === 'exists' ? callLine('materialcraft.save_copy', { path: args.path, overwrite: true }) : ''), + ); + return { path: written.path, name: save.name, size: written.size, created: written.created, ...(save.note ? { note: save.note } : {}) }; + }, + }, + { + name: 'materialcraft.status', + purpose: 'Show the MaterialCraft wrapper status line and error.', + when: 'Use when the user asks what MaterialCraft is doing, or after an open or save that may have failed.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is MaterialCraft doing?' }], + // The app has no page API to read, so this reads the wrapper's own state: the #status line + // and the #error line (hidden when empty) that the wrapper keeps (app.mjs:7-8). + run: async (args, ctx) => { + const wrapper = await ctx.host.appWindow(APP); + const status = wrapper?.document?.getElementById?.('status')?.textContent ?? ''; + const err = wrapper?.document?.getElementById?.('error'); + const error = (err && !err.hidden && err.textContent) || ''; + return { status, ...(error ? { error } : {}) }; + }, + }, +]; diff --git a/agent/apps/media/skills.md b/agent/apps/media/skills.md new file mode 100644 index 0000000..59767ab --- /dev/null +++ b/agent/apps/media/skills.md @@ -0,0 +1,65 @@ +## Play a file +slug: play-a-file +summary: Play an audio or video file from the Files app in the Media Player. +keywords: play, open, listen, watch, audio, video, song, file +tools: desktop.open_app, media.play_file + +When: the user wants to play, open or listen to an audio or video file. +Steps: +1. call_tool tool=desktop.open_app app=media +2. call_tool tool=media.play_file path=/music/tune.mp3 +Check: the result has the file name and says whether it is playing. +Gotchas: change path=; only audio and video files are accepted; if playing is false with a note, autoplay was blocked by the browser, so tell the user to click Play in the Media app. + +## Pause the playback +slug: pause-the-playback +summary: Pause the audio or video that is playing. +keywords: pause, stop, hold, quiet, halt +tools: desktop.open_app, media.pause + +When: the user wants the current playback to stop for a while. +Steps: +1. call_tool tool=desktop.open_app app=media +2. call_tool tool=media.pause +Check: media.status shows playing is false. +Gotchas: pausing keeps the position, so the same file continues from where it stopped; use it instead of stopping the whole app. + +## Move the playback position +slug: move-the-playback-position +summary: Jump to a given second of the current media. +keywords: seek, jump, skip to, position, fast forward, rewind, second +tools: desktop.open_app, media.seek + +When: the user wants to jump forward or back in the current media. +Steps: +1. call_tool tool=desktop.open_app app=media +2. call_tool tool=media.status +3. call_tool tool=media.seek seconds=30 +Check: the result reports the new time. +Gotchas: change seconds=; the media must be loaded first (check media.status duration), and seconds must stay within the media length. + +## Change the volume +slug: change-the-volume +summary: Set the Media Player volume from 0 to 100 percent. +keywords: volume, louder, quieter, mute, sound level, percent +tools: desktop.open_app, media.volume + +When: the user wants the playback louder or softer. +Steps: +1. call_tool tool=desktop.open_app app=media +2. call_tool tool=media.volume percent=50 +Check: the result reports the new volume. +Gotchas: change percent=; the value is a percent from 0 to 100 and is saved by the app; for full silence use percent=0, the separate Mute button toggles muting. + +## Check what is playing +slug: check-what-is-playing +summary: Report the current title, position, volume and the playlist. +keywords: status, playing, now, current, what, playlist, track +tools: desktop.open_app, media.status + +When: the user asks what is playing, or before controlling playback. +Steps: +1. call_tool tool=desktop.open_app app=media +2. call_tool tool=media.status +Check: the result has the title, the playing flag, the position and the playlist. +Gotchas: a null duration means nothing is loaded yet; the playlist lists every item with its current flag. diff --git a/agent/apps/media/tools.js b/agent/apps/media/tools.js new file mode 100644 index 0000000..78ad5ca --- /dev/null +++ b/agent/apps/media/tools.js @@ -0,0 +1,151 @@ +// Media pack: drive the Media Player app (src/scripts/pc/apps/media.mjs). The app runs directly +// in its utility page (kind iframe in catalog.yaml, no inner iframe; pcHost.appWindow('media') +// resolves the page's own window). Live DOM: #media-video (the media element), #media-title, +// #media-status, #media-seek, #media-volume (a 0..1 range whose input event runs the app's +// setVolume, which clamps and saves to localStorage pc:media:volume) and the playlist #media- +// list (li[data-i] rows with a .mp-name, the selected row carrying class "sel"). The app's own +// "Open from Files" path builds a Blob from the picked bytes and adds it to the playlist +// (media.mjs:134), which this pack mirrors on the video element directly: the playlist is +// module-scoped in media.mjs, so the video element is the reachable surface. The app notes +// (media.mjs:34) that programmatic play() can be blocked by the real-browser autoplay policy, +// so play_file reports the live playing state plus a note instead of failing. +import { ToolError } from '../../../src/apps/ai-agent/runtime/args.mjs'; +import { mediaKind } from '../../../src/scripts/pc/media/playlist.mjs'; + +const APP = 'media'; +const NEEDS = ['host', 'app:media']; +const NOT_HERE = 'The Media Player is not available here (Buddy is not running inside WebPC).'; + +// Gate on ctx.host (needs: ['host', 'app:media']), then turn host rejections, which carry a +// code (unknown_app, not_open, not_iframe, timeout, invalid_argument), and Files readBytes +// rejections (not_found, not_a_file, too_large) into a ToolError. +const call = (ctx, fn) => { + if (!ctx.host) throw new ToolError('not_available', NOT_HERE, ''); + return Promise.resolve() + .then(() => fn(ctx.host)) + .catch(error => { + if (error instanceof ToolError) throw error; + throw new ToolError(error.code || 'app_error', error.message, ''); + }); +}; + +// The appWindow result is the media page window itself (no inner iframe). +const page = host => host.appWindow(APP); + +export const pack = { id: APP, title: 'Media Player' }; + +export const tools = [ + { + name: 'media.play_file', + purpose: 'Play an audio or video file from the Files app in the Media Player.', + when: 'Use when the user wants to play, open or listen to an audio or video file.', + params: { path: { type: 'path', required: true, description: 'The file path in the Files app, e.g. /music/tune.mp3' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { path: '/music/tune.mp3' }, says: 'Play this song' }], + // readBytes (src/apps/ai-agent/runtime/files-ctx.mjs:64) gives the bytes; mediaKind + // (src/scripts/pc/media/playlist.mjs, the app's own type check) gates the format. The app's + // Open-from-Files path wraps the bytes in a Blob and plays them, so mirror that on the video + // element. video.play() may be rejected by the autoplay policy (media.mjs:34), which is + // reported as playing false plus a note, not an error. + run: async (args, ctx) => call(ctx, async host => { + const read = ctx.files?.readBytes; + if (typeof read !== 'function') throw new ToolError('not_available', 'the Files tools are not enabled here, so no file can be played', ''); + const file = await read(args.path); + const kind = mediaKind(file.name); + if (!kind) throw new ToolError('invalid_argument', `"${file.name}" is not an audio or video file`, ''); + const win = await page(host); + const video = win.document.getElementById('media-video'); + video.src = win.URL.createObjectURL(new win.Blob([file.bytes])); + win.document.getElementById('media-title').textContent = file.name; + let note; + try { + await video.play(); + } catch { + note = 'autoplay was blocked by the browser; click the Play button in the Media app to hear it'; + } + return { name: file.name, kind, playing: video.paused === false, ...(note ? { note } : {}) }; + }), + }, + { + name: 'media.pause', + purpose: 'Pause the media that is playing.', + when: 'Use when the user wants playback to stop for a while.', + params: {}, + effect: 'change', + needs: NEEDS, + examples: [{ args: {}, says: 'Pause the music' }], + // The app's own pause path is video.pause() (media.mjs:61 toggle()). + run: async (args, ctx) => call(ctx, async host => { + const win = await page(host); + win.document.getElementById('media-video').pause(); + return { paused: true }; + }), + }, + { + name: 'media.seek', + purpose: 'Move playback to a position in seconds.', + when: 'Use when the user wants to jump forward or back in the media.', + params: { seconds: { type: 'number', required: true, min: 0, description: 'The position in seconds to move to' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { seconds: 30 }, says: 'Jump to 30 seconds' }], + // The app's own seek path is video.currentTime = the seek value (media.mjs:102). The media + // must be loaded first: without metadata video.duration is not finite and a seek is dropped. + run: async (args, ctx) => call(ctx, async host => { + const win = await page(host); + const video = win.document.getElementById('media-video'); + const duration = video.duration; + if (!Number.isFinite(duration) || duration <= 0) throw new ToolError('app_error', 'no media is loaded yet; play a file first', ''); + if (args.seconds < 0 || args.seconds > duration) throw new ToolError('invalid_argument', `seconds must be between 0 and the media length (${Math.floor(duration)} s)`, ''); + video.currentTime = args.seconds; + return { time: video.currentTime }; + }), + }, + { + name: 'media.volume', + purpose: 'Set the playback volume, 0 to 100 percent.', + when: 'Use when the user wants it louder or softer.', + params: { percent: { type: 'integer', required: true, min: 0, max: 100, description: 'The volume in percent' } }, + effect: 'change', + needs: NEEDS, + examples: [{ args: { percent: 50 }, says: 'Half volume' }], + // Drive the app's own volume input (0..1, media.mjs:87): set its value and fire input, so + // the app's setVolume clamps and saves the volume to localStorage the way a user's slider + // would. + run: async (args, ctx) => call(ctx, async host => { + const win = await page(host); + const video = win.document.getElementById('media-video'); + const vol = win.document.getElementById('media-volume'); + vol.value = String(args.percent / 100); + vol.dispatchEvent(new Event('input')); + return { volume: video.volume }; + }), + }, + { + name: 'media.status', + purpose: 'Report what is playing, where, and the playlist.', + when: 'Use when the user asks what is playing, or before controlling playback.', + params: {}, + effect: 'read', + needs: NEEDS, + examples: [{ args: {}, says: 'What is playing?' }], + // Live state only: the video element for position/duration/volume/muted, #media-title for + // the name, and #media-list rows for the playlist (media.mjs renderList: li[data-i] with + // .mp-name, the selected row carrying class "sel"). + run: async (args, ctx) => call(ctx, async host => { + const win = await page(host); + const video = win.document.getElementById('media-video'); + const rows = [...win.document.querySelectorAll('#media-list li[data-i]')]; + return { + title: win.document.getElementById('media-title').textContent, + playing: video.paused === false, + time: video.currentTime, + duration: Number.isFinite(video.duration) ? video.duration : null, + volume: video.volume, + muted: video.muted, + playlist: rows.map(row => ({ name: row.querySelector('.mp-name')?.textContent ?? '', current: /(^|\s)sel(\s|$)/.test(row.className) })), + }; + }), + }, +]; diff --git a/agent/apps/nettools/skills.md b/agent/apps/nettools/skills.md new file mode 100644 index 0000000..50e7cf3 --- /dev/null +++ b/agent/apps/nettools/skills.md @@ -0,0 +1,77 @@ +## Look up a DNS record +slug: look-up-a-dns-record +summary: Look up a DNS record (A, AAAA, MX, TXT, NS, PTR) over HTTPS via Cloudflare or Google. +keywords: dns, resolve, a record, mx, txt, pointer, reverse lookup, doh +tools: desktop.open_app, nettools.dns_lookup + +When: the user wants to resolve a domain or check what a DNS record points to. +Steps: +1. call_tool tool=desktop.open_app app=nettools +2. call_tool tool=nettools.dns_lookup name=example.com type=A +Check: the result names the provider and the status (for example NOERROR) plus the answers. +Gotchas: change name= and type=; for PTR enter an IP address (the reverse name is built by the app); the lookup goes to an external DNS-over-HTTPS service, so it needs the network. + +## Fetch a domain or IP record +slug: fetch-a-domain-or-ip-record +summary: Fetch the RDAP registration record (nameservers, dates, status) for a domain or IP. +keywords: rdap, whois, registration, nameservers, registrar, registry record +tools: desktop.open_app, nettools.rdap + +When: the user asks who registered a domain, or for the registration data of a domain or IP. +Steps: +1. call_tool tool=desktop.open_app app=nettools +2. call_tool tool=nettools.rdap query=example.com +Check: the result has the nameservers, the status and the dates, when the registry reports them. +Gotchas: change query= (a domain or an IP address); rdap.org redirects to the responsible registry, so the answer names that registry; this is registry data, not the current DNS records. + +## Calculate a subnet +slug: calculate-a-subnet +summary: Compute the network, mask, host range and address count of a CIDR block. +keywords: subnet, cidr, network, mask, ip range, hosts in, broadcast +tools: desktop.open_app, nettools.subnet + +When: the user asks about a CIDR block, an IP range or how many addresses a prefix has. +Steps: +1. call_tool tool=desktop.open_app app=nettools +2. call_tool tool=nettools.subnet cidr=10.0.0.0/24 +Check: the result has the network, the mask and the address count (plus the first and last host for IPv4). +Gotchas: change cidr= to the block in
/ form, IPv4 or IPv6; this runs fully locally, so it never sends a request. + +## Check a password strength +slug: check-a-password-strength +summary: Check how strong a password is, with a score and crack-time estimates. +keywords: password, strength, crack, zxcvbn, score, guessable +tools: desktop.open_app, nettools.password_strength + +When: the user wants a password rated, or wants to know if one is weak. +Steps: +1. call_tool tool=desktop.open_app app=nettools +2. call_tool tool=nettools.password_strength text=correct-horse-battery-staple +Check: the result has the score out of 4 and the offline and online attack estimates. +Gotchas: change text=; the check is fully local (the password is not stored, logged or sent); if the user pastes a real password into the chat, tell them it now sits in the conversation. + +## Encrypt a file with age +slug: encrypt-a-file-with-age +summary: Encrypt a file from the Files app with an age passphrase; the result downloads. +keywords: age, encrypt, encrypt file, passphrase, secure file, age encryption +tools: desktop.open_app, nettools.age_encrypt + +When: the user wants a file encrypted with an age passphrase before sending or storing it. +Steps: +1. call_tool tool=desktop.open_app app=nettools +2. call_tool tool=nettools.age_encrypt path=/docs/report.pdf passphrase=s3cret-passphrase +Check: the result says the file was encrypted and that the .age file was downloaded. +Gotchas: change path= and passphrase=; the file is fully read into memory, so keep it a reasonable size; the download lands in the user's downloads folder as .age; encryption is fully local, nothing is uploaded. + +## Decrypt an age file +slug: decrypt-an-age-file +summary: Decrypt an age file from the Files app with a passphrase; the result downloads. +keywords: age, decrypt, age file, passphrase, open encrypted file +tools: desktop.open_app, nettools.age_decrypt + +When: the user has an .age file and the passphrase and wants it decrypted. +Steps: +1. call_tool tool=desktop.open_app app=nettools +2. call_tool tool=nettools.age_decrypt path=/docs/report.pdf.age passphrase=s3cret-passphrase +Check: the result says the file was decrypted and that it was downloaded under its original name. +Gotchas: change path= and passphrase=; a wrong passphrase is reported as a decryption failure, not a crash; decryption is fully local and the result downloads to the user's downloads folder. diff --git a/agent/apps/nettools/tools.js b/agent/apps/nettools/tools.js new file mode 100644 index 0000000..0bd51d6 --- /dev/null +++ b/agent/apps/nettools/tools.js @@ -0,0 +1,231 @@ +// Nettools pack: drive the Network and Security Tools app (scripts/pc/nettools/*.mjs), which +// runs in the #nettools-frame inner iframe of the app page (pcHost.appWindow('nettools') +// resolves the wrapper page; the vendor page sets window.webpcNettools = { ready: true } once +// the tab shell is mounted, main.mjs:29, which the wrapper polls, scripts/pc/apps/nettools.mjs). +// Tabs lazy-load on first click (ui.mjs mountTabs:60-77): the tab button is a +// nav.nt-tabs button.nt-tab with dataset.id, the active panel is the .nt-content that is not +// hidden, and before its module mounts the panel holds the "Loading