Craft Anything

A native, pure-Rust app that shows anyone how a piece of software works, with
evidence-backed answers, then helps them rebuild it. It ships a desktop app, a
CLI and an MCP server, all driven by one engine.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Brandon ThomasandClaude Opus 5.5 committed 2026-10-31 10:52:14 -04:00
commit f64ae3bf3c
597 files changed
+187757

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
[alias]
xtask = "run --quiet --package xtask --"
+6
View File
@@ -0,0 +1,6 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
reviews:
auto_review:
# Dependabot bumps are checked by CI; skip CodeRabbit reviews on them.
ignore_usernames:
- "dependabot[bot]"
+7
View File
@@ -0,0 +1,7 @@
# LF everywhere: files are embedded with include_str! and must not change with the checkout platform.
* text=auto eol=lf
*.png binary
*.jpg binary
*.ico binary
*.icns binary
*.ttf binary
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
# Refuse commits that carry API keys, private keys, secret env values or a home folder path.
# Enable once per clone: git config core.hooksPath .githooks
exec cargo xtask secrets
+16
View File
@@ -0,0 +1,16 @@
---
name: Something doesn't work
about: A crash, a hang, a wrong result, or a build that goes wrong
labels: bug
---
<!-- A security problem? Don't open an issue: use the Security tab's "Report a vulnerability"
(SECURITY.md). Don't paste API keys, tokens or private files here. -->
**What you did:** <!-- the app screen or CLI command, and what you pointed it at -->
**What happened:** <!-- and what you expected instead -->
**Version and system:** <!-- `craft-anything-cli --version`, and Windows / macOS / Linux -->
**Output:** <!-- `craft-anything-cli doctor`, and the error or the project's last lines -->
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: true
contact_links:
- name: Report a security problem
url: https://github.com/storytold/craft-anything/security/advisories/new
about: Please report vulnerabilities privately (SECURITY.md), not as an issue.
+11
View File
@@ -0,0 +1,11 @@
---
name: An idea
about: Something Craft Anything should do, study or make
labels: idea
---
**What you'd like to do:** <!-- in your words: what you'd point it at, and what you'd want back -->
**Why:** <!-- what it would help you understand or build -->
<!-- Planned work lives in docs/ROADMAP.md; if your idea fits an item there, say which. -->
+4
View File
@@ -0,0 +1,4 @@
# Custom runner labels actionlint can't know about.
self-hosted-runner:
labels:
- github-ubuntu-16core # org 16-core larger runner, used by the FreeBSD VM jobs (release.yml, freebsd.yml)
+16
View File
@@ -0,0 +1,16 @@
<!-- The title is the commit message (PRs are squash-merged): plain English, what changed for the
person or developer, with the roadmap id, e.g. "Decode radio recordings with rtl_433 (R3.1)". -->
**Roadmap item:** <!-- R1.4, R3.9… and the line you claimed in docs/ROADMAP.md -->
**What changed:**
**Verified:** <!-- tests run, and anything tried for real (a live build, a real file, a device) -->
**Not verified:** <!-- what you couldn't try, so the docs and STATUS say so -->
- [ ] `cargo fmt --all --check`, `cargo clippy -p <crates> --all-targets -- -D warnings`,
`cargo test -p <crates>`, `cargo xtask layers`, `cargo xtask secrets`
- [ ] Docs in this PR: the roadmap line ticked (and new `- [ ]` lines for what's left), STATUS if
what works changed, `cargo xtask tools` if tools were added
- [ ] No other tool's code, scripts or wording copied (behaviour only; AGENTS.md)
+99
View File
@@ -0,0 +1,99 @@
# CI for pull requests and main: format, clippy, tests, dependency layering, the tool list and
# the wasm32 check (the same gates as `cargo xtask ci`). Linux only: macOS is built and tested only
# by release.yml (the org's macOS runners are kept for releases; craftrules release/playbook.md),
# and Windows/FreeBSD packaging have their own workflows.
name: CI
# Every pull request and every push to main, once the repository is public (GitHub-hosted runners
# are free for public repositories; while it's private, the jobs below are skipped unless started by
# hand, so they cost nothing).
on:
pull_request:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
# Debug and test builds keep line tables (file:line in panic backtraces) but drop the rest of the
# debug info: faster codegen and links, and a smaller target dir.
CARGO_PROFILE_DEV_DEBUG: line-tables-only
# A newer push to a PR branch cancels its older run. Runs on main are never cancelled, so every
# main state that gets a run is checked to the end.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
test:
name: test (ubuntu-latest)
if: github.event_name == 'workflow_dispatch' || !github.event.repository.private
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Linux system dependencies (egui/winit/rfd)
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev \
libgl1-mesa-dev libgtk-3-dev
- uses: dtolnay/rust-toolchain@stable
with:
components: clippy, rustfmt
# Only main saves caches; PRs restore main's, so PR caches don't evict main's.
- uses: Swatinem/rust-cache@v2
with:
save-if: ${{ github.ref == 'refs/heads/main' }}
cache-on-failure: true
- name: Format
run: cargo fmt --all -- --check
- name: Clippy
run: cargo clippy --workspace --all-targets --locked -- -D warnings
# Every crate's tests run even when one fails, so one failure can't hide another.
- name: Test
run: cargo test --workspace --locked --no-fail-fast
- name: Dependency layering
run: cargo run --locked -q -p xtask -- layers
- name: Tool list
run: cargo run --locked -q -p xtask -- tools --check
- name: Generated schemas
run: cargo run --locked -q -p xtask -- schemas --check
# No keys, tokens, private keys or local paths in what would be committed.
- name: Secret scan
run: cargo run --locked -q -p xtask -- secrets
wasm:
name: wasm32 check
if: github.event_name == 'workflow_dispatch' || !github.event.repository.private
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
with:
key: wasm32
save-if: ${{ github.ref == 'refs/heads/main' }}
cache-on-failure: true
# The L0-L2 analysis crates and apps/craft-anything-web must keep compiling for the browser.
- name: Check wasm-safe crates
run: cargo run --locked -q -p xtask -- wasm
- name: Check the web app
run: cargo check --locked --target wasm32-unknown-unknown -p craft-anything-web
+95
View File
@@ -0,0 +1,95 @@
# Builds and tests the workspace on FreeBSD, inside a FreeBSD VM on a Linux runner
# (GitHub has no FreeBSD runners). The `package` job checks packaging/freebsd/package.sh (the
# release job runs it for real), so a broken FreeBSD package fails here before it can fail a
# release. Nothing is uploaded from the build job and no secrets are used.
name: FreeBSD
# Pushes to main, pull requests that touch FreeBSD packaging or dependencies, and by hand. While
# the repository is private the jobs are skipped unless started by hand, so they cost nothing.
on:
push:
branches: [main]
pull_request:
paths:
- Cargo.toml
- Cargo.lock
- "**/Cargo.toml"
- .github/workflows/freebsd.yml
- packaging/freebsd/**
- packaging/env.sh
workflow_dispatch:
concurrency:
group: freebsd-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
freebsd:
name: FreeBSD 14 (build + test)
if: github.event_name == 'workflow_dispatch' || !github.event.repository.private
# A private repo's ubuntu-latest (2 vCPUs, 7 GB) is too small for this VM; the org's 16-core
# larger runner fits it (craftrules learnings/ci-and-release.md).
runs-on: github-ubuntu-16core
timeout-minutes: 300
steps:
- uses: actions/checkout@v4
- name: Build and test in a FreeBSD VM
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
# Nothing to bring back; copying the target dir out of the VM fails on large builds.
copyback: false
prepare: |
pkg install -y git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2
curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal
run: |
set -e
. "$HOME/.cargo/env"
# The checkout is synced in under another owner; let tests that call git read it.
git config --global --add safe.directory "*"
rustc --version
CARGO_PROFILE_DEV_DEBUG=0 cargo build --workspace --all-targets --locked
CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked
package:
name: FreeBSD 14 (package)
# The release build takes a while: only for pull requests that touch FreeBSD packaging (or
# dependencies) and on demand, not on every push to main.
if: github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && !github.event.repository.private)
runs-on: github-ubuntu-16core
timeout-minutes: 150
steps:
- uses: actions/checkout@v4
- name: Package in a FreeBSD VM
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
prepare: |
pkg install -y bash curl git pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
run: |
set -e
. "$HOME/.cargo/env"
git config --global --add safe.directory "$PWD"
# Build outside the checkout so only dist/ is copied back out of the VM.
export CARGO_TARGET_DIR=/var/tmp/craft-anything-target CARGO_BUILD_JOBS=4
bash packaging/freebsd/package.sh
# Every part the package must have.
tar -tzf dist/release/craft-anything-*-freebsd-x86_64.tar.gz >/var/tmp/contents.txt
for want in '/bin/craft-anything$' '/bin/craft-anything-cli$' '/share/applications/ai\.storyteller\.craft-anything\.desktop$' '/share/icons/hicolor/' '/share/doc/craft-anything/LICENSE-MIT$' '/share/doc/craft-anything/NOTICE$'; do
grep -Eq "$want" /var/tmp/contents.txt || { echo "missing from the package: $want"; exit 1; }
done
- uses: actions/upload-artifact@v4
with:
name: freebsd-package
path: dist/release/*
if-no-files-found: error
+70
View File
@@ -0,0 +1,70 @@
# Quick static checks for the release pipeline (seconds, no Rust build): workflow syntax,
# packaging shell/PowerShell scripts, and the Linux desktop/AppStream/Flatpak metadata.
name: Packaging lint
# enable on PRs when M4 starts (docs/ROADMAP.md)
on:
workflow_dispatch:
permissions:
contents: read
concurrency:
group: packaging-lint-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
runs-on: ubuntu-latest
env:
ACTIONLINT_VERSION: 1.7.12
steps:
- uses: actions/checkout@v4
- name: Install tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends shellcheck desktop-file-utils appstream libxml2-utils python3-yaml
curl -fsSL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz -C "$RUNNER_TEMP" actionlint
- name: actionlint
run: |
"$RUNNER_TEMP/actionlint" -color
- name: shellcheck
run: shellcheck packaging/*.sh packaging/*/*.sh packaging/linux/AppRun
- name: AppImage AppRun desktop integration
run: bash packaging/linux/apprun-test.sh
- name: PowerShell
shell: pwsh
run: |
foreach ($f in Get-ChildItem packaging/windows/*.ps1) {
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$errors) | Out-Null
if ($errors) { $errors | ForEach-Object { Write-Output "::error file=$($f.Name)::$_" }; exit 1 }
Write-Output "ok $($f.Name)"
}
./packaging/windows/check-icons.ps1
- name: FreeBSD package layout (dry run, no build)
run: bash packaging/freebsd/package.sh --dry-run
- name: Package metadata names only this app
run: |
other=$(grep -rhoiIE '[a-z]*craft[a-z_-]*' packaging/ .github/ | tr '[:upper:]' '[:lower:]' | grep -vE '^(craft|artcraft|getartcraft|craftrules|launchcraftanything|craft[-_]?anything.*)$' | sort -u)
if [ -n "$other" ]; then
echo "::error::package metadata names another app: $other"
exit 1
fi
- name: XML, desktop entry, AppStream, Flatpak manifest
run: |
xmllint --noout packaging/windows/craft-anything.wxs packaging/windows/craft-anything.en-us.wxl packaging/macos/*.plist* packaging/linux/*.xml*
desktop-file-validate packaging/linux/ai.storyteller.craft-anything.desktop
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.craft-anything.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.craft-anything.metainfo.xml"
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.craft-anything.metainfo.xml"
python3 - <<'EOF'
import yaml
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.craft-anything.yml"))
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.craft-anything.bundle.yml"))
for m in (src, bundle):
assert m["id"] == "ai.storyteller.craft-anything" and m["command"] == "craft-anything", m["id"]
for key in ("runtime", "runtime-version", "sdk", "finish-args"):
assert src[key] == bundle[key], f"Flatpak manifests disagree on {key}: {src[key]} vs {bundle[key]}"
print("Flatpak manifests ok")
EOF
+457
View File
@@ -0,0 +1,457 @@
# Release pipeline: every push to `release` builds signed installers for every platform and
# creates or updates the draft GitHub Release "Craft Anything v<version>". See docs/releasing.md.
#
# Only the jobs that read secrets (macOS and Windows signing, and the draft release) run in the
# `release` environment (restricted to the `release` branch), which holds the signing secrets; the
# rest build on any branch, so `gh workflow run release.yml --ref <branch>` is a real dry run.
# Every secret is optional: missing ones produce unsigned artifacts and a warning, never a failed
# build. Playbook: storytold/craftrules release/playbook.md.
name: Release
on:
push:
branches: [release]
workflow_dispatch:
inputs:
version:
description: "Version override for a test run, e.g. 0.2.0-rc.1 (empty: Cargo.toml)"
type: string
default: ""
permissions:
contents: read
concurrency:
group: release-${{ github.ref }}
# Never cancel a run mid-notarization or mid-upload; a newer push waits its turn.
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
CRAFT_ANYTHING_BUILD_SHA: ${{ github.sha }}
INPUT_VERSION: ${{ inputs.version }}
jobs:
version:
name: version
runs-on: ubuntu-latest
# No `environment: release`: this job reads no secrets, so a branch dry run can run it.
outputs:
version: ${{ steps.v.outputs.version }}
date: ${{ steps.v.outputs.date }}
prerelease: ${{ steps.v.outputs.prerelease }}
steps:
- uses: actions/checkout@v4
- id: v
name: Resolve version
run: |
. packaging/env.sh
v="${INPUT_VERSION#v}"
v="${v:-$VERSION}"
if ! printf '%s' "$v" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
echo "::error::'$v' is not a version like 1.2.3 or 1.2.3-rc.1"
exit 1
fi
case "$v" in *-*) pre=true ;; *) pre=false ;; esac
{
echo "version=$v"
echo "date=$(date -u +%Y-%m-%d)"
echo "prerelease=$pre"
} >>"$GITHUB_OUTPUT"
echo "### Craft Anything v$v (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
macos:
name: macOS universal
needs: version
runs-on: macos-15-xlarge # M2 Pro larger runner; use only in release.yml (actions_macos_xl budget caps spend)
environment: release
env:
CRAFT_ANYTHING_VERSION: ${{ needs.version.outputs.version }}
CRAFT_ANYTHING_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: aarch64-apple-darwin, x86_64-apple-darwin
- uses: Swatinem/rust-cache@v2
with:
key: release-macos-universal
- name: Apply version override
if: inputs.version != ''
run: cargo run --locked -q -p xtask -- version set "$CRAFT_ANYTHING_VERSION"
- name: Import signing certificate
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: packaging/macos/import-cert.sh
- name: Build, sign, notarize
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: packaging/macos/package.sh --arch universal
# Unpacks the CLI zip and checks the binary users get: Developer ID, hardened runtime,
# timestamp, and Gatekeeper's notarization lookup (codesign --verify, spctl). Also the DMG's
# stapled ticket. Strict when the signing secrets are present, warnings otherwise.
- name: Verify signatures and notarization
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: packaging/macos/verify.sh --arch universal
- uses: actions/upload-artifact@v4
with:
name: release-macos
path: dist/release/*
if-no-files-found: error
- name: Remove temporary keychain
if: always()
run: |
if [ -n "${MACOS_KEYCHAIN:-}" ]; then security delete-keychain "$MACOS_KEYCHAIN" || true; fi
windows:
name: Windows ${{ matrix.arch }}
needs: version
runs-on: windows-latest
environment: release
strategy:
fail-fast: false
matrix:
include:
- { arch: x64, target: x86_64-pc-windows-msvc }
- { arch: x86, target: i686-pc-windows-msvc }
# Windows on ARM: cross-compiled on the x64 runner, so signing and WiX run as above.
# .github/workflows/windows-arm64.yml installs and runs it on ARM64 hardware.
- { arch: arm64, target: aarch64-pc-windows-msvc }
env:
CRAFT_ANYTHING_VERSION: ${{ needs.version.outputs.version }}
CRAFT_ANYTHING_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- uses: Swatinem/rust-cache@v2
with:
key: release-windows-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
shell: bash
run: cargo run --locked -q -p xtask -- version set "$CRAFT_ANYTHING_VERSION"
- name: Install WiX
shell: pwsh
run: |
dotnet tool install --global wix --version 5.0.2
wix extension add -g WixToolset.UI.wixext/5.0.2 WixToolset.Util.wixext/5.0.2
- name: Build, sign, package
shell: pwsh
env:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
# The exe must carry its icon and VERSIONINFO (apps/craft-anything/build.rs).
CRAFT_ANYTHING_REQUIRE_WINRES: "1"
run: ./packaging/windows/package.ps1 -Arch ${{ matrix.arch }}
- uses: actions/upload-artifact@v4
with:
name: release-windows-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
linux:
name: Linux ${{ matrix.arch }}
needs: version
# The oldest GitHub-hosted image, so the binaries only need glibc >= 2.35 (Ubuntu 22.04+,
# Debian 12+, Fedora 36+, RHEL 10). See docs/releasing.md.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job reads no secrets, so a branch dry run can run it.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-22.04, deb: amd64 }
- { arch: aarch64, runner: ubuntu-22.04-arm, deb: arm64 }
env:
CRAFT_ANYTHING_VERSION: ${{ needs.version.outputs.version }}
CRAFT_ANYTHING_BUILD_DATE: ${{ needs.version.outputs.date }}
NFPM_VERSION: 2.47.0
steps:
- uses: actions/checkout@v4
- name: Install build and packaging tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev \
desktop-file-utils appstream python3-yaml zsync
curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \
"https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb"
sudo dpkg -i "$RUNNER_TEMP/nfpm.deb"
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
with:
key: release-linux-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
run: cargo run --locked -q -p xtask -- version set "$CRAFT_ANYTHING_VERSION"
- name: Build and package (AppImage, deb, rpm, tar.gz)
run: packaging/linux/package.sh
- name: Check the packages
run: |
dpkg-deb --info dist/release/*.deb
dpkg-deb --contents dist/release/*.deb | grep -E 'usr/bin/craft-anything$|metainfo|applications'
ldd target/release/craft-anything
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.craft-anything.yml')); assert m['id'] == 'ai.storyteller.craft-anything'"
for appimage in dist/release/*.AppImage; do
chmod +x "$appimage"
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
# Update information is embedded, and the .zsync for delta updates sits beside it.
"$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|'
test -s "$appimage.zsync"
done
- uses: actions/upload-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
flatpak:
name: Flatpak ${{ matrix.arch }}
needs: [version, linux]
# Repackages the Linux job's tarball (the same binaries as the AppImage/deb/rpm); no Rust
# build here. 24.04 for a newer flatpak-builder (1.4) than 22.04 ships.
runs-on: ${{ matrix.runner }}
# No `environment: release`: this job signs nothing, so it gets no release secrets.
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-24.04 }
- { arch: aarch64, runner: ubuntu-24.04-arm }
env:
CRAFT_ANYTHING_VERSION: ${{ needs.version.outputs.version }}
CRAFT_ANYTHING_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: actions/download-artifact@v4
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- name: Install flatpak-builder
run: |
sudo apt-get update
# librsvg2-common: the SVG pixbuf loader. flatpak-builder runs the host's
# `appstreamcli compose`, which renders the scalable icon and fails without it.
sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common
# Ubuntu 24.04's AppArmor blocks the unprivileged user namespaces bubblewrap needs.
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
- name: Build the Flatpak bundle
run: packaging/linux/flatpak-bundle.sh "dist/linux/craft-anything-$CRAFT_ANYTHING_VERSION-linux-${{ matrix.arch }}.tar.gz"
- uses: actions/upload-artifact@v4
with:
name: release-flatpak-${{ matrix.arch }}
path: dist/release/*.flatpak
if-no-files-found: error
freebsd:
name: FreeBSD x86_64
needs: version
# GitHub has no FreeBSD runners: build in a FreeBSD 14.3 VM, the same image and packages as
# .github/workflows/freebsd.yml. A private repo's ubuntu-latest has 2 vCPUs and 7 GB, too small
# for this VM (QEMU "cannot set up guest memory"), so it runs on the org's 16-core larger runner.
runs-on: github-ubuntu-16core
timeout-minutes: 180
# No `environment: release`: this job signs nothing, so it gets no release secrets.
env:
CRAFT_ANYTHING_VERSION: ${{ needs.version.outputs.version }}
CRAFT_ANYTHING_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
if: inputs.version != ''
- name: Apply version override
if: inputs.version != ''
run: cargo run --locked -q -p xtask -- version set "$CRAFT_ANYTHING_VERSION"
- name: Build and package in a FreeBSD VM (tar.gz)
# vmactions/freebsd-vm v1.5.9, pinned by commit (it runs our build).
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
# Passed into the VM by name; never templated into the script below.
envs: "CRAFT_ANYTHING_VERSION CRAFT_ANYTHING_BUILD_DATE CRAFT_ANYTHING_BUILD_SHA"
# The FreeBSD CI packages, plus bash for the packaging script.
prepare: |
pkg install -y bash git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
run: |
set -e
. "$HOME/.cargo/env"
git config --global --add safe.directory "$PWD"
# Build outside the checkout so only dist/ is copied back out of the VM (copying the
# target dir back fails on large builds). 4 jobs: more runs the VM out of memory.
export CARGO_TARGET_DIR=/var/tmp/craft-anything-target CARGO_BUILD_JOBS=4
bash packaging/freebsd/package.sh
# Every part the package must have.
tar -tzf dist/release/craft-anything-*-freebsd-x86_64.tar.gz >"$HOME/freebsd-contents.txt"
for want in '/bin/craft-anything$' '/bin/craft-anything-cli$' '/share/applications/ai\.storyteller\.craft-anything\.desktop$' '/share/icons/hicolor/' '/share/doc/craft-anything/LICENSE-MIT$' '/share/doc/craft-anything/NOTICE$'; do
grep -Eq "$want" "$HOME/freebsd-contents.txt" || { echo "missing from the package: $want"; exit 1; }
done
- uses: actions/upload-artifact@v4
with:
name: release-freebsd-x86_64
path: dist/release/*
if-no-files-found: error
web:
name: Web (wasm)
needs: version
runs-on: ubuntu-latest
# No `environment: release`: this job reads no secrets, so a branch dry run can run it.
env:
CRAFT_ANYTHING_VERSION: ${{ needs.version.outputs.version }}
CRAFT_ANYTHING_BUILD_DATE: ${{ needs.version.outputs.date }}
TRUNK_VERSION: 0.21.14
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@v2
with:
key: release-web
- name: Install trunk
run: |
curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz -C "$HOME/.cargo/bin" trunk
trunk --version
- name: Apply version override
if: inputs.version != ''
run: cargo run --locked -q -p xtask -- version set "$CRAFT_ANYTHING_VERSION"
- name: Build and zip
run: packaging/web/package.sh
- uses: actions/upload-artifact@v4
with:
name: release-web
path: dist/release/*
if-no-files-found: error
linux-riscv64:
name: Linux riscv64
needs: version
# Cross-compiled on x86_64 (no hosted RISC-V runners) against the runner's own Ubuntu release
# from ports.ubuntu.com, so the binaries need that release's glibc (24.04: 2.39). 22.04's
# riscv64 ports lag its amd64 updates, which breaks the multiarch install. tar.gz only; the
# CLI is smoke-tested under QEMU.
runs-on: ubuntu-24.04
# No `environment: release`: this job reads no secrets, so a branch dry run can run it.
env:
CRAFT_ANYTHING_VERSION: ${{ needs.version.outputs.version }}
CRAFT_ANYTHING_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@stable
with:
targets: riscv64gc-unknown-linux-gnu
- uses: Swatinem/rust-cache@v2
with:
key: release-linux-riscv64
- name: Apply version override
if: inputs.version != ''
run: cargo run --locked -q -p xtask -- version set "$CRAFT_ANYTHING_VERSION"
- name: Install cross-compilation dependencies
run: |
. /etc/os-release
sudo dpkg --add-architecture riscv64
# Pin the existing (archive.ubuntu.com) sources to amd64; riscv64 comes from ports.
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
sudo sed -i '/^Types: deb/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
fi
if [ -f /etc/apt/sources.list ]; then
sudo sed -i 's/^deb /deb [arch=amd64] /g' /etc/apt/sources.list
sudo sed -i 's/^deb-src /deb-src [arch=amd64] /g' /etc/apt/sources.list
fi
for suite in "$VERSION_CODENAME" "$VERSION_CODENAME-updates" "$VERSION_CODENAME-security"; do
echo "deb [arch=riscv64] http://ports.ubuntu.com/ubuntu-ports $suite main universe restricted multiverse"
done | sudo tee /etc/apt/sources.list.d/riscv64.list
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
gcc-riscv64-linux-gnu binutils-riscv64-linux-gnu libc6-dev-riscv64-cross libc6-dev:riscv64 qemu-user \
libxkbcommon-dev:riscv64 libwayland-dev:riscv64 libx11-dev:riscv64 libxrandr-dev:riscv64 \
libxi-dev:riscv64 libgl1-mesa-dev:riscv64
- name: Build and package (tar.gz)
env:
CARGO_TARGET_RISCV64GC_UNKNOWN_LINUX_GNU_LINKER: riscv64-linux-gnu-gcc
PKG_CONFIG_SYSROOT_DIR: /
PKG_CONFIG_PATH: /usr/lib/riscv64-linux-gnu/pkgconfig:/usr/share/pkgconfig
PKG_CONFIG_ALLOW_CROSS: "1"
CROSS_ARCH: riscv64
CROSS_TARGET: riscv64gc-unknown-linux-gnu
CROSS_COMPILE: riscv64-linux-gnu-
EMULATOR: qemu-riscv64
QEMU_LD_PREFIX: /usr/riscv64-linux-gnu
run: packaging/linux/package.sh --formats tar
- uses: actions/upload-artifact@v4
with:
name: release-linux-riscv64
path: dist/release/*.tar.gz
if-no-files-found: error
release:
name: Draft GitHub Release
needs: [version, macos, windows, linux, linux-riscv64, flatpak, freebsd, web]
runs-on: ubuntu-latest
environment: release
permissions:
contents: write
env:
VERSION: ${{ needs.version.outputs.version }}
PRERELEASE: ${{ needs.version.outputs.prerelease }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/download-artifact@v4
with:
pattern: release-*
path: artifacts
merge-multiple: true
- name: Checksums
working-directory: artifacts
run: |
sha256sum -- * | tee SHA256SUMS.txt
- name: Create or update the draft release
working-directory: artifacts
run: |
tag="v$VERSION"
title="Craft Anything v$VERSION"
pre=()
if [ "$PRERELEASE" = true ]; then pre=(--prerelease); fi
if draft="$(gh release view "$tag" --json isDraft --jq .isDraft 2>/dev/null)"; then
if [ "$draft" != "true" ]; then
echo "::error::Release $tag is already published. Bump the version (cargo run -p xtask -- version set X.Y.Z) before pushing to release."
exit 1
fi
echo "Updating draft $tag: replacing its assets"
gh release view "$tag" --json assets --jq '.assets[].name' | while read -r asset; do
gh release delete-asset "$tag" "$asset" --yes
done
gh release edit "$tag" --draft --title "$title" --target "$GITHUB_SHA" --prerelease="$PRERELEASE"
gh release upload "$tag" --clobber -- *
else
echo "Creating draft $tag"
gh release create "$tag" --draft --title "$title" --target "$GITHUB_SHA" --generate-notes "${pre[@]}" -- *
fi
{
echo "Draft release **$title** at \`${GITHUB_SHA::9}\`:"
echo
sed 's/^/ /' SHA256SUMS.txt
} >>"$GITHUB_STEP_SUMMARY"
+86
View File
@@ -0,0 +1,86 @@
# Windows on ARM: package the ARM64 release the way release.yml does (cross-compiled on an x64
# runner, unsigned here), then install that MSI on a Windows 11 ARM64 runner, check the installed
# binaries are ARM64, run the CLI natively, and uninstall. (A native ARM64 `cargo test` job is left
# out for now: egui UI tests have hit an intermittent access violation there.)
name: Windows ARM64
# enable on PRs when M4 starts (docs/ROADMAP.md)
on:
workflow_dispatch:
concurrency:
group: windows-arm64-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
jobs:
package:
name: package (cross-compiled on x64)
runs-on: windows-latest
timeout-minutes: 90
steps:
- uses: actions/checkout@v4
- uses: dtolnay/rust-toolchain@89b12181fb390509a0842a86cc55eeb8eb928c1d # stable
with:
targets: aarch64-pc-windows-msvc
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2
with:
key: windows-arm64-package
- name: Install WiX
shell: pwsh
run: |
dotnet tool install --global wix --version 5.0.2
wix extension add -g WixToolset.UI.wixext/5.0.2 WixToolset.Util.wixext/5.0.2
- name: Build and package (unsigned)
shell: pwsh
env:
DIST: ${{ github.workspace }}\dist\arm64
run: ./packaging/windows/package.ps1 -Arch arm64
- uses: actions/upload-artifact@v4
with:
name: craft-anything-windows-arm64
path: dist/arm64/*
if-no-files-found: error
retention-days: 7
install:
name: install and run on ARM64
needs: package
runs-on: windows-11-arm
timeout-minutes: 30
steps:
- uses: actions/download-artifact@v4
with:
name: craft-anything-windows-arm64
path: dist
- name: Install the MSI, check it, run it, uninstall it
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$msi = (Get-ChildItem dist/*.msi | Select-Object -First 1).FullName
$p = Start-Process msiexec.exe -ArgumentList '/i', "`"$msi`"", '/qn', '/l*v', 'install.log' -Wait -PassThru
if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; throw "msiexec /i exited $($p.ExitCode)" }
$dir = Join-Path $env:ProgramFiles 'Craft Anything'
foreach ($exe in 'craft-anything.exe', 'craft-anything-cli.exe') {
$path = Join-Path $dir $exe
if (-not (Test-Path $path)) { throw "$exe not installed in $dir" }
$bytes = [System.IO.File]::ReadAllBytes($path)
$machine = [BitConverter]::ToUInt16($bytes, [BitConverter]::ToInt32($bytes, 0x3C) + 4)
if ($machine -ne 0xAA64) { throw "$exe is for machine 0x$('{0:X}' -f $machine), not ARM64" }
Write-Output "ok $path (ARM64)"
}
# The installed CLI runs natively on ARM64.
$cli = Join-Path $dir 'craft-anything-cli.exe'
$out = & $cli --version 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) { Write-Output $out; throw "$cli --version exited $LASTEXITCODE" }
Write-Output "ok $(Split-Path -Leaf $cli) --version: $($out.Trim())"
$p = Start-Process msiexec.exe -ArgumentList '/x', "`"$msi`"", '/qn' -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "msiexec /x exited $($p.ExitCode)" }
if (Test-Path (Join-Path $dir 'craft-anything.exe')) { throw 'uninstall left craft-anything.exe behind' }
Write-Output 'ok uninstalled'
+16
View File
@@ -0,0 +1,16 @@
*~
plan/
plans/
/target
/log/
corpus/
/dist/
.claude/worktrees/
# Secrets and local settings (`cargo xtask secrets` refuses them too)
.env
.env.*
*.pem
*.p12
*.pfx
*.key
.claude/settings.local.json
+162
View File
@@ -0,0 +1,162 @@
# AGENTS.md: guide for AI agents and contributors
Craft Anything is a native, pure-Rust app that shows anyone how a piece of software works (programs, apps, files,
websites, phones) with evidence-backed answers, then helps them rebuild it. It ships a desktop app (egui), a CLI and
an MCP server, all driven by one engine. Display name **Craft Anything**; machine names `craft-anything-*`; bundle id
`ai.storyteller.craft-anything`. Standards shared across the Crafting Apps live in `../craftrules` (read its
`AGENTS.md`); follow them. Repos never share code.
**Original work only:** never copy code, scripts, schemas, names, assets or wording from another project, and
never name other reverse-engineering products in source, docs, UI or commit messages.
## Workspace map
```text
crates/
evidence L0 Evidence records, canonical ids, confidence, unknowns, ToolError (the error contract)
formats L0 Standalone parsers (no workspace deps, no I/O): ELF/PE/Mach-O/WASM/DEX/APK/ASAR/plist/.NET/Go/…
disasm L1 Our own native engine (Clean room): decode, functions, CFG, xrefs, call graph, pseudo-C
js L1 JavaScript/Electron/web bundles: parse, module graph, IPC, source maps, unbundling
analysis L2 Analyzers producing evidence (triage, dossiers, trace, compare, app graph, rebuild ledger)
platform L2 Native services: owned processes, PTY capture, sandbox, engine store, atomic files
engines L3 Optional external engines: Ghidra bridge (Deep mode), adb, CDP, Frida, JADX, Apktool…
engine L4 Session, projects (.cany), workspaces (what the person is making), the inbox
(questions/approvals), ToolSpec registry, settings, consent, the tool list
ai L5 AI backends (Anthropic, OpenAI, OpenRouter, local, agent CLIs, SSH) + agent loop + crews,
and the rebuild workflow (study → build → check → refine)
mcp L5 MCP server: progressive toolsets, resources, prompts
setup L5 Connect to coding-agent apps; doctor; uninstall
ui-egui L6 The egui interface (Beginner + Experienced). The only crate that may use egui/eframe/winit/rfd.
testkit Test helpers and synthetic sample builders
apps/ craft-anything (desktop) · craft-anything-cli (CLI + `mcp`) · craft-anything-web (browser viewer)
xtask/ cargo xtask layers | tools [--check] | wasm | secrets [--history] | ci | version [set X.Y.Z]
```
Layering is enforced by `cargo xtask layers`. Register new crates in `xtask/src/main.rs`.
## Golden rules
1. **Never crash** (`../craftrules/standards/never-crash.md`). Hostile input is our main input. No
`unwrap`/`expect`/`panic!`/`todo!`/`unimplemented!`/`unreachable!`/indexing on input-derived values in non-test
code; every production crate root carries the deny attribute. Checked arithmetic, bounded recursion, capped
allocations. Every crash fix gets a regression test.
2. **Everything is a tool.** User-visible behaviour = a `ToolSpec` in `crates/engine/src/tools/<area>.rs` with id,
title, summary, beginner text, toolset, effects, requires, a schemars params struct, and `run`. Register the
module with one line in `tools/mod.rs`. UI, CLI, MCP and the AI agent all dispatch by id. Programmatic calls
never open dialogs.
3. **Evidence is the result.** Analysis tools return `ToolOutput::Evidence` built with `EvidenceBuilder` (honest
confidence, limitations, coverage, locations). Large results: summary first, paged views (`offset`/`limit`).
4. **Clean room vs Deep.** `session.clean_room()` is true unless Deep mode is on (`deep_mode`, or `--deep` for one
CLI run). Clean room never looks inside the original: only the tools in `engine/src/clean_room.rs` run, so a new
tool is Deep-only until it's listed there, and it may be listed only if it touches no target or watches from
outside, as a visitor or user would. Deep mode uses every tool; built-in engines must work fully without Ghidra,
which only adds. Evidence records the engine and the flag.
5. **Effects are honest.** Declare every side effect. `EXECUTES_FOREIGN_CODE` and `MUTATES_DEVICE` trigger consent.
6. **Never break wasm** for L0–L2 (`cargo xtask wasm`).
7. **Thin UI.** UI state is serde data; colours/radii come from theme tokens.
8. **No secrets, no personal data** in requests, logs, tests or the repo (it is public): no API keys, tokens,
private keys, `.env` files or local paths, only obvious fakes like `sk-test`. `cargo xtask secrets` checks what
git would commit (`--history` checks every commit); enable the hook once per clone with
`git config core.hooksPath .githooks`. Generic `CraftAnything-dev` User-Agent.
9. **Safe Rust only.** `unsafe_code = "forbid"` everywhere, no exceptions. Prefer pure-Rust crates; any dependency
must be safe to use from safe code.
10. **Never crash, never lock up, around other programs.** Every external program (Ghidra, Java, adb, a browser,
an agent CLI, ssh, git…) runs through `craft_anything_platform::process` only, never `std::process::Command`
directly:
- stdin is closed (or a pipe we write to), never inherited, so nothing can sit waiting at a prompt; ssh gets
`BatchMode=yes`; tools get their non-interactive flags;
- every run has a deadline (wall clock and idle), output is capped and drained on threads so pipes never fill,
and the child (and its process group / Job Object) is killed on timeout, cancel or drop;
- a missing program, non-zero exit, bad output or timeout is a `ToolError` with a plain-English remediation,
never a panic or a hang;
- nothing slow ever runs on the UI thread: the UI sends work to background threads and polls results.
## Working rules (mandatory)
These apply to every change by every agent and contributor, whether or not anyone mentions them.
### Roles and ownership
- `docs/ROADMAP.md` is the plan: each item has an id (`R<milestone>.<n>`), an **owner**, a status and pending
changes (`- [ ]` lines). Owners are roles, never people's names: **maintainers** (the project's maintainers
steer it; agents may take its unclaimed pending changes, but anything marked **decision** waits for a
maintainer) or **open** (anyone may take it).
- **Claim before you start:** put `— claimed: <name>, branch <branch>` on the pending change and push your branch
early (or open a draft PR) so others see it. Never take a change someone else has claimed.
- Work in the order the roadmap's "Order and dependencies" table gives; an item starts only when its
dependencies are done.
- A person's explicit instruction for a task overrides these rules for that task only; otherwise they apply to
every change, without being asked.
### Before you write code
- Pick work from `docs/ROADMAP.md` only. Don't start an item that is claimed, `blocked`, or waiting on a
**decision**, and don't start one whose dependencies aren't done.
- Claim the pending change first (name + branch, in its own small commit), so no two agents do the same work.
- Read the code you'll touch and check STATUS.md and the roadmap for gaps it depends on. If you find new gaps or
dependencies, add them to the roadmap rather than widening your change.
### Git workflow
- Never commit to `main`. Branch from an up-to-date `main` with a standard prefix, then the roadmap id if
there is one: `feature/`, `bugfix/`, `hotfix/` (urgent fix to released code), `refactor/`, `docs/`, `test/`
or `chore/` (tooling, deps, CI). Example: `feature/r1.1-target-kind`.
- One roadmap item (or pending change) per PR. Keep PRs small and reviewable. No unrelated refactors or drive-by
formatting.
- Open a PR into `main`. It is **squash-merged**, so the PR title is the commit message: plain English, present
tense, what changed for the person or developer.
- Rebase on `main` before asking for review. Never force-push someone else's branch.
- Parallel agents work in their own git worktree and their own `CARGO_TARGET_DIR` (see "Parallel agents" below).
- Before every commit and push, check `git branch --show-current`; push by name (`git push origin <branch>`).
### Architecture
- **Headless first.** Every capability works without the GUI: engine → tools → CLI/MCP, with the GUI as one
thin client. Orchestration, persistence and process control never live in `ui-egui` or `apps/*`. If the UI
needs something, it calls the same engine API (or tool) the CLI does.
- **Extend through seams.** New target kinds, checks, builders, asset providers and engines are trait
implementations registered in one place. Don't add another arm to a `match` over a closed enum. Prefer traits
and generics with sensible built-in implementations, so forks can swap parts without editing core code.
- **Data over code.** Catalogues (stacks, engine recipes, model ids, prices, install pins) are typed tables, not
string matches or prompt text.
- **Structured results.** Decide on typed fields, never on English text.
- **Versioned files.** Anything we persist has a version field, a schema and a migration path.
- Respect the layers (`cargo xtask layers`); put code at the lowest layer that can own it.
### Done means
- The checks in "Before you finish" pass for the crates you touched. New behaviour has tests; crash fixes have
regression tests.
- Docs updated in the same PR: the roadmap item ticked, STATUS.md if what works changed, `docs/tools.md` if you
added tools.
- Report what you verified and what you didn't. Never claim a live run you didn't do.
- Made a mistake worth not repeating? Add it to `docs/pitfalls.md` in the same PR.
- Found work that's missing or left for later? Add it as a `- [ ]` line under its roadmap item in the same PR
(`cargo xtask pending` lists all open work).
## Extending
`docs/extending.md` says where each kind of addition goes (tools, target kinds, checks, stacks, coding agents,
asset providers, engines, plugins).
## Pitfalls
`docs/pitfalls.md` lists mistakes already made here (git, tests, builds, design) and the rule for each.
It is part of these rules: read it before your first change (Claude Code loads it automatically through
`CLAUDE.md`).
## Before you finish
```sh
cargo fmt --all
cargo test -p <crates you touched>
cargo clippy -p <crates> --all-targets -- -D warnings
cargo xtask layers
cargo xtask secrets # no keys, tokens or local paths in what you commit
cargo xtask wasm # if you touched L0–L2
cargo xtask tools # if you added tools (commit docs/tools.md)
```
Then append a terse entry to `log/devlog.md` (what landed, numbers, what's still open). `log/` is gitignored:
the devlog is a local scratch record; anything others need goes in the PR, `docs/STATUS.md` or `docs/ROADMAP.md`.
## Parallel agents
Own target dir (`CARGO_TARGET_DIR=target/agent-<name>`), own files. Shared files (`engine/src/tools/mod.rs`,
`engine/src/lib.rs`, workspace `Cargo.toml`) get small surgical edits; re-read right before editing. Write manifests
atomically (temp file outside `crates/`, then `mv`). If someone else's edit breaks the build, wait and retry.
+50
View File
@@ -0,0 +1,50 @@
# Attribution
Third-party material bundled with Craft Anything, file by file. Rust crates are pulled from
crates.io under their own licences (see `Cargo.lock`) and are not listed here.
## Fonts (`assets/fonts/`)
All fonts are under the SIL Open Font License 1.1. The fonts are embedded unmodified; the
licence requires that the font software is not sold by itself and that reserved font names are
not used for modified versions.
| File | Font | Copyright | Source | Licence |
|---|---|---|---|---|
| `DMSans-Regular.ttf`, `DMSans-Medium.ttf`, `DMSans-Bold.ttf` | DM Sans 1.200 (body text, labels, headlines) | © 2014-2017 Indian Type Foundry, © 2019 Google LLC | https://github.com/googlefonts/dm-fonts (`Sans/Exports/`, commit 23aafb3) | `OFL-DMSans.txt` |
| `JetBrainsMono-Regular.ttf` | JetBrains Mono (code views) | © 2020 The JetBrains Mono Project Authors | https://github.com/JetBrains/JetBrainsMono | `OFL-JetBrainsMono.txt` |
| `GeistMono-Regular.ttf`, `GeistMono-Medium.ttf` | Geist Mono (labels and buttons) | © 2024 The Geist Project Authors | https://github.com/vercel/geist-font (`fonts/GeistMono/ttf/`) | `OFL-GeistMono.txt` |
## egui default fonts (`epaint_default_fonts` crate)
egui embeds these fonts through the `epaint_default_fonts` crate (crate licence:
`(MIT OR Apache-2.0) AND OFL-1.1 AND Ubuntu-font-1.0`). They are embedded unmodified; the licence
texts are in the crate's `fonts/` folder.
| File | Font | Copyright | Licence |
|---|---|---|---|
| `Ubuntu-Light.ttf` | Ubuntu Light (egui's default proportional font) | © 2011 Canonical Ltd. | Ubuntu Font Licence 1.0, `UFL.txt` |
| `NotoEmoji-Regular.ttf` | Noto Emoji | © 2013 Google Inc. | SIL OFL 1.1, `OFL.txt` |
| `Hack-Regular.ttf` | Hack (egui's default monospace font) | © 2018 Source Foundry Authors; Bitstream Vera © 2003 Bitstream, Inc.; DejaVu changes public domain | MIT and Bitstream Vera License, `Hack-Regular.txt` |
| `emoji-icon-font.ttf` | emoji-icon-font | © 2014 John Slegers | MIT, `emoji-icon-font-mit-license.txt` |
## Icons (`assets/icons/`)
| Files | Set | Copyright | Source | Licence |
|---|---|---|---|---|
| `*.svg` | Lucide | © Lucide Icons and Contributors | https://lucide.dev | ISC, `LICENSE-lucide.txt` |
## App icon (`assets/app-icon/`)
The raven, the Crafting Apps' shared icon, made by the ArtCraft team; not open source, used on the
brand terms below. See `assets/app-icon/LICENSE.txt`.
## Brand (`docs/brand/`)
The ArtCraft name, wordmark and logos are trademarks of the ArtCraft Team and are not covered by
the open-source licence; see `docs/brand/LICENSE-brand.txt`.
## Optional build-time fonts
Builds made with `CRAFT_FONTS_DIR` (craft-fonts) also embed the fonts in that folder; their
licences ship with that folder and must be added to this list for such builds.
+11
View File
@@ -0,0 +1,11 @@
# Craft Anything
The rules below are loaded into every session (imports). They are mandatory for every change: follow them
without being asked, unless the person explicitly says otherwise for a specific task.
@AGENTS.md
@docs/pitfalls.md
The plan and assignments are `docs/ROADMAP.md` (open work: `cargo xtask pending`); what works today is
`docs/STATUS.md` (with `docs/tool-status.md`); where additions go is `docs/extending.md`. Private plans may
live in `plan/` (gitignored) when present.
+31
View File
@@ -0,0 +1,31 @@
# Contributing
Thanks for helping. The rules every change follows (people and AI agents alike) are in
[AGENTS.md](AGENTS.md); the mistakes they come from are in [docs/pitfalls.md](docs/pitfalls.md).
In short:
- **Pick work from [docs/ROADMAP.md](docs/ROADMAP.md)** (`cargo xtask pending` lists what's open).
Claim it first: add `— claimed: <your name>, branch <branch>` to its line and open a draft PR,
so nobody else does the same work.
- **One change per PR**, on a branch named `feature/`, `bugfix/`, `docs/`, `test/`, `refactor/` or
`chore/` plus the roadmap id (`feature/r1.4-provider-key-ui`). PRs are squash-merged, so the
title is the commit message: plain English, what changed for the person or developer.
- **Where things go:** [docs/extending.md](docs/extending.md) (tools, target kinds, checks, coding
agents, engines, plugins).
- **Never crash, safe Rust only, every external program through `craft_anything_platform::process`,
no secrets or personal data anywhere.** Everything is our own work: no code, names or wording copied from other projects.
Before you ask for review:
```sh
cargo fmt --all
cargo test -p <crates you touched>
cargo clippy -p <crates> --all-targets -- -D warnings
cargo xtask layers
cargo xtask secrets
```
Enable the secret-scan hook once per clone: `git config core.hooksPath .githooks`.
Code is dual-licensed under MIT or Apache-2.0 ([LICENSE-MIT](LICENSE-MIT),
[LICENSE-APACHE](LICENSE-APACHE)); by contributing you agree your work is licensed the same way.
Generated
+8385
View File
File diff suppressed because it is too large. Load diff
+91
View File
@@ -0,0 +1,91 @@
[workspace]
resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.97"
repository = "https://github.com/storytold/craft-anything"
[workspace.dependencies]
# internal
craft-anything-evidence = { path = "crates/evidence" }
craft-anything-formats = { path = "crates/formats" }
craft-anything-disasm = { path = "crates/disasm" }
craft-anything-js = { path = "crates/js" }
craft-anything-analysis = { path = "crates/analysis" }
craft-anything-platform = { path = "crates/platform" }
craft-anything-engines = { path = "crates/engines" }
craft-anything-engine = { path = "crates/engine" }
craft-anything-ai = { path = "crates/ai" }
craft-anything-mcp = { path = "crates/mcp" }
craft-anything-setup = { path = "crates/setup" }
craft-anything-ui-egui = { path = "crates/ui-egui" }
craft-anything-testkit = { path = "crates/testkit" }
# external
thiserror = "2"
serde = { version = "1", features = ["derive", "rc"] }
serde_json = "1"
sha2 = "0.10"
hex = "0.4"
bitflags = { version = "2", features = ["serde"] }
schemars = "1"
log = "0.4"
toml = "0.9"
eframe = { version = "0.36", default-features = false }
egui = "0.36"
egui_extras = { version = "0.36", default-features = false }
egui_kittest = "0.36"
rfd = "0.17"
rayon = "1"
proptest = "1"
# JavaScript (pure Rust, wasm-safe)
oxc_allocator = "0.153"
oxc_ast = "0.153"
oxc_ast_visit = "0.153"
oxc_parser = "0.153"
oxc_span = "0.153"
oxc_syntax = "0.153"
oxc_codegen = "0.153"
oxc_semantic = "0.153"
miniz_oxide = "0.8"
# native engine (pure Rust)
object = { version = "0.36", default-features = false, features = ["read", "std"] }
iced-x86 = { version = "1.21", default-features = false, features = ["std", "decoder", "intel", "instr_info"] }
yaxpeax-arm = { version = "0.5", default-features = false, features = ["std", "alloc", "fmt"] }
yaxpeax-arch = { version = "0.3", default-features = false, features = ["std", "alloc"] }
rustc-demangle = "0.1"
wasmparser = { version = "0.261", default-features = false, features = ["std", "validate", "features", "component-model", "simd"] }
wasmprinter = { version = "0.261", default-features = false, features = ["component-model"] }
regex = "1"
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
dbg_macro = "warn"
todo = "warn"
[profile.dev.package."*"]
opt-level = 2
[profile.dev]
opt-level = 1
[profile.release]
lto = "thin"
codegen-units = 1
# The browser build (apps/craft-anything-web, `trunk build --release`): small and fast to load.
[profile.web-release]
inherits = "release"
opt-level = "s"
lto = "fat"
codegen-units = 1
debug = false
strip = true
panic = "abort"
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 ArtCraft Team and the Craft Anything contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+31
View File
@@ -0,0 +1,31 @@
Craft Anything
Copyright (c) 2026 ArtCraft Team and the Craft Anything contributors.
Licensed under the MIT License or the Apache License, Version 2.0, at your option
(LICENSE-MIT, LICENSE-APACHE).
The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are
not open source and are not covered by the license above; their terms are in
docs/brand/LICENSE-brand.txt.
Third-party material
This product bundles third-party material under its own licenses, listed below. The per-file
list (author, source, license) is in ATTRIBUTION.md.
- Inter (assets/fonts/) — SIL Open Font License 1.1. See assets/fonts/OFL-Inter.txt.
- JetBrains Mono (assets/fonts/) — SIL Open Font License 1.1. See assets/fonts/OFL-JetBrainsMono.txt.
- Archivo (assets/fonts/) — SIL Open Font License 1.1. See assets/fonts/OFL-Archivo.txt.
- Geist Mono (assets/fonts/) — SIL Open Font License 1.1. See assets/fonts/OFL-GeistMono.txt.
- Lucide icons (assets/icons/) — ISC License. See assets/icons/LICENSE-lucide.txt.
- egui default fonts (embedded by the epaint_default_fonts crate):
- Ubuntu Light — Ubuntu Font Licence 1.0.
- Noto Emoji — SIL Open Font License 1.1.
- Hack — MIT License; contains Bitstream Vera glyphs under the Bitstream Vera License.
- emoji-icon-font (Copyright (c) 2014 John Slegers) — MIT License.
The licence texts ship in that crate's fonts/ folder (UFL.txt, OFL.txt, Hack-Regular.txt,
emoji-icon-font-mit-license.txt) and in the third-party licence bundle (docs/licences.md).
Rust crates are listed with their licences in the third-party licence bundle shipped with each
release (see docs/licences.md).
Builds made with craft-fonts (CRAFT_FONTS_DIR) also embed the fonts listed in ATTRIBUTION.md.
+330
View File
@@ -0,0 +1,330 @@
<p align="center">
<a href="https://getartcraft.com/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/brand/artcraft-logo-white.svg">
<img alt="ArtCraft" src="docs/brand/artcraft-logo.svg" width="200">
</picture>
</a>
</p>
<p align="center">
<img src="assets/app-icon/hicolor/256x256/apps/ai.storyteller.craft-anything.png" width="128" height="128" alt="Craft Anything icon: an engraved raven on a blue tile">
</p>
<h1 align="center">Craft Anything</h1>
<p align="center">
<b>See how any website, app or game works, then have AI build your own version; an open-source, clean-room engine in pure Rust.</b><br>
Point it at a target, say what you want, and it studies the original with real inspection tools,<br>
has a coding agent build a new project, checks the result against the original and refines it.
</p>
<p align="center">
<img alt="100% Rust" src="https://img.shields.io/badge/100%25-Rust-b7410e?style=flat-square&logo=rust">
<img alt="macOS · Windows · Linux · FreeBSD · Web" src="https://img.shields.io/badge/macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20FreeBSD%20%C2%B7%20Web-native-2d81ff?style=flat-square">
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-3a3a3a?style=flat-square">
<img alt="Status: early alpha" src="https://img.shields.io/badge/status-early%20alpha-d69e2e?style=flat-square">
</p>
<p align="center">
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
</p>
<p align="center">
<a href="#downloads"><b>Download Craft Anything</b></a> ·
<a href="https://getartcraft.com/">ArtCraft</a> ·
<a href="https://getartcraft.com/apps">All Crafting Apps</a>
</p>
<br>
<p align="center">
<img src="docs/images/project-website.png" alt="A website project in Craft Anything: the check lists what doesn't match yet and how alike each page is, the builder says its version is ready, an approval card asks before running a command, and the plan shows two of four steps done" width="100%">
<br>
<sub>A website project: each check says how alike the build is, you approve anything outside the rules, and the plan shows what's left.</sub>
</p>
> [!NOTE]
> **ArtCraft is a community of artists from all walks of life.** Painters, photographers,
> filmmakers, illustrators, designers, animators, hobbyists, and people who picked up a pencil
> last week. If you make things, you're one of us. **[Come say hi on Discord](https://discord.gg/artcraft).**
<p align="center">
<a href="#how-it-works">How it works</a> ·
<a href="#two-ways-to-use-it">Two ways to use it</a> ·
<a href="#ai">AI</a> ·
<a href="#built-for-agents">Agents</a> ·
<a href="#under-the-hood">Under the hood</a> ·
<a href="#get-started">Get started</a> ·
<a href="#status">Status</a> ·
<a href="#downloads">Downloads</a> ·
<a href="https://discord.gg/artcraft">Discord</a>
</p>
<br>
<table>
<tr>
<td width="25%" valign="top">
<h3>🔍 Study anything</h3>
Websites, desktop apps, phone apps, games and files: real inspection tools find out how they're built and what they do, with the evidence behind every answer.
</td>
<td width="25%" valign="top">
<h3>🛠️ Build your own</h3>
Say what you want ("Recreate this website", "Recreate this game's gameplay in Rust") and a coding agent builds a new project in the stack you ask for.
</td>
<td width="25%" valign="top">
<h3>✅ Checked, not guessed</h3>
Every build is compared with the original (pages at three screen widths, a game's own self-test, an app's runs) and refined until it's close.
</td>
<td width="25%" valign="top">
<h3>🤖 Agent-ready</h3>
284 tools, each one a CLI command and an MCP tool, so any agent can drive the same engine the app uses. No AI is needed to inspect.
</td>
</tr>
</table>
<br>
## How it works
Point Craft Anything at a target, say what you want, and press Start. It works in four steps,
asking you in plain words when a decision is yours:
1. **Study:** inspect the original: its pages at every width, its code, its files, how it runs.
2. **Build:** a coding agent builds a new project, in the language, framework or engine your
request names (or a sensible default).
3. **Check:** compare the build with the original and list what doesn't match yet.
4. **Ready:** open, play or preview the result, or ask for changes and it refines it.
<table>
<tr>
<td width="50%" valign="top">
<img src="docs/images/make.png" alt="The Make screen: pick a website, an app or a game to recreate, type the address, choose Clean room or Deep, say what you want and press Start" width="100%"><br>
<sub><b>Make:</b> pick what to recreate, say what you want, press Start.</sub>
</td>
<td width="50%" valign="top">
<img src="docs/images/project-game.png" alt="A finished snake game project with its steps all done and a Play the game button" width="100%"><br>
<sub><b>Ready:</b> play the game, or ask for changes below.</sub>
</td>
</tr>
</table>
## Two ways to use it
- **Simple** (default): "What do you want to make?" Pick a website, app or game, describe it,
press Start. A project page shows the four steps (Study → Build → Check → Ready), what the
agent is doing in plain words, question and approval cards, how alike the result is, and
buttons to open the result or its folder. Ask for changes in the box at the bottom.
"Just look inside" opens a target for questions without building anything (in Deep mode).
- **Advanced**: the full workbench: every tool (Ctrl/Cmd+K), functions, strings, pseudo-C,
disassembly, hex, call graphs, evidence, unknowns, jobs, logs and the agent console.
Both modes drive the same engine.
## Clean room or Deep
- **Clean room** (the default): nothing inside the original is read, not its code, files or page
source. Craft Anything works from what you can see: pictures you add, the website as a visitor
sees it (screenshots, visible text, measured layout, colours, fonts and spacing, menus opened)
and, when you allow it, a picture of the app's window. Tools that would look inside are refused
and say how to turn on Deep mode.
- **Deep**: every tool is used, for your private use. A program's code and files are read with the
built-in engines (and Ghidra when it's installed), a website's JavaScript is read and its start
page watched, and the builder may use all of them.
Switch in the title bar or Settings, with `settings_set deep_mode true`, or for one CLI run with
`--deep` (or `--clean-room`).
<p align="center">
<img src="docs/images/workbench.png" alt="The Advanced workbench: a function list, pseudo-C of the selected function, the agent answering a question with a tool call, and the evidence ledger" width="100%">
<br>
<sub><b>Advanced:</b> functions, pseudo-C, the agent and the evidence behind every answer.</sub>
</p>
## AI
Building needs a coding agent on your computer. **Claude Code** is supported first: Craft
Anything runs your own, unmodified `claude` program, which uses your own sign-in; Craft Anything
never sees or handles your account. Your use of it falls under your own agreement with
Anthropic. See [docs/claude-code.md](docs/claude-code.md) for how and why. A Codex adapter
exists but hasn't been verified on a real install yet. Anthropic, OpenAI, OpenRouter and local
OpenAI-compatible servers are available for questions and analysis (Settings → AI).
## Built for agents
Every tool is also a CLI subcommand and an MCP tool, so an agent can study a target or run a
whole rebuild without the app:
```sh
craft-anything-cli commands # every tool, by toolset
craft-anything-cli mcp # serve them to any MCP client
craft-anything-cli rebuild https://example.com "Recreate this website"
```
Results are evidence records with their confidence, coverage and limitations; big ones come back
as a summary first and are paged with `core_evidence_browse`. `craft-anything-cli setup`
connects Craft Anything to coding-agent apps.
## Under the hood
A pure-Rust reverse-engineering engine with 284 tools (271 in the engine, the rest from the AI and
setup layers) for native programs, .NET, Java, Android, Apple, Electron/JavaScript, websites,
firmware, packet captures, databases and game files. Its own decoders, disassembler and
decompiler work without any outside program; Deep mode uses them all, and Ghidra when it's
installed. It powers the desktop app (egui), the CLI and the MCP server, and parts of it run in
the browser as WebAssembly. The full list is in [docs/tools.md](docs/tools.md).
## Get started
Requires Rust **1.97 or newer** (a dependency needs it; `rustup update`). On Debian or Ubuntu,
the desktop app also needs:
```sh
sudo apt-get install libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev
```
Then:
```sh
git clone https://github.com/storytold/craft-anything && cd craft-anything
cargo run --release -p craft-anything # the desktop app
cargo install --path apps/craft-anything-cli # the CLI, as `craft-anything-cli`
craft-anything-cli doctor # checks the install, coding agents and engines
```
Building needs a coding agent signed in on your computer (see [AI](#ai)); `doctor` says what's
missing. Rebuild from the command line (questions are asked in the terminal):
```sh
craft-anything-cli rebuild https://example.com "Recreate this website"
craft-anything-cli rebuild - "A snake game in Rust" --rounds 1
craft-anything-cli rebuild https://example.com "Make the header blue" --continue-in "<project folder>"
craft-anything-cli rebuild - "Add a contact form" --project-folder "<your folder>" --existing edit
```
New projects go in `Documents/Craft Anything` (change it in Settings → General). Each project
folder holds `craft.json` (the request, target, status and history), `capture/` (what was
recorded from the target), `app/` (the generated project), `checks/` (each comparison against
the original), `investigation.cany/` (evidence) and `inbox/` (open questions).
A project can also start in a folder you pick (Choose a folder… under Start, or `--project-folder`).
If it already has files, you say what they are: the app itself, which the builder edits in place,
or material to start from, with the app built in `app/` beside them (Settings → General can
remember the answer). Settings → General also lists projects from more folders; removing one
only takes it off the list.
## Status
> [!IMPORTANT]
> **Status:** Craft Anything is in early alpha. What works today, what is partial and what's next:
>
> - **Works today:** the desktop app (Simple and Advanced), the CLI and the MCP server; the
> Study → Build → Check → Refine workflow for websites, apps and games with Claude Code as the
> builder; website checks at three screen widths; game rebuilds in Unity, Unreal or Godot; Deep
> mode with Ghidra; generated pictures and 3D models (opt-in, your own fal.ai key); plugins (MCP
> servers, and WASM components in builds with the `wasm-plugins` option).
> - **Partly there:** building with API keys and other coding agents (built, not yet run live),
> behaviour checks for apps and games, a few engine tools tested only against stand-ins.
> - **Next:** the first public release (installers for Windows, macOS, Linux and FreeBSD, and the
> browser viewer are set up in CI), then the managed tier.
>
> [docs/STATUS.md](docs/STATUS.md) has the detail and how each part was checked,
> [docs/tool-status.md](docs/tool-status.md) the tool-by-tool checklist, and
> [docs/ROADMAP.md](docs/ROADMAP.md) the plan, item by item. Please file issues, or tell us what
> broke on [Discord](https://discord.gg/artcraft).
**Responsible use.** Use Craft Anything on software you own or are allowed to examine. It never
bypasses DRM, logins or anti-cheat. Rebuilds recreate layout, style and behaviour from evidence;
the agent is told not to copy logos, photos or text unless you confirm you own them or have
permission.
## Downloads
On GitHub, the [latest release](https://github.com/storytold/craft-anything/releases/latest) has every build listed below, and [all releases](https://github.com/storytold/craft-anything/releases) has earlier versions and their notes. `<ver>` in the file names is the version number, and `SHA256SUMS.txt` lists a checksum for every file.
### Windows
| Build | Installer | Portable |
|---|---|---|
| x64 (64-bit Intel/AMD) | `craft-anything-<ver>-windows-x64.msi` | `craft-anything-<ver>-windows-x64-portable.zip` |
| arm64 (Snapdragon and other ARM PCs) | `craft-anything-<ver>-windows-arm64.msi` | `craft-anything-<ver>-windows-arm64-portable.zip` |
| x86 (32-bit) | `craft-anything-<ver>-windows-x86.msi` | `craft-anything-<ver>-windows-x86-portable.zip` |
Installers and executables are code-signed. The portable zip keeps its settings next to the app.
### macOS
| Build | File | Notes |
|---|---|---|
| App, universal (Apple silicon + Intel) | `craft-anything-<ver>-macos-universal.dmg` | Signed and notarized |
| Command-line tool, universal | `craft-anything-cli-<ver>-macos-universal.zip` | Signed and notarized |
### Linux
| Format | x86_64 | aarch64 (ARM64) | Notes |
|---|---|---|---|
| AppImage | `craft-anything-<ver>-linux-x86_64.AppImage` | `craft-anything-<ver>-linux-aarch64.AppImage` | Runs anywhere; updates itself with [AppImageUpdate](https://github.com/AppImageCommunity/AppImageUpdate) (`.zsync` files) |
| Flatpak | `craft-anything-<ver>-linux-x86_64.flatpak` | `craft-anything-<ver>-linux-aarch64.flatpak` | Sandboxed; `flatpak install --user <file>` |
| Debian/Ubuntu | `craft-anything-<ver>-linux-x86_64.deb` | `craft-anything-<ver>-linux-aarch64.deb` | |
| Fedora/RHEL/openSUSE | `craft-anything-<ver>-linux-x86_64.rpm` | `craft-anything-<ver>-linux-aarch64.rpm` | |
| Tarball | `craft-anything-<ver>-linux-x86_64.tar.gz` | `craft-anything-<ver>-linux-aarch64.tar.gz` | Unpack anywhere |
RISC-V (riscv64): `craft-anything-<ver>-linux-riscv64.tar.gz`, a tarball only.
### FreeBSD
| Build | File |
|---|---|
| x86_64 | `craft-anything-<ver>-freebsd-x86_64.tar.gz` |
### Web (WebAssembly)
| Build | File | Notes |
|---|---|---|
| Browser viewer | `craft-anything-web-<ver>.zip` | Says what a file is, in the browser (the file never leaves it); host the folder on any static web server ([packaging/web/README.md](packaging/web/README.md)) |
<br>
<p align="center">
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
</p>
<h3 align="center">Come make things with us</h3>
<p align="center">
Our Discord is where artists of every kind hang out: people who paint, shoot, draw, cut film,
set type, and people still figuring out what they like to make. Share what you're working on,
ask for help, tell us what's broken, or tell us what you wish these tools could do.
Whatever your medium and however long you've been at it, you're welcome here.
</p>
<p align="center">
<a href="https://discord.gg/artcraft"><b>discord.gg/artcraft</b></a> ·
<a href="https://getartcraft.com/">getartcraft.com</a> ·
<a href="https://getartcraft.com/apps">The Crafting Apps</a> ·
<a href="https://github.com/storytold/craft-anything">Craft Anything</a>
</p>
---
## License and credits
Craft Anything is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option.
Copyright (c) 2026 ArtCraft Team and the Craft Anything contributors. Required notices are in [NOTICE](NOTICE).
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
The screenshots show sample projects made for them: example.com, a snake game and a small
calculator program.
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
part of this repository and Craft Anything, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
<p align="center">
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
</p>
+23
View File
@@ -0,0 +1,23 @@
# Security
Craft Anything reads hostile files and runs other programs, so we take reports seriously.
## Reporting a vulnerability
Please report it privately: on GitHub, open the repository's **Security** tab and choose
**Report a vulnerability**. Don't open a public issue for it. Say what's affected, how to reproduce
it, and what an attacker gains. We'll reply within a week and tell you what we'll do.
## What counts
- A crash, hang or runaway memory use on any input file or website (never-crash is a hard rule:
[AGENTS.md](AGENTS.md)).
- Code from a target running without the person's consent, or a tool doing more than its declared
effects.
- A path that lets a coding agent act outside its project without approval.
- A key, token or other secret reaching a log, a tool's output, evidence or the repository.
- A plugin escaping its sandbox (WASM plugins import nothing; MCP plugins ask before each call).
## Supported versions
Fixes go into the latest release.
+35
View File
@@ -0,0 +1,35 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Craft Anything: third-party licences</title>
<style>
body { font-family: sans-serif; max-width: 60rem; margin: 2rem auto; padding: 0 1rem; }
pre { white-space: pre-wrap; background: #f4f4f4; padding: 1rem; }
</style>
</head>
<body>
<h1>Third-party licences</h1>
<p>Craft Anything includes the following Rust crates. Fonts and icons bundled from
<code>assets/</code> are listed in NOTICE and ATTRIBUTION.md.</p>
<h2>Summary</h2>
<ul>
{{#each overview}}
<li><a href="#{{id}}">{{name}}</a> ({{count}})</li>
{{/each}}
</ul>
<h2>Licences</h2>
{{#each licenses}}
<section id="{{id}}">
<h3>{{name}}</h3>
<p>Used by:</p>
<ul>
{{#each used_by}}
<li><a href="{{#if crate.repository}}{{crate.repository}}{{else}}https://crates.io/crates/{{crate.name}}{{/if}}">{{crate.name}} {{crate.version}}</a></li>
{{/each}}
</ul>
<pre>{{text}}</pre>
</section>
{{/each}}
</body>
</html>
+23
View File
@@ -0,0 +1,23 @@
# cargo-about config: builds the third-party licence bundle shipped with releases.
# cargo about generate about.hbs -o THIRD-PARTY-LICENSES.html
# Keep `accepted` in step with deny.toml (policy: docs/licences.md).
accepted = [
"MIT",
"Apache-2.0",
"Apache-2.0 WITH LLVM-exception",
"BSD-2-Clause",
"BSD-3-Clause",
"ISC",
"Zlib",
"0BSD",
"Unicode-3.0",
"BSL-1.0",
"CDLA-Permissive-2.0",
"OFL-1.1",
"Ubuntu-font-1.0",
"MPL-2.0", # only option-ext; deny.toml enforces that
]
# Bundle only what ships: skip dev-dependencies and build tooling crates.
ignore-dev-dependencies = true
ignore-build-dependencies = false
workarounds = ["ring"]
+34
View File
@@ -0,0 +1,34 @@
[package]
name = "craft-anything-cli"
description = "Craft Anything on the command line: every tool, the MCP server, setup and doctor"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lints]
workspace = true
[dependencies]
craft-anything-engine = { workspace = true }
craft-anything-engines = { workspace = true }
craft-anything-evidence = { workspace = true }
craft-anything-platform = { workspace = true }
craft-anything-mcp = { workspace = true }
craft-anything-ai = { workspace = true }
craft-anything-setup = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
clap = { version = "4", features = ["derive"] }
ctrlc = { version = "3", features = ["termination"] }
[features]
wasm-plugins = ["craft-anything-engine/wasm-plugins"]
[dev-dependencies]
tempfile = "3"
[build-dependencies]
# The DPI-aware manifest for craft-anything-cli.exe; build.rs only uses it when targeting Windows.
winresource = "0.1"
+30
View File
@@ -0,0 +1,30 @@
//! Windows only: mark `craft-anything-cli.exe` DPI-aware (an application manifest), so window
//! pictures (`native_window_capture`) and screen coordinates are in real pixels at any display
//! scaling. On every other target this does nothing. A missing resource compiler is a warning,
//! unless `CRAFT_ANYTHING_REQUIRE_WINRES=1` (the release workflow) makes it an error.
const MANIFEST: &str = r#"<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
</assembly>"#;
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-env-changed=CRAFT_ANYTHING_REQUIRE_WINRES");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_manifest(MANIFEST).set("OriginalFilename", "craft-anything-cli.exe").set("InternalName", "craft-anything-cli");
if let Err(e) = res.compile() {
if std::env::var_os("CRAFT_ANYTHING_REQUIRE_WINRES").is_some() {
println!("cargo:error=embedding Windows resources failed: {e}");
return;
}
println!("cargo:warning=craft-anything-cli.exe built without its DPI-aware manifest: {e}");
}
}
+278
View File
@@ -0,0 +1,278 @@
//! `chat` and `ai list|detect|add|test`.
use crate::output::Format;
use crate::{Cli, INTERRUPTED, emit, fail, make_engine, out};
use clap::{Args, Subcommand};
use craft_anything_ai::{AgentEvent, AiHub, BackendConfig, BackendKind};
use craft_anything_evidence::ToolError;
use serde_json::{Value, json};
use std::io::{Read as _, Write as _};
use std::sync::atomic::Ordering;
use std::time::Duration;
#[derive(Debug, Args)]
pub struct ChatArgs {
/// The question.
pub question: String,
/// File, app or folder to open first.
#[arg(long)]
pub target: Option<String>,
/// Backend name (default: the lead backend).
#[arg(long)]
pub backend: Option<String>,
/// Plain-words answers.
#[arg(long)]
pub beginner: bool,
}
#[derive(Debug, Subcommand)]
pub enum AiCommand {
/// Configured backends.
List,
/// Look for keys, local servers, agent CLIs and SSH hosts.
Detect,
/// Add a backend.
Add {
name: String,
/// anthropic, openai, openrouter, openai_compatible, agent_cli
#[arg(long)]
kind: String,
#[arg(long)]
model: Option<String>,
#[arg(long)]
base_url: Option<String>,
#[arg(long)]
ssh_host: Option<String>,
/// Read the API key from this environment variable (keys are never taken on the command line).
#[arg(long)]
key_env: Option<String>,
/// Read the API key from stdin.
#[arg(long)]
key_stdin: bool,
},
/// Remove a backend.
Remove { name: String },
/// Turn a backend on again.
On { name: String },
/// Turn a backend off: nothing uses it, and it keeps its settings and key.
Off { name: String },
/// Send a tiny request and report latency.
Test { name: String },
/// Choose the backend that builds (leave the name out to go back to automatic).
Builder { name: Option<String> },
/// Choose the backend that takes a game's own files out after the study, in Deep mode (an API
/// backend such as Kimi K3 through OpenRouter; leave the name out to turn it off).
Extractor { name: Option<String> },
}
fn hub(cli: &Cli) -> Result<AiHub, ToolError> {
Ok(AiHub::new(make_engine(cli.project.as_deref(), cli.deep_for_run())?))
}
fn write_raw(s: &str) {
let mut o = std::io::stdout().lock();
let _ = o.write_all(s.as_bytes()).and_then(|_| o.flush());
}
/// Headless agent run: stream the answer to stdout, tool activity to stderr.
pub fn chat(cli: &Cli, a: &ChatArgs) -> u8 {
let hub = match hub(cli) {
Ok(h) => h,
Err(e) => return fail(&e, cli.format()),
};
if let Some(t) = &a.target {
let abs = match std::path::absolute(t) {
Ok(p) => p,
Err(e) => return fail(&ToolError::io(t, e), cli.format()),
};
if let Err(e) = hub.engine.call("core_target_open", json!({"path": abs}), crate::call_options(cli, &Default::default())) {
return fail(&e, cli.format());
}
}
let mut conv = match hub.start(a.backend.as_deref(), a.beginner) {
Ok(c) => c,
Err(e) => return fail(&e, cli.format()),
};
conv.send(&a.question);
let jsonl = cli.format() == Format::Jsonl;
let mut code = 0u8;
let mut stopped = false;
loop {
if INTERRUPTED.load(Ordering::SeqCst) && !stopped {
conv.stop();
stopped = true;
}
let events = conv.poll();
if events.is_empty() {
if stopped && !conv.is_busy() {
break;
}
std::thread::sleep(Duration::from_millis(15));
continue;
}
let mut done = false;
for ev in events {
if jsonl {
out(&serde_json::to_string(&ev).unwrap_or_default());
}
match &ev {
AgentEvent::TextDelta { text } if !jsonl => write_raw(text),
AgentEvent::Status { text } if !jsonl => eprintln!("· {text}"),
AgentEvent::ToolStarted { tool, .. } if !jsonl => eprintln!("→ {tool}"),
AgentEvent::ToolFinished { tool, ok, summary, evidence_id, .. } if !jsonl => {
let ev = evidence_id.as_deref().map(|e| format!(" [{e}]")).unwrap_or_default();
eprintln!("{} {tool}: {summary}{ev}", if *ok { "✓" } else { "✗" });
}
AgentEvent::ConsentNeeded { call_id, title, explanation, .. } => {
if !jsonl {
eprintln!(
"! {title} needs your OK: {explanation} ({})",
if cli.allow_run { "allowed by --allow-run" } else { "declined; re-run with --allow-run to allow" }
);
}
conv.answer_consent(call_id, cli.allow_run);
}
AgentEvent::Error { message, remediation } => {
code = 1;
if !jsonl {
eprintln!("error: {message}");
if let Some(r) = remediation {
eprintln!("fix: {r}");
}
}
}
AgentEvent::TurnDone { backend, input_tokens, output_tokens, cost_usd } => {
if !jsonl {
let cost = cost_usd.map(|c| format!(", ${c:.4}")).unwrap_or_default();
write_raw("\n");
eprintln!("[{backend}: {input_tokens} in / {output_tokens} out{cost}]");
}
done = true;
}
_ => {}
}
}
if done {
break;
}
}
if stopped { 130 } else { code }
}
fn read_key(key_env: &Option<String>, key_stdin: bool) -> Result<Option<String>, String> {
if let Some(var) = key_env {
return std::env::var(var).map(Some).map_err(|_| format!("environment variable {var} is not set"));
}
if key_stdin {
let mut s = String::new();
std::io::stdin().take(64 * 1024).read_to_string(&mut s).map_err(|e| format!("reading the key from stdin: {e}"))?;
let k = s.trim().to_string();
return if k.is_empty() { Err("no key on stdin".into()) } else { Ok(Some(k)) };
}
Ok(None)
}
pub fn ai(cli: &Cli, c: &AiCommand, f: Format) -> u8 {
let hub = match hub(cli) {
Ok(h) => h,
Err(e) => return fail(&e, f),
};
match c {
AiCommand::List => {
let v: Vec<Value> = hub
.backends()
.into_iter()
.map(|b| {
let has_key = hub.has_key(&b.name);
let mut v = serde_json::to_value(&b).unwrap_or(Value::Null);
if let Some(m) = v.as_object_mut() {
m.insert("key_stored".into(), json!(has_key));
}
v
})
.collect();
emit(&Value::Array(v), f);
0
}
AiCommand::Detect => {
emit(&serde_json::to_value(hub.detect()).unwrap_or(Value::Null), f);
0
}
AiCommand::Add { name, kind, model, base_url, ssh_host, key_env, key_stdin } => {
let kind: BackendKind = match serde_json::from_value(json!(kind)) {
Ok(k) => k,
Err(_) => return crate::usage_error("--kind must be one of anthropic, openai, openrouter, openai_compatible, agent_cli"),
};
let key = match read_key(key_env, *key_stdin) {
Ok(k) => k,
Err(m) => return crate::usage_error(&m),
};
let model = model.clone().or_else(|| kind.suggested_models().first().map(|m| m.to_string())).unwrap_or_default();
let cfg = BackendConfig { name: name.clone(), kind, model, base_url: base_url.clone(), ssh_host: ssh_host.clone(), enabled: true };
match hub.add_backend(cfg.clone(), key) {
Ok(()) => {
emit(&json!({"added": cfg}), f);
0
}
Err(e) => fail(&e, f),
}
}
AiCommand::Remove { name } => match hub.remove_backend(name) {
Ok(removed) => {
emit(&json!({"removed": removed, "name": name}), f);
if removed { 0 } else { 1 }
}
Err(e) => fail(&e, f),
},
AiCommand::On { name } | AiCommand::Off { name } => {
let on = matches!(c, AiCommand::On { .. });
match hub.set_enabled(name, on) {
Ok(found) => {
emit(&json!({"name": name, "enabled": on, "found": found}), f);
if found { 0 } else { 1 }
}
Err(e) => fail(&e, f),
}
}
AiCommand::Builder { name } => match hub.set_role(craft_anything_ai::Role::Builder, name.as_deref()) {
Ok(()) => {
emit(&json!({"builder": name}), f);
0
}
Err(e) => fail(&e, f),
},
AiCommand::Extractor { name } => match hub.set_role(craft_anything_ai::Role::Extractor, name.as_deref()) {
Ok(()) => {
emit(&json!({"extractor": name}), f);
0
}
Err(e) => fail(&e, f),
},
AiCommand::Test { name } => match hub.test_backend(name) {
Ok(r) => {
emit(&serde_json::to_value(r).unwrap_or(Value::Null), f);
0
}
Err(e) => fail(&e, f),
},
}
}
/// AI reachability checks for `doctor` (bounded; each configured backend once).
pub fn doctor_checks() -> Vec<craft_anything_setup::Check> {
use craft_anything_setup::{Check, CheckStatus};
let Ok(engine) = make_engine(None, None) else { return Vec::new() };
let hub = AiHub::new(engine);
let results = hub.check_reachability();
if results.is_empty() {
return vec![Check::new("ai", CheckStatus::Info, "No AI backend is set up (optional).").fix("Run `craft-anything-cli ai detect`, then `ai add`.")];
}
results
.into_iter()
.map(|(name, r)| match r {
Ok(ms) => Check::new(format!("ai:{name}"), CheckStatus::Ok, format!("{name} answered in {ms} ms.")),
Err(why) => Check::new(format!("ai:{name}"), CheckStatus::Warn, format!("{name} isn't reachable: {why}"))
.fix(format!("Run `craft-anything-cli ai test {name}` for details.")),
})
.collect()
}
+522
View File
@@ -0,0 +1,522 @@
//! `craft-anything-cli`: every tool as a subcommand, the MCP server, setup, doctor and headless chat.
//!
//! Exit codes: 0 success, 1 the operation failed (a structured error is printed), 2 usage error,
//! 130 interrupted.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod ai_cmd;
mod output;
mod rebuild_cmd;
mod setup_cmd;
mod tool_args;
use clap::{Parser, Subcommand};
use craft_anything_engine::project::{Project, Purpose};
use craft_anything_engine::{CallOptions, Caller, CancelToken, Consent, Engine, Requires, Session, Settings, ToolOutput};
use craft_anything_evidence::ToolError;
use output::Format;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
pub static INTERRUPTED: AtomicBool = AtomicBool::new(false);
#[derive(Debug, Parser)]
#[command(name = "craft-anything-cli", version, about = "Craft Anything on the command line: every tool, the MCP server, setup and doctor.")]
#[command(after_help = "Every tool is also a subcommand: `craft-anything-cli commands` lists them, `craft-anything-cli <tool> --help` shows its options.\n\
When a tool has its own --format option (core-target-open, report, ...), --format after the tool name goes to the tool; pick the output with --output-format (or --format before the tool name).")]
pub struct Cli {
/// Output format. `--output-format` always means this, even after a tool that has its own `--format`.
#[arg(long, global = true, value_enum, default_value_t = Format::Json, alias = "output-format")]
pub format: Format,
/// Shorthand for --format json.
#[arg(long, global = true)]
pub json: bool,
/// A project folder (`*.cany`): evidence, memory and the journal are kept there. Created if missing.
#[arg(long, global = true)]
pub project: Option<PathBuf>,
/// Allow tools that run code or change a device without asking.
#[arg(long, global = true)]
pub allow_run: bool,
/// Deep mode for this run only: tools may read a target's code, files and page source.
#[arg(long, global = true, conflicts_with = "clean_room")]
pub deep: bool,
/// Clean room for this run only, whatever Settings say: nothing inside a target is read.
#[arg(long, global = true)]
pub clean_room: bool,
#[command(subcommand)]
pub command: Command,
}
#[derive(Debug, Subcommand)]
pub enum Command {
/// Run the MCP server on stdin/stdout.
Mcp {
/// List every tool instead of the Essentials plus enabled toolsets.
#[arg(long)]
all_tools: bool,
/// A folder where questions and approvals for the person are posted (`core_person_ask`,
/// `core_action_approve`); the Craft Anything app answers them.
#[arg(long)]
inbox: Option<PathBuf>,
},
/// Connect Craft Anything to your coding-agent apps.
Setup(setup_cmd::SetupArgs),
/// Check the install, registrations, engines, AI backends and the MCP server.
Doctor(setup_cmd::DoctorArgs),
/// Remove Craft Anything's registrations and skill from agent apps.
Uninstall(setup_cmd::UninstallArgs),
/// List every tool.
Commands,
/// What this install can do: toolsets, tool availability, engines.
Capabilities,
/// Open a file and run a first look at it.
Triage { path: String },
/// Write a readable investigation report (Markdown or HTML) from findings and evidence.
Report {
/// Optional target to open first (its sha256 ties evidence to a file). Omit to report on
/// the open project's memory and ledger.
path: Option<String>,
/// Write a self-contained HTML page instead of Markdown.
#[arg(long)]
html: bool,
/// Write to this file instead of printing to stdout.
#[arg(long)]
out: Option<PathBuf>,
/// Leave out the evidence-ledger appendix.
#[arg(long)]
no_evidence: bool,
},
/// Ask the AI agent a question about a target (streams to stdout).
Chat(ai_cmd::ChatArgs),
/// Study a website, app or game and have a coding agent rebuild it in a new project folder.
Rebuild(rebuild_cmd::RebuildArgs),
/// Manage AI backends.
Ai {
#[command(subcommand)]
command: ai_cmd::AiCommand,
},
/// For a coding agent's hook, run after each of its tool calls: hand over the notes the person
/// added while it works (printed as the hook's JSON; nothing when none wait).
#[command(hide = true)]
BuilderNotes { dir: PathBuf },
/// Run a tool by name: `craft-anything-cli <tool> [path] [--key value] [--json '{..}' | @file.json | -]`.
#[command(external_subcommand)]
Tool(Vec<String>),
}
impl Cli {
pub fn format(&self) -> Format {
if self.json { Format::Json } else { self.format }
}
/// The mode `--deep` or `--clean-room` asks for, if either.
pub fn deep_for_run(&self) -> Option<bool> {
(self.deep || self.clean_room).then_some(self.deep)
}
}
fn main() -> ExitCode {
init_logging();
let _ = ctrlc::set_handler(|| {
if INTERRUPTED.swap(true, Ordering::SeqCst) {
// second Ctrl-C: leave now
std::process::exit(130);
}
});
let cli = match Cli::try_parse() {
Ok(c) => c,
Err(e) => {
let code = if e.use_stderr() { 2 } else { 0 };
let _ = e.print();
return ExitCode::from(code);
}
};
let code = run(cli);
if INTERRUPTED.load(Ordering::SeqCst) { ExitCode::from(130) } else { ExitCode::from(code) }
}
fn init_logging() {
struct Stderr(log::LevelFilter);
impl log::Log for Stderr {
fn enabled(&self, m: &log::Metadata<'_>) -> bool {
m.level() <= self.0
}
fn log(&self, r: &log::Record<'_>) {
if self.enabled(r.metadata()) {
eprintln!("[{}] {}: {}", r.level(), r.target(), r.args());
}
}
fn flush(&self) {}
}
let level = match std::env::var("CRAFT_ANYTHING_LOG").unwrap_or_default().to_ascii_lowercase().as_str() {
"trace" => log::LevelFilter::Trace,
"debug" => log::LevelFilter::Debug,
"info" => log::LevelFilter::Info,
"warn" => log::LevelFilter::Warn,
"error" => log::LevelFilter::Error,
_ => log::LevelFilter::Off,
};
if level != log::LevelFilter::Off && log::set_logger(Box::leak(Box::new(Stderr(level)))).is_ok() {
log::set_max_level(level);
}
}
/// Print a line to stdout; a closed pipe (`| head`) is not an error worth crashing over.
pub fn out(s: &str) {
use std::io::Write as _;
let mut o = std::io::stdout().lock();
let _ = o.write_all(s.as_bytes()).and_then(|_| o.write_all(b"\n")).and_then(|_| o.flush());
}
/// Print a value in the chosen format.
pub fn emit(v: &Value, f: Format) {
out(&output::render(v, f));
}
/// Print an error (to stdout as structured output, so scripts can parse it) and return exit code 1.
pub fn fail(e: &ToolError, f: Format) -> u8 {
emit(&json!({"error": e}), f);
1
}
pub fn usage_error(msg: &str) -> u8 {
usage(msg)
}
fn usage(msg: &str) -> u8 {
eprintln!("error: {msg}");
2
}
/// The engine with settings loaded, the run's mode, and the project (if any) opened.
pub fn make_engine(project: Option<&Path>, deep_for_run: Option<bool>) -> Result<Arc<Engine>, ToolError> {
let mut session = Session::new(Settings::load());
session.deep_for_run = deep_for_run;
if let Some(dir) = project {
session.open_project(open_or_create_project(dir)?)?;
}
let plugins = craft_anything_engine::plugins::install(&mut session);
let mut layer_tools = craft_anything_ai::tools();
layer_tools.extend(craft_anything_setup::tools::specs());
Ok(Engine::shared_with(session, layer_tools, plugins))
}
fn open_or_create_project(dir: &Path) -> Result<Project, ToolError> {
let dir = std::path::absolute(dir).map_err(|e| ToolError::io(dir.display(), e))?;
if dir.join("project.toml").is_file() {
return Project::open(&dir);
}
let name = dir.file_stem().map(|s| s.to_string_lossy().into_owned()).unwrap_or_else(|| "project".into());
Project::create(&dir, &name, Purpose::default())
}
pub fn call_options(cli: &Cli, cancel: &CancelToken) -> CallOptions<'static> {
let consent = if cli.allow_run { Consent::Granted } else { Consent::NotAsked };
CallOptions::new(Caller::Cli).with_consent(consent).with_cancel(cancel.clone())
}
/// A cancel token that trips on Ctrl-C.
pub fn interrupt_token() -> CancelToken {
let token = CancelToken::default();
let t = token.clone();
let _ = std::thread::Builder::new().name("ctrl-c-watch".into()).spawn(move || {
while !INTERRUPTED.load(Ordering::SeqCst) {
std::thread::sleep(std::time::Duration::from_millis(50));
}
t.cancel();
});
token
}
fn run(cli: Cli) -> u8 {
let f = cli.format();
match &cli.command {
// Runs after every tool call of a builder: no engine, nothing but the hook's JSON on stdout.
Command::BuilderNotes { dir } => {
use craft_anything_ai::rebuild::notes;
if let Some(out) = notes::hook_output(&notes::claim(dir)) {
println!("{out}");
}
0
}
Command::Mcp { all_tools, inbox } => {
let engine = match make_engine(cli.project.as_deref(), cli.deep_for_run()) {
Ok(e) => e,
Err(e) => {
eprintln!("craft-anything mcp: {}", e.message);
return 1;
}
};
if let Some(dir) = inbox {
engine.session().ext.insert(Arc::new(craft_anything_engine::inbox::InboxDir(dir.clone())));
// A builder can generate game assets with the person's keys (one per asset
// provider), read here from the keychain so none appears on a command line or in
// a log.
let providers = engine.session().ext.get::<craft_anything_engines::assets::AssetProviders>().map(|p| p.as_ref().clone()).unwrap_or_default();
let keys = craft_anything_ai::keys::asset_keys(&craft_anything_ai::KeyStore::system(), &providers);
engine.session().ext.insert(Arc::new(keys));
}
let mut opts = craft_anything_mcp::ServerOptions::from_env();
opts.all_tools |= *all_tools;
opts.allow_run = cli.allow_run;
match craft_anything_mcp::serve_stdio(engine, opts) {
Ok(()) => 0,
Err(e) => {
eprintln!("craft-anything mcp: {e}");
1
}
}
}
Command::Setup(a) => setup_cmd::setup(a, f),
Command::Doctor(a) => setup_cmd::doctor(a, f),
Command::Uninstall(a) => setup_cmd::uninstall(a, f),
Command::Commands => commands(f),
Command::Capabilities => capabilities(&cli, f),
Command::Triage { path } => triage(&cli, path, f),
Command::Report { path, html, out, no_evidence } => {
report(&cli, path.as_deref(), if *html { "html" } else { "markdown" }, out.as_deref(), *no_evidence, f)
}
Command::Chat(a) => ai_cmd::chat(&cli, a),
Command::Rebuild(a) => rebuild_cmd::rebuild(&cli, a),
Command::Ai { command } => ai_cmd::ai(&cli, command, f),
Command::Tool(args) => tool(&cli, args, f),
}
}
fn commands(f: Format) -> u8 {
// The same engine every command gets: settings, the AI layer's tools and plugins.
let engine = match make_engine(None, None) {
Ok(e) => e,
Err(e) => return fail(&e, f),
};
if f == Format::Json || f == Format::Jsonl {
let v: Vec<Value> = engine
.registry()
.all()
.iter()
.map(|s| json!({"command": s.cli_name(), "tool": s.id, "toolset": s.toolset.id(), "title": s.title, "summary": s.summary, "needs_target": s.requires == Requires::Target}))
.collect();
emit(&Value::Array(v), f);
} else {
for t in engine.registry().toolsets() {
let specs: Vec<_> = engine.registry().in_toolset(t).collect();
if specs.is_empty() {
continue;
}
out(&format!("{}:", t.title()));
for s in specs {
out(&format!(" {:<34} {}", s.cli_name(), s.title));
}
}
}
0
}
fn capabilities(cli: &Cli, f: Format) -> u8 {
let engine = match make_engine(cli.project.as_deref(), cli.deep_for_run()) {
Ok(e) => e,
Err(e) => return fail(&e, f),
};
let session = engine.session();
let toolsets: Vec<Value> = engine
.registry()
.toolsets()
.iter()
.map(|t| {
let tools: Vec<Value> = engine
.registry()
.in_toolset(*t)
.map(|s| {
let a = engine.availability(s, &session);
json!({"tool": s.id, "available": a.available || s.requires == Requires::Target, "needs_target": s.requires == Requires::Target, "reason": if s.requires == Requires::Target { None } else { a.reason }})
})
.collect();
json!({"id": t.id(), "title": t.title(), "tools": tools})
})
.collect();
let engines: Vec<Value> = craft_anything_engines::ENGINES
.iter()
.map(|e| {
let found = craft_anything_engines::locate(e.id, &session.settings.engines.tools, &session.settings.engine_store_dir());
json!({"id": e.id, "name": e.name, "needed_for": e.needed_for, "found": found.is_some(), "path": found, "installable_here": e.host_pin().is_some()})
})
.collect();
emit(
&json!({
"version": env!("CARGO_PKG_VERSION"),
"analysis_mode": if session.clean_room() { "clean-room" } else { "deep" },
"tools": engine.registry().len(),
"toolsets": toolsets,
"engines": engines,
"host": craft_anything_evidence::host_triple(),
}),
f,
);
0
}
/// open → op → close for one target. `open` carries extra `core_target_open` params (raw-binary
/// architecture and entry point, a forced format, a Deep language pin).
fn with_target(
engine: &Engine,
cli: &Cli,
cancel: &CancelToken,
path: &str,
open: &serde_json::Map<String, Value>,
op: impl FnOnce() -> Result<ToolOutput, ToolError>,
) -> Result<ToolOutput, ToolError> {
let abs = std::path::absolute(path).map_err(|e| ToolError::io(path, e))?;
let mut params = open.clone();
params.insert("path".into(), json!(abs));
engine.call("core_target_open", Value::Object(params), call_options(cli, cancel))?;
let out = op();
let _ = engine.call("core_target_close", json!({}), call_options(cli, cancel));
out
}
fn triage(cli: &Cli, path: &str, f: Format) -> u8 {
let engine = match make_engine(cli.project.as_deref(), cli.deep_for_run()) {
Ok(e) => e,
Err(e) => return fail(&e, f),
};
let cancel = interrupt_token();
let tool = ["core_target_triage", "core_overview_show"].into_iter().find(|t| engine.registry().get(t).is_some());
let r = with_target(&engine, cli, &cancel, path, &Default::default(), || match tool {
Some(t) => engine.call(t, json!({}), call_options(cli, &cancel)),
None => {
let mut v = engine.call("core_session_show", json!({}), call_options(cli, &cancel))?.to_json();
if let Some(m) = v.as_object_mut() {
m.insert("note".into(), json!("No triage tool is registered in this build yet; showing what was opened."));
}
Ok(ToolOutput::Value(v))
}
});
match r {
Ok(out) => {
emit(&out.to_json(), f);
0
}
Err(e) => fail(&e, f),
}
}
fn report(cli: &Cli, path: Option<&str>, format: &str, out_file: Option<&Path>, no_evidence: bool, f: Format) -> u8 {
let format = format.to_ascii_lowercase();
if format != "markdown" && format != "html" {
return usage("--format must be markdown or html");
}
let engine = match make_engine(cli.project.as_deref(), cli.deep_for_run()) {
Ok(e) => e,
Err(e) => return fail(&e, f),
};
let cancel = interrupt_token();
// The report tool writes the file itself when given an absolute path; otherwise it returns the
// text and we print it (raw, so the Markdown/HTML is usable directly).
let out_abs = match out_file {
Some(p) => match std::path::absolute(p) {
Ok(a) => Some(a),
Err(e) => return fail(&ToolError::io(p.display(), e), f),
},
None => None,
};
let mut params = json!({"format": format, "include_evidence": !no_evidence});
if let (Some(a), Some(m)) = (&out_abs, params.as_object_mut()) {
m.insert("path".into(), json!(a));
}
let run = || engine.call("core_report_write", params.clone(), call_options(cli, &cancel));
let result = match path {
Some(p) => with_target(&engine, cli, &cancel, p, &Default::default(), run),
None => run(),
};
match result {
Ok(output) => {
let v = output.to_json();
match (out_abs, v["result"]["report"].as_str()) {
// Printed report: emit the raw text so it can be piped to a file or viewer.
(None, Some(text)) => out(text),
// Wrote a file (or an unexpected shape): show the structured result.
_ => emit(&v, f),
}
0
}
Err(e) => fail(&e, f),
}
}
fn tool(cli: &Cli, args: &[String], f: Format) -> u8 {
let Some((name, rest)) = args.split_first() else { return usage("missing command") };
// Global flags written after the tool name land here; pick them out.
let mut f = f;
let (mut allow_run, mut deep, mut clean_room) = (cli.allow_run, cli.deep, cli.clean_room);
let mut rest_args = Vec::new();
let mut it = rest.iter().peekable();
// `--format` and `--project` are left to tool_args when the tool has an option of that name
// (`project-show --project <folder>`); otherwise they're the global flags.
while let Some(a) = it.next() {
match a.as_str() {
"--allow-run" => allow_run = true,
"--deep" => deep = true,
"--clean-room" => clean_room = true,
"--json" if it.peek().is_none_or(|n| !(n.starts_with('{') || n.starts_with('@') || n.as_str() == "-")) => f = Format::Json,
_ => rest_args.push(a.clone()),
}
}
// The engine first (tools from higher layers are only known through it), with the project
// given before the tool name.
if deep && clean_room {
return usage("--deep and --clean-room can't be used together");
}
let mut cli = Cli { format: f, json: false, project: cli.project.clone(), allow_run, deep, clean_room, command: Command::Commands };
let mut engine = match make_engine(cli.project.as_deref(), cli.deep_for_run()) {
Ok(e) => e,
Err(e) => return fail(&e, f),
};
let Some(spec) = engine.registry().get(name).copied() else {
return usage(&format!("unknown command {name:?}. Run `craft-anything-cli commands` to list tools, or --help for built-in commands."));
};
let schema = engine.registry().input_schema(&spec);
let tool_has_project = schema.pointer("/properties/project").is_some();
if !tool_has_project && let Some(i) = rest_args.iter().position(|a| a == "--project") {
let Some(p) = rest_args.get(i + 1).cloned() else { return usage("--project needs a folder") };
rest_args.drain(i..i + 2);
cli.project = Some(PathBuf::from(p));
engine = match make_engine(cli.project.as_deref(), cli.deep_for_run()) {
Ok(e) => e,
Err(e) => return fail(&e, f),
};
}
let cli = &cli;
let rest = rest_args.as_slice();
let inv = match tool_args::parse(&spec, &schema, rest) {
Ok(i) => i,
Err(m) => return usage(&m),
};
if let Some(v) = &inv.output_format {
match <Format as clap::ValueEnum>::from_str(v, true) {
Ok(v) => f = v,
Err(_) => return usage("--output-format needs one of json, jsonl, md, text"),
}
}
if inv.help {
out(&tool_args::help(&spec, &schema));
return 0;
}
let cancel = interrupt_token();
let result = match (&inv.open_path, spec.requires) {
(Some(path), _) => with_target(&engine, cli, &cancel, path, &inv.open_params, || engine.call(spec.id, inv.params.clone(), call_options(cli, &cancel))),
(None, Requires::Target) => {
return usage(&format!("{} needs a target: craft-anything-cli {} <path> …", spec.cli_name(), spec.cli_name()));
}
(None, _) => engine.call(spec.id, inv.params.clone(), call_options(cli, &cancel)),
};
match result {
Ok(out) => {
emit(&out.to_json(), f);
0
}
Err(e) => fail(&e, f),
}
}
+236
View File
@@ -0,0 +1,236 @@
//! Output formats: json (pretty on a TTY), jsonl, md, text, csv and tsv (a result's rows, for a spreadsheet).
use clap::ValueEnum;
use serde_json::{Map, Value};
use std::io::IsTerminal as _;
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum, Default)]
pub enum Format {
#[default]
Json,
Jsonl,
Md,
Text,
Csv,
Tsv,
}
pub fn render(v: &Value, f: Format) -> String {
match f {
Format::Json => {
if std::io::stdout().is_terminal() {
serde_json::to_string_pretty(v).unwrap_or_default()
} else {
serde_json::to_string(v).unwrap_or_default()
}
}
Format::Jsonl => match v {
Value::Array(items) => items.iter().map(|i| serde_json::to_string(i).unwrap_or_default()).collect::<Vec<_>>().join("\n"),
_ => serde_json::to_string(v).unwrap_or_default(),
},
Format::Md => markdown(v),
Format::Text => text(v, 0),
Format::Csv => table(v, ','),
Format::Tsv => table(v, '\t'),
}
}
/// The rows a table shows: an array of objects itself, or the largest one in a result (evidence's
/// `result`, where a tool's list sits); otherwise the object's own fields as one row.
fn rows(v: &Value) -> Vec<Map<String, Value>> {
// A tool's plain value comes wrapped as `{"result": …}`, like evidence's result.
let wrapped = v.as_object().is_some_and(|m| m.len() == 1 && m.contains_key("result"));
let body = if is_evidence(v) || wrapped { &v["result"] } else { v };
let objects = |a: &[Value]| a.iter().filter_map(|i| i.as_object().cloned()).collect::<Vec<_>>();
let found = match body {
Value::Array(a) => objects(a),
Value::Object(m) => m.values().filter_map(Value::as_array).map(|a| objects(a)).max_by_key(Vec::len).unwrap_or_default(),
_ => Vec::new(),
};
if !found.is_empty() {
return found;
}
match body {
Value::Object(m) => vec![m.clone()],
_ => Vec::new(),
}
}
fn table(v: &Value, sep: char) -> String {
if let Some(e) = v.get("error") {
return text(&serde_json::json!({"error": e}), 0);
}
let rows = rows(v);
let mut columns: Vec<&String> = Vec::new();
for key in rows.iter().flat_map(|r| r.keys()) {
if !columns.contains(&key) {
columns.push(key);
}
}
let line = |cells: Vec<String>| cells.join(&sep.to_string());
let mut out = vec![line(columns.iter().map(|c| cell(&Value::String((*c).clone()), sep)).collect())];
for r in &rows {
out.push(line(columns.iter().map(|c| r.get(*c).map_or_else(String::new, |x| cell(x, sep))).collect()));
}
out.join("\n")
}
/// One table cell. What's in a result comes from the file being studied, so text a spreadsheet
/// would run as a formula is kept as text.
fn cell(v: &Value, sep: char) -> String {
let raw = match v {
Value::Null => String::new(),
Value::String(s) => s.clone(),
other => other.to_string(),
};
let safe = if matches!(v, Value::String(_)) && raw.starts_with(['=', '+', '-', '@', '\t', '\r']) { format!("'{raw}") } else { raw };
if sep == '\t' {
return safe.replace(['\t', '\n', '\r'], " ");
}
if safe.contains([sep, '"', '\n', '\r']) { format!("\"{}\"", safe.replace('"', "\"\"")) } else { safe }
}
fn is_evidence(v: &Value) -> bool {
v.get("id").and_then(Value::as_str).is_some_and(|i| i.starts_with("ev_")) && v.get("operation").is_some()
}
fn markdown(v: &Value) -> String {
if let Some(e) = v.get("error") {
let mut s = format!("**Error ({})**: {}\n", e["code"].as_str().unwrap_or("error"), e["message"].as_str().unwrap_or_default());
if let Some(r) = e.get("remediation").and_then(Value::as_str) {
s.push_str(&format!("\n**What to do:** {r}\n"));
}
return s;
}
if is_evidence(v) {
let mut s = format!("## {}\n\n", v["operation"].as_str().unwrap_or_default());
if let Some(sum) = v.get("summary").and_then(Value::as_str).filter(|s| !s.is_empty()) {
s.push_str(&format!("{sum}\n\n"));
}
s.push_str(&format!("- Evidence: `{}`\n- Confidence: {}\n", v["id"].as_str().unwrap_or_default(), v["confidence"].as_str().unwrap_or_default()));
if let Some(ls) = v.get("limitations").and_then(Value::as_array).filter(|l| !l.is_empty()) {
s.push_str("- Limitations:\n");
for l in ls {
s.push_str(&format!(" - {}\n", l["message"].as_str().unwrap_or_default()));
}
}
s.push_str(&format!("\n```json\n{}\n```\n", serde_json::to_string_pretty(&v["result"]).unwrap_or_default()));
return s;
}
format!("```json\n{}\n```\n", serde_json::to_string_pretty(v).unwrap_or_default())
}
fn text(v: &Value, depth: usize) -> String {
if depth == 0 {
if let Some(e) = v.get("error") {
let mut s = format!("error: {}", e["message"].as_str().unwrap_or_default());
if let Some(r) = e.get("remediation").and_then(Value::as_str) {
s.push_str(&format!("\nfix: {r}"));
}
return s;
}
if is_evidence(v) {
let sum = v.get("summary").and_then(Value::as_str).unwrap_or_default();
return format!("{sum}\n[{}; {}]\n{}", v["id"].as_str().unwrap_or_default(), v["confidence"].as_str().unwrap_or_default(), text(&v["result"], 1));
}
}
let pad = " ".repeat(depth.saturating_sub(1));
match v {
Value::Object(m) => m
.iter()
.map(|(k, val)| match val {
Value::Object(_) | Value::Array(_) => format!("{pad}{k}:\n{}", text(val, depth + 1)),
_ => format!("{pad}{k}: {}", scalar(val)),
})
.collect::<Vec<_>>()
.join("\n"),
Value::Array(a) => a
.iter()
.map(|val| match val {
Value::Object(_) | Value::Array(_) => format!("{pad}-\n{}", text(val, depth + 1)),
_ => format!("{pad}- {}", scalar(val)),
})
.collect::<Vec<_>>()
.join("\n"),
_ => format!("{pad}{}", scalar(v)),
}
}
fn scalar(v: &Value) -> String {
match v {
Value::String(s) => s.clone(),
other => other.to_string(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn formats() {
let v = json!({"a": 1, "b": {"c": [1, "x"]}});
assert_eq!(render(&v, Format::Jsonl), r#"{"a":1,"b":{"c":[1,"x"]}}"#);
let t = render(&v, Format::Text);
assert!(t.contains("a: 1") && t.contains("- x"), "{t}");
assert!(render(&v, Format::Md).starts_with("```json"));
let e = json!({"error": {"code": "bad_input", "message": "bad", "remediation": "fix it"}});
assert!(render(&e, Format::Text).contains("fix: fix it"));
assert!(render(&e, Format::Md).contains("What to do"));
assert_eq!(render(&json!([1, 2]), Format::Jsonl), "1\n2");
}
fn evidence(result: Value) -> Value {
json!({"id": "ev_1", "operation": "op", "summary": "s", "confidence": "observed", "result": result})
}
#[test]
fn tables_show_the_largest_list_of_rows() {
let v = evidence(json!({"total": 2, "notes": [{"a": 1}], "entries": [{"path": "a,b", "size": 1}, {"path": "c\"d", "kind": "x"}]}));
assert_eq!(render(&v, Format::Csv), "path,size,kind\n\"a,b\",1,\n\"c\"\"d\",,x");
assert_eq!(render(&v, Format::Tsv), "path\tsize\tkind\na,b\t1\t\nc\"d\t\tx");
}
#[test]
fn a_bare_array_and_a_plain_object_are_tables_too() {
assert_eq!(render(&json!([{"a": 1}, {"a": 2}]), Format::Csv), "a\n1\n2");
assert_eq!(render(&json!({"a": 1, "b": "x"}), Format::Csv), "a,b\n1,x");
assert_eq!(render(&json!([1, 2]), Format::Csv), "");
}
#[test]
fn a_plain_tools_wrapped_value_is_unwrapped() {
assert_eq!(render(&json!({"result": {"count": 0, "projects": [{"id": "a"}]}}), Format::Csv), "id\na");
assert_eq!(render(&json!({"result": {"count": 0}}), Format::Csv), "count\n0");
}
#[test]
fn nested_values_stay_json_in_one_cell() {
assert_eq!(render(&json!([{"a": {"b": [1, 2]}}]), Format::Csv), "a\n\"{\"\"b\"\":[1,2]}\"");
}
#[test]
fn text_from_a_hostile_file_cannot_become_a_spreadsheet_formula() {
for evil in ["=cmd|' /C calc'!A0", "+1+1", "-2", "@SUM(A1)", "\t=1"] {
let csv = render(&json!([{"name": evil}]), Format::Csv);
let cell = csv.lines().nth(1).unwrap().trim_start_matches('"');
assert!(cell.starts_with('\''), "{csv}");
let tsv = render(&json!([{"name": evil}]), Format::Tsv);
assert!(tsv.lines().nth(1).unwrap().starts_with('\''), "{tsv}");
}
assert_eq!(render(&json!([{"n": -2}]), Format::Csv), "n\n-2", "real numbers stay numbers");
}
#[test]
fn line_breaks_and_tabs_cannot_add_rows_or_columns() {
assert_eq!(render(&json!([{"a": "x\ny"}]), Format::Csv), "a\n\"x\ny\"");
assert_eq!(render(&json!([{"a": "x\n\ty"}]), Format::Tsv), "a\nx y");
}
#[test]
fn errors_stay_readable_in_table_formats() {
let e = json!({"error": {"code": "x", "message": "boom"}});
assert!(render(&e, Format::Csv).contains("boom"));
}
}
+254
View File
@@ -0,0 +1,254 @@
//! `rebuild`: the whole study → build → check workflow, headless. Questions and approvals are
//! answered on the terminal, or automatically with `--unattended` (first choice; approvals are
//! refused, so nothing outside the project happens without a person).
use crate::{Cli, INTERRUPTED, make_engine};
use clap::Args;
use craft_anything_ai::rebuild::{self, RebuildRun, RunEvent, RunOptions};
use craft_anything_ai::{AgentEvent, AiHub, BackendKind};
use craft_anything_engine::inbox::{Answer, Request, RequestKind};
use craft_anything_engine::workspace::Workspace;
use craft_anything_evidence::ToolError;
use std::io::{BufRead as _, Write as _};
use std::path::PathBuf;
use std::sync::atomic::Ordering;
use std::time::Duration;
#[derive(Debug, Args)]
pub struct RebuildArgs {
/// A web address, an absolute path to an app, game or file, or `-` for none.
pub target: String,
/// What to make, in your words.
pub request: String,
/// Where the new project folder goes (default: the projects folder from settings).
#[arg(long, conflicts_with = "project_folder")]
pub projects_dir: Option<PathBuf>,
/// Start the new project in this folder itself (it's added to the project list). If it
/// already has files, --existing says what they are.
#[arg(long, conflicts_with = "continue_in")]
pub project_folder: Option<PathBuf>,
/// With --project-folder that has files: `edit` (they're the app, edited in place) or
/// `start-from` (material to start from; the app is built in app/ beside them).
#[arg(long, requires = "project_folder", value_parser = ["edit", "start-from"])]
pub existing: Option<String>,
/// Continue an existing project folder; the request becomes a follow-up message.
#[arg(long)]
pub continue_in: Option<PathBuf>,
/// With --continue-in: carry on where the project's last run stopped (paused, or the app or
/// the computer stopped); the request is ignored.
#[arg(long, requires = "continue_in")]
pub resume: bool,
/// The coding agent to use (a backend name from `ai list`).
#[arg(long)]
pub backend: Option<String>,
/// Refinement rounds after the first build.
#[arg(long, default_value_t = 2)]
pub rounds: u32,
/// Answer questions with the first choice and refuse approvals, without asking.
#[arg(long)]
pub unattended: bool,
/// What to build with: an engine (unity, unreal, godot, rust) or a stack's full name.
/// New projects only; otherwise it's chosen from the request and target.
#[arg(long)]
pub build_with: Option<String>,
/// Let the builder generate pictures and 3D models for a new game (needs a fal.ai key; paid
/// within the project's asset budget). Change it later with `project-assets-allow`.
#[arg(long)]
pub generate_assets: bool,
}
pub fn rebuild(cli: &Cli, a: &RebuildArgs) -> u8 {
match run(cli, a) {
Ok(true) => 0,
Ok(false) => 1,
Err(e) => {
eprintln!("rebuild: {}", e.message);
if let Some(r) = e.remediation {
eprintln!(" {r}");
}
1
}
}
}
/// Use the configured agent app, or add the first one found on this computer.
fn ensure_agent(hub: &AiHub) -> Result<(), ToolError> {
if hub.backends().iter().any(|b| b.kind == BackendKind::AgentCli && b.enabled) {
return Ok(());
}
if let Some(d) = hub.detect().into_iter().find(|d| d.suggestion.kind == BackendKind::AgentCli) {
eprintln!("Using {} ({}).", d.suggestion.name, d.reason);
hub.add_backend(d.suggestion, None)?;
}
Ok(())
}
fn run(cli: &Cli, a: &RebuildArgs) -> Result<bool, ToolError> {
let engine = make_engine(None, cli.deep_for_run())?;
let hub = AiHub::new(engine.clone());
ensure_agent(&hub)?;
if a.build_with.is_some() && a.continue_in.is_some() {
return Err(ToolError::invalid("--build-with is for new projects; a project keeps the stack it was built with.")
.with_remediation("Leave out --build-with, or start a new project."));
}
if a.generate_assets && a.continue_in.is_some() {
return Err(ToolError::invalid("--generate-assets is for new projects.").with_remediation("Use project-assets-allow for an existing project."));
}
let (ws, message) = match &a.continue_in {
Some(dir) => (Workspace::open(&std::path::absolute(dir).map_err(|e| ToolError::io(dir.display(), e))?)?, (!a.resume).then(|| a.request.clone())),
None => {
use craft_anything_ai::rebuild::project::Place;
use craft_anything_engine::workspace::ExistingFiles;
let settings = engine.session().settings.clone();
let existing = a.existing.as_deref().map(|e| if e == "edit" { ExistingFiles::Edit } else { ExistingFiles::StartFrom });
let folder = a.project_folder.as_deref().map(std::path::absolute).transpose().map_err(|e| ToolError::io("--project-folder", e))?;
let place = match (&folder, &a.projects_dir) {
(Some(f), _) => Place::At(f, existing),
(None, Some(d)) => Place::In(d),
(None, None) => Place::Projects,
};
let ws = rebuild::project::new_project(&settings, &a.target, &a.request, place, a.build_with.as_deref(), a.generate_assets, a.backend.as_deref())?;
if folder.is_some() {
engine.session().remember_project(&ws.root)?;
}
(ws, None)
}
};
println!("Project: {}", ws.root.display());
// A follow-up shows in the project's feed as the person typed it.
let shown = message.clone();
let good_enough = engine.session().settings.build.good_enough;
let opts = RunOptions {
backend: a.backend.clone(),
message,
shown,
continuing: a.resume,
max_rounds: a.rounds,
good_enough,
beginner: !cli.json,
..RunOptions::default()
};
let mut run = RebuildRun::start(&hub, ws, opts)?;
let mut ok = false;
let mut line_open = false;
loop {
if INTERRUPTED.load(Ordering::SeqCst) {
run.stop();
}
for e in run.poll() {
match e {
RunEvent::Step { step, text } => {
end_line(&mut line_open);
println!("[{}] {text}", step.label());
}
RunEvent::Agent(AgentEvent::TextDelta { text }) => {
print!("{text}");
line_open = !text.ends_with('\n');
}
RunEvent::Agent(AgentEvent::ToolStarted { tool, .. }) => {
end_line(&mut line_open);
println!(" · {tool}");
}
RunEvent::Agent(AgentEvent::Error { message, .. }) => {
end_line(&mut line_open);
println!(" ! {message}");
}
RunEvent::Agent(_) => {}
RunEvent::Note(text) => {
end_line(&mut line_open);
println!(" + {text}");
}
RunEvent::Ask(r) => {
end_line(&mut line_open);
let answer = if a.unattended { auto_answer(&r) } else { prompt_answer(&r) };
run.answer(&r.id, &answer)?;
}
RunEvent::Checked(c) => {
end_line(&mut line_open);
match c.similarity {
Some(s) => println!("[Check {}] {s:.0}% alike — {}", c.round, c.note),
None => println!("[Check {}] {}", c.round, c.note),
}
}
RunEvent::Preview(url) => println!("Preview: {url}"),
RunEvent::Finished { ok: o, message, paused } => {
end_line(&mut line_open);
println!(
"{}",
if o {
format!("Done. {message}")
} else if paused {
message
} else {
format!("Stopped: {message}")
}
);
ok = o;
}
}
}
if !run.is_running() && run.poll().is_empty() {
break;
}
std::thread::sleep(Duration::from_millis(100));
}
let _ = std::io::stdout().flush();
Ok(ok)
}
fn end_line(open: &mut bool) {
if *open {
println!();
*open = false;
}
}
fn auto_answer(r: &Request) -> Answer {
match r.kind {
RequestKind::Question => {
println!("? {} → {} (unattended)", r.title, r.choices.first().map(String::as_str).unwrap_or("no preference"));
Answer {
choice: r.choices.first().cloned(),
text: r.choices.is_empty().then(|| "No preference; use your best judgement.".to_string()),
..Default::default()
}
}
RequestKind::Approval => {
println!("? {} → refused (unattended)", r.title);
Answer { allow: Some(false), text: Some("Unattended run: actions outside the project aren't allowed.".into()), ..Default::default() }
}
}
}
fn read_line() -> String {
let mut s = String::new();
let _ = std::io::stdin().lock().read_line(&mut s);
s.trim().to_string()
}
fn prompt_answer(r: &Request) -> Answer {
println!("\n? {}", r.title);
if !r.detail.is_empty() {
println!(" {}", r.detail.lines().take(12).collect::<Vec<_>>().join("\n "));
}
match r.kind {
RequestKind::Question => {
for (i, c) in r.choices.iter().enumerate() {
println!(" {}) {c}", i + 1);
}
print!("Your answer (number or text): ");
let _ = std::io::stdout().flush();
let line = read_line();
match line.parse::<usize>().ok().and_then(|n| n.checked_sub(1)).and_then(|i| r.choices.get(i)) {
Some(c) => Answer { choice: Some(c.clone()), ..Default::default() },
None => Answer { text: Some(line), ..Default::default() },
}
}
RequestKind::Approval => {
print!("Allow? [y]es / [a]lways for this project / [n]o: ");
let _ = std::io::stdout().flush();
let line = read_line().to_lowercase();
Answer { allow: Some(line.starts_with('y') || line.starts_with('a')), always: line.starts_with('a'), ..Default::default() }
}
}
}
+185
View File
@@ -0,0 +1,185 @@
//! `setup`, `doctor`, `uninstall`.
use crate::output::Format;
use crate::{emit, fail, out};
use clap::Args;
use craft_anything_setup::{ActionKind, CheckStatus, DoctorRequest, Host, PlanRequest};
use serde_json::{Value, json};
use std::io::IsTerminal as _;
#[derive(Debug, Args)]
pub struct SetupArgs {
/// Show what would change without writing anything.
#[arg(long)]
pub dry_run: bool,
/// Client to configure (repeatable): claude_code, codex, cursor, …
#[arg(long = "client")]
pub clients: Vec<String>,
/// Configure every detected client.
#[arg(long)]
pub all_detected: bool,
/// Apply without asking.
#[arg(long, short = 'y')]
pub yes: bool,
/// Don't install the skill.
#[arg(long)]
pub no_skill: bool,
}
#[derive(Debug, Args)]
pub struct DoctorArgs {
/// Only check these clients (repeatable).
#[arg(long = "client")]
pub clients: Vec<String>,
}
#[derive(Debug, Args)]
pub struct UninstallArgs {}
fn human(f: Format) -> bool {
matches!(f, Format::Text | Format::Md)
}
fn confirm(question: &str) -> bool {
if !(std::io::stdin().is_terminal() && std::io::stderr().is_terminal()) {
return false;
}
eprint!("{question} [y/N] ");
let mut line = String::new();
std::io::stdin().read_line(&mut line).is_ok() && matches!(line.trim(), "y" | "Y" | "yes")
}
fn print_plan(plan: &craft_anything_setup::Plan) {
out(&format!("Register: {}", plan.command.join(" ")));
for a in &plan.actions {
let v = serde_json::to_value(a).unwrap_or(Value::Null);
out(&format!("[{}] {} — {}", v["action"].as_str().unwrap_or_default(), a.display, v["path"].as_str().unwrap_or_default()));
if let Some(r) = v["reason"].as_str() {
out(&format!(" {r}"));
}
if let Some(r) = v["remediation"].as_str() {
out(&format!(" → {r}"));
}
if matches!(a.action, ActionKind::Create | ActionKind::Update) {
for l in v["preview"].as_str().unwrap_or_default().lines() {
out(&format!(" {l}"));
}
}
}
for s in &plan.skills {
let v = serde_json::to_value(s).unwrap_or(Value::Null);
out(&format!("[skill] {}", v["dir"].as_str().unwrap_or_default()));
}
for n in &plan.notes {
out(&format!("note: {n}"));
}
}
pub fn setup(a: &SetupArgs, f: Format) -> u8 {
let host = Host::current();
let command = match craft_anything_setup::default_command() {
Ok(c) => c,
Err(e) => return fail(&e, f),
};
let req = PlanRequest { clients: a.clients.clone(), all_detected: a.all_detected, command, include_skill: !a.no_skill };
let plan = match craft_anything_setup::plan(&host, &req) {
Ok(p) => p,
Err(e) => return fail(&e, f),
};
let status = if plan.blocked {
"blocked"
} else if a.dry_run {
"planned"
} else if plan.change_count() == 0 {
"unchanged"
} else {
""
};
if !status.is_empty() {
if human(f) {
print_plan(&plan);
out(&format!("status: {status}"));
} else {
emit(&json!({"status": status, "plan": plan}), f);
}
return if plan.blocked { 1 } else { 0 };
}
let approved = a.yes || {
if human(f) {
print_plan(&plan);
}
confirm(&format!("Apply these {} changes?", plan.change_count()))
};
if !approved {
if human(f) {
out("status: needs_confirmation (re-run with --yes to apply)");
} else {
emit(&json!({"status": "needs_confirmation", "plan": plan}), f);
}
return 1;
}
let report = craft_anything_setup::apply(&plan);
if human(f) {
for r in &report.results {
let v = serde_json::to_value(r).unwrap_or(Value::Null);
out(&format!(
"[{}] {} {}",
v["outcome"].as_str().unwrap_or_default(),
v["client"].as_str().unwrap_or_default(),
v["error"].as_str().unwrap_or_default()
));
}
out(&format!("status: {}", report.status));
if !report.restart.is_empty() {
out(&format!("Restart {} to load Craft Anything.", report.restart.join(", ")));
}
} else {
emit(&serde_json::to_value(&report).unwrap_or(Value::Null), f);
}
if matches!(report.status, "configured" | "unchanged") { 0 } else { 1 }
}
pub fn doctor(a: &DoctorArgs, f: Format) -> u8 {
let host = Host::current();
let req = DoctorRequest { clients: a.clients.clone(), extra: crate::ai_cmd::doctor_checks(), ..DoctorRequest::default() };
let report = craft_anything_setup::doctor(&host, &req);
if human(f) {
for c in &report.checks {
let st = match c.status {
CheckStatus::Ok => "ok",
CheckStatus::Warn => "warn",
CheckStatus::Fail => "FAIL",
CheckStatus::Info => "info",
};
out(&format!("[{st}] {}: {}", c.name, c.message));
if let Some(r) = &c.remediation {
out(&format!(" → {r}"));
}
}
out(if report.healthy { "healthy" } else { "problems found" });
} else {
emit(&serde_json::to_value(&report).unwrap_or(Value::Null), f);
}
if report.healthy { 0 } else { 1 }
}
pub fn uninstall(_a: &UninstallArgs, f: Format) -> u8 {
let report = craft_anything_setup::uninstall(&Host::current());
let v = serde_json::to_value(&report).unwrap_or(Value::Null);
if human(f) {
for r in &report.removed_entries {
let e = serde_json::to_value(r).unwrap_or(Value::Null);
out(&format!("removed {} ({})", e["client"].as_str().unwrap_or_default(), e["path"].as_str().unwrap_or_default()));
}
for p in &report.removed_skill_files {
out(&format!("removed {}", p.display()));
}
for b in &report.blocking {
out(&format!("blocked by {} — fix or move that file first", b.display));
}
out(&format!("status: {}", report.status));
} else {
emit(&v, f);
}
if matches!(report.status, "removed" | "nothing_to_remove") { 0 } else { 1 }
}
+408
View File
@@ -0,0 +1,408 @@
//! Turn `craft-anything-cli <tool> [path] [--json '{..}' | @file.json] [--key value…]` into tool params,
//! using the tool's JSON schema to type each flag.
use craft_anything_engine::{Requires, ToolSpec};
use serde_json::{Map, Value, json};
/// A parsed tool invocation.
#[derive(Debug, Default, PartialEq)]
pub struct ToolInvocation {
pub params: Value,
/// Path to open first (for tools that need an open target).
pub open_path: Option<String>,
/// Extra `core_target_open` params for that path (`format`, `architecture`, `entry_point`, `language_id`).
pub open_params: Map<String, Value>,
/// The output format asked for after the tool name (`--output-format`, or `--format` when the
/// tool has no `format` option of its own).
pub output_format: Option<String>,
pub help: bool,
}
/// `core_target_open` options a target tool accepts for its `<target-path>` (raw binaries, Deep pins).
const OPEN_OPTIONS: [&str; 3] = ["architecture", "entry_point", "language_id"];
/// `--format` values that pick how the target is opened rather than how output is printed.
const OPEN_FORMATS: [&str; 2] = ["raw-binary", "dos-com"];
fn schema_props(schema: &Value) -> Map<String, Value> {
schema.get("properties").and_then(Value::as_object).cloned().unwrap_or_default()
}
fn required(schema: &Value) -> Vec<String> {
schema.get("required").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()).unwrap_or_default()
}
/// The JSON type of a property ("string", "integer", "number", "boolean", "array", "object"), skipping "null".
fn prop_type(schema: &Value, prop: &Value) -> String {
let resolved = resolve_ref(schema, prop);
match resolved.get("type") {
Some(Value::String(s)) => s.clone(),
Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).find(|t| *t != "null").unwrap_or("string").to_string(),
_ => {
// anyOf/oneOf of [X, null]
for key in ["anyOf", "oneOf"] {
if let Some(arr) = resolved.get(key).and_then(Value::as_array) {
for alt in arr {
let t = prop_type(schema, alt);
if t != "null" {
return t;
}
}
}
}
if resolved.get("enum").is_some() { "string".into() } else { "any".into() }
}
}
}
fn resolve_ref<'a>(schema: &'a Value, prop: &'a Value) -> &'a Value {
if let Some(r) = prop.get("$ref").and_then(Value::as_str) {
let name = r.rsplit('/').next().unwrap_or_default();
for defs in ["$defs", "definitions"] {
if let Some(d) = schema.get(defs).and_then(|d| d.get(name)) {
return d;
}
}
}
prop
}
fn convert(ty: &str, key: &str, raw: &str) -> Result<Value, String> {
match ty {
"integer" => {
let t = raw.trim();
if let Some(h) = t.strip_prefix("0x").or_else(|| t.strip_prefix("0X")) {
u64::from_str_radix(h, 16).map(|n| json!(n)).map_err(|_| format!("--{key} expects a number, got {raw:?}"))
} else {
t.parse::<i64>().map(|n| json!(n)).map_err(|_| format!("--{key} expects a whole number, got {raw:?}"))
}
}
"number" => raw.trim().parse::<f64>().map(|n| json!(n)).map_err(|_| format!("--{key} expects a number, got {raw:?}")),
"boolean" => match raw.trim() {
"true" | "yes" | "1" => Ok(json!(true)),
"false" | "no" | "0" => Ok(json!(false)),
_ => Err(format!("--{key} expects true or false, got {raw:?}")),
},
"object" => serde_json::from_str::<Value>(raw).map_err(|e| format!("--{key} expects JSON: {e}")),
"array" => Ok(serde_json::from_str::<Value>(raw).ok().filter(Value::is_array).unwrap_or_else(|| json!([raw]))),
"string" => Ok(json!(raw)),
_ => Ok(serde_json::from_str::<Value>(raw).unwrap_or_else(|_| json!(raw))),
}
}
/// Read inline JSON or `@file.json`.
pub fn read_json_arg(raw: &str) -> Result<Value, String> {
let text = if raw == "-" {
read_stdin_json(std::io::stdin())?
} else {
match raw.strip_prefix('@') {
Some(path) => std::fs::read_to_string(path).map_err(|e| format!("can't read {path}: {e}"))?,
None => raw.to_string(),
}
};
serde_json::from_str(&text).map_err(|e| format!("params must be a JSON object: {e}"))
}
/// Most bytes of parameters taken from standard input.
const MAX_STDIN_JSON: u64 = 64 << 20;
/// Parameters piped in (`--json -`). Never waits at a terminal: nobody is going to type JSON there.
fn read_stdin_json<R: std::io::Read + std::io::IsTerminal>(input: R) -> Result<String, String> {
if input.is_terminal() {
return Err("--json - reads parameters from a pipe, but standard input is a terminal; pipe the JSON in, or pass it inline or as @file.json".into());
}
read_bounded_json(input)
}
fn read_bounded_json<R: std::io::Read>(input: R) -> Result<String, String> {
use std::io::Read as _;
let mut text = String::new();
let read = input.take(MAX_STDIN_JSON + 1).read_to_string(&mut text).map_err(|e| format!("can't read parameters from standard input: {e}"))?;
if read as u64 > MAX_STDIN_JSON {
return Err(format!("parameters on standard input are over the limit of {MAX_STDIN_JSON} bytes; use @file.json"));
}
Ok(text)
}
pub fn parse(spec: &ToolSpec, schema: &Value, args: &[String]) -> Result<ToolInvocation, String> {
let props = schema_props(schema);
let mut params = Map::new();
let mut positionals = Vec::new();
let mut inv = ToolInvocation::default();
let mut i = 0usize;
while let Some(a) = args.get(i) {
i += 1;
if a == "--help" || a == "-h" {
inv.help = true;
continue;
}
if a == "--json" || a == "--params" {
let raw = args.get(i).ok_or("--json needs a value")?;
i += 1;
merge(&mut params, read_json_arg(raw)?)?;
continue;
}
if let Some(rest) = a.strip_prefix("--") {
let (key, inline) = match rest.split_once('=') {
Some((k, v)) => (k.to_string(), Some(v.to_string())),
None => (rest.to_string(), None),
};
let snake = key.replace('-', "_");
let is_target = spec.requires == Requires::Target;
// Output format and target-open options, unless the tool has an option of the same name.
if !props.contains_key(&snake) && (snake == "output_format" || snake == "format" || (is_target && OPEN_OPTIONS.contains(&snake.as_str()))) {
let raw = match inline {
Some(v) => v,
None => {
let v = args.get(i).ok_or_else(|| format!("--{key} needs a value"))?.clone();
i += 1;
v
}
};
if snake == "output_format" || (snake == "format" && !(is_target && OPEN_FORMATS.contains(&raw.as_str()))) {
inv.output_format = Some(raw);
} else {
inv.open_params.insert(snake, json!(raw));
}
continue;
}
let prop = props.get(&snake).ok_or_else(|| {
let known: Vec<String> = props.keys().map(|k| format!("--{}", k.replace('_', "-"))).collect();
format!("{} has no option --{key}. Options: {}", spec.cli_name(), if known.is_empty() { "(none)".into() } else { known.join(", ") })
})?;
let ty = prop_type(schema, prop);
let raw = match inline {
Some(v) => v,
None if ty == "boolean" && args.get(i).is_none_or(|n| n.starts_with("--")) => "true".to_string(),
None => {
let v = args.get(i).ok_or_else(|| format!("--{key} needs a value"))?.clone();
i += 1;
v
}
};
let value = convert(&ty, &key, &raw)?;
if ty == "array"
&& let Some(Value::Array(existing)) = params.get_mut(&snake)
&& let Value::Array(more) = value
{
existing.extend(more);
continue;
}
params.insert(snake, value);
continue;
}
if let Some(path) = a.strip_prefix('@')
&& path.ends_with(".json")
{
merge(&mut params, read_json_arg(a)?)?;
continue;
}
positionals.push(a.clone());
}
// An architecture or entry point only means something for a raw binary.
if (inv.open_params.contains_key("architecture") || inv.open_params.contains_key("entry_point")) && !inv.open_params.contains_key("format") {
inv.open_params.insert("format".into(), json!("raw-binary"));
}
let mut positionals = positionals.into_iter();
if spec.requires == Requires::Target
&& let Some(p) = positionals.next()
{
inv.open_path = Some(p);
}
// Remaining positionals fill required string params in order, then an optional path (what a bare
// argument almost always is, whatever other options sort before it), then other string params.
let mut slots: Vec<String> = required(schema).into_iter().filter(|k| !params.contains_key(k)).collect();
if !slots.iter().any(|k| k == "path") && !params.contains_key("path") && props.get("path").is_some_and(|v| prop_type(schema, v) == "string") {
slots.push("path".into());
}
for k in props.keys() {
if !slots.contains(k) && !params.contains_key(k) && prop_type(schema, props.get(k).unwrap_or(&Value::Null)) == "string" {
slots.push(k.clone());
}
}
let mut slots = slots.into_iter();
for p in positionals {
let slot = slots.next().ok_or_else(|| format!("{} doesn't take another argument ({p:?})", spec.cli_name()))?;
let ty = prop_type(schema, props.get(&slot).unwrap_or(&Value::Null));
params.insert(slot.clone(), convert(&ty, &slot.replace('_', "-"), &p)?);
}
inv.params = Value::Object(params);
Ok(inv)
}
fn merge(into: &mut Map<String, Value>, v: Value) -> Result<(), String> {
match v {
Value::Object(m) => {
into.extend(m);
Ok(())
}
_ => Err("params must be a JSON object".into()),
}
}
/// Help text for one tool, generated from its schema.
/// The fields inside an object option (or an array of objects), listed under it as
/// `option.field`, two levels deep and at most 30 a level.
fn nested_fields(schema: &Value, prop: &Value, path: &str, depth: usize, out: &mut String) {
if depth > 2 {
return;
}
let mut obj = resolve_ref(schema, prop);
// Option<T> arrives as anyOf/oneOf [T, null].
if let Some(alt) = ["anyOf", "oneOf"]
.iter()
.find_map(|k| obj.get(*k).and_then(Value::as_array))
.and_then(|a| a.iter().find(|x| x.get("type").and_then(Value::as_str) != Some("null")))
{
obj = resolve_ref(schema, alt);
}
if obj.get("type").and_then(Value::as_str) == Some("array")
&& let Some(items) = obj.get("items")
{
obj = resolve_ref(schema, items);
}
let Some(fields) = obj.get("properties").and_then(Value::as_object) else { return };
let req = required(obj);
for (name, f) in fields.iter().take(30) {
let ty = prop_type(schema, f);
let desc = f.get("description").and_then(Value::as_str).unwrap_or_default();
let star = if req.contains(name) { " (required)" } else { "" };
let field = format!("{path}.{name}");
out.push_str(&format!(" {field:<26} {ty}{star} {desc}\n"));
nested_fields(schema, f, &field, depth + 1, out);
}
}
pub fn help(spec: &ToolSpec, schema: &Value) -> String {
let props = schema_props(schema);
let req = required(schema);
let mut s = format!("{} — {}\n\n{}\n\nUsage: craft-anything-cli {}", spec.cli_name(), spec.title, spec.summary, spec.cli_name());
if spec.requires == Requires::Target {
s.push_str(" <target-path>");
}
s.push_str(" [options] [--json '{...}' | @params.json | -]\n");
if !props.is_empty() {
s.push_str("\nOptions:\n");
for (k, p) in &props {
let ty = prop_type(schema, p);
let desc = p.get("description").and_then(Value::as_str).unwrap_or_default();
let star = if req.contains(k) { " (required)" } else { "" };
s.push_str(&format!(" --{:<28} {ty}{star} {desc}\n", k.replace('_', "-")));
nested_fields(schema, p, k, 1, &mut s);
}
}
if spec.requires == Requires::Target {
s.push_str("\nTarget options (how <target-path> is opened):\n");
s.push_str(" --architecture x86, x86_64, arm or arm64 for a raw binary (implies --format raw-binary)\n");
s.push_str(" --entry-point Load/entry address (0x-hex) for a raw binary\n");
s.push_str(" --format raw-binary or dos-com to force how the file is read\n");
s.push_str(" --language-id Deep mode only: pin a Ghidra processor language\n");
}
let own_format = props.contains_key("format");
s.push_str(&format!(
"\nOutput:\n --output-format json, jsonl, md or text{}\n",
if own_format { " (--format after the tool name is this tool's own option)" } else { " (--format works too)" }
));
s
}
#[cfg(test)]
mod tests {
use super::*;
use craft_anything_engine::Registry;
// The tests use built-in tools, whose schema is their own type's.
fn parse(spec: &ToolSpec, args: &[String]) -> Result<ToolInvocation, String> {
super::parse(spec, &(spec.input_schema)(), args)
}
fn help(spec: &ToolSpec) -> String {
super::help(spec, &(spec.input_schema)())
}
#[test]
fn help_lists_fields_inside_object_options() {
let r = Registry::with_all_tools();
let h = help(r.get("app_rebuild_claim_check").unwrap());
assert!(h.contains("specification.goal"), "{h}");
assert!(h.contains("specification.expectations.evidence_ids"), "array items are listed too: {h}");
let plan = help(r.get("core_plan_update").unwrap());
assert!(plan.contains(" steps."), "{plan}");
let flat = help(r.get("core_target_open").unwrap());
assert!(!flat.contains(" path."), "plain options have no nested lines");
}
#[test]
fn flags_positionals_and_json() {
let r = Registry::with_all_tools();
let open = r.get("core_target_open").unwrap();
let inv = parse(open, &["/bin/ls".into()]).unwrap();
assert_eq!(inv.params["path"], "/bin/ls");
assert!(inv.open_path.is_none());
let upd = r.get("core_plan_update").unwrap();
let inv = parse(upd, &["--json".into(), r#"{"steps":[]}"#.into(), "--based-on-revision".into(), "3".into()]).unwrap();
assert_eq!(inv.params, json!({"steps": [], "based_on_revision": 3}));
assert!(parse(upd, &["--nope".into(), "1".into()]).unwrap_err().contains("--steps"));
assert!(parse(upd, &["--based-on-revision".into(), "x".into()]).is_err());
let close = r.get("core_target_close").unwrap();
let inv = parse(close, &["/tmp/a.bin".into()]).unwrap();
assert_eq!(inv.open_path.as_deref(), Some("/tmp/a.bin"));
let rj = r.get("core_journal_read").unwrap();
let inv = parse(rj, &["--limit=5".into(), "--kind".into(), "tool_call".into()]).unwrap();
assert_eq!(inv.params, json!({"limit": 5, "kind": "tool_call"}));
assert!(parse(rj, &["--help".into()]).unwrap().help);
assert!(help(rj).contains("--limit"));
}
#[test]
fn format_flag_goes_to_the_tool_its_target_or_the_output() {
let r = Registry::with_all_tools();
// A tool with its own `format` option keeps it; the output format has its own flag.
let open = r.get("core_target_open").unwrap();
let inv = parse(open, &["--format".into(), "raw-binary".into(), "--output-format".into(), "text".into()]).unwrap();
assert_eq!(inv.params["format"], "raw-binary");
assert_eq!(inv.output_format.as_deref(), Some("text"));
assert!(help(open).contains("this tool's own option"));
// Without one, --format is the output format...
let rj = r.get("core_journal_read").unwrap();
let inv = parse(rj, &["--format=md".into()]).unwrap();
assert_eq!(inv.output_format.as_deref(), Some("md"));
assert_eq!(inv.params, json!({}));
// ...and on a target tool, raw-binary/dos-com and the raw options describe how to open the path.
let pc = r.get("native_function_pseudocode").unwrap();
let args: Vec<String> = ["/tmp/raw.bin", "--architecture", "x86_64", "--entry-point", "0x1000", "--function", "0x1000", "--format", "text"]
.iter()
.map(|s| s.to_string())
.collect();
let inv = parse(pc, &args).unwrap();
assert_eq!(inv.open_path.as_deref(), Some("/tmp/raw.bin"));
assert_eq!(Value::Object(inv.open_params.clone()), json!({"architecture": "x86_64", "entry_point": "0x1000", "format": "raw-binary"}));
assert_eq!(inv.output_format.as_deref(), Some("text"));
let inv = parse(pc, &["/tmp/a.com".into(), "--format".into(), "dos-com".into()]).unwrap();
assert_eq!(inv.open_params["format"], "dos-com");
assert!(inv.output_format.is_none());
assert!(help(pc).contains("--entry-point"));
}
#[test]
fn at_file_input() {
let dir = std::env::temp_dir().join(format!("cany-cli-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let f = dir.join("p.json");
std::fs::write(&f, r#"{"question":"q?"}"#).unwrap();
let r = Registry::with_all_tools();
let inv = parse(r.get("core_brief_write").unwrap(), &[format!("@{}", f.display())]).unwrap();
assert_eq!(inv.params["question"], "q?");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn parameters_from_a_pipe_are_bounded() {
assert_eq!(read_bounded_json(&b"{\"a\":1}"[..]).unwrap(), "{\"a\":1}");
let big = std::io::repeat(b' ').take(MAX_STDIN_JSON + 10);
use std::io::Read as _;
assert!(read_bounded_json(big).unwrap_err().contains("over the limit"));
assert!(read_bounded_json(&[0xffu8, 0xfe][..]).is_err(), "bad text is an error");
}
}
+189
View File
@@ -0,0 +1,189 @@
//! End-to-end tests of the built binary (run through the process runner).
use craft_anything_platform::process::{Output, Process};
use serde_json::{Value, json};
use std::time::Duration;
fn cli(args: &[&str], config: &std::path::Path) -> Output {
Process::new(env!("CARGO_BIN_EXE_craft-anything-cli")).args(args).env("CRAFT_ANYTHING_CONFIG_DIR", config).timeout(Duration::from_secs(60)).run().unwrap()
}
#[test]
fn commands_and_exit_codes() {
let cfg = tempfile::tempdir().unwrap();
let out = cli(&["commands", "--format", "json"], cfg.path());
assert!(out.success);
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
assert!(v.as_array().unwrap().iter().any(|c| c["command"] == "core-session-show"));
assert_eq!(cli(&["no-such-tool"], cfg.path()).code, Some(2));
assert_eq!(cli(&["--bogus-flag"], cfg.path()).code, Some(2));
let fail = cli(&["core-finding-record", "--statement", "x", "--evidence-ids", "ev_nope"], cfg.path());
assert_eq!(fail.code, Some(1));
let e: Value = serde_json::from_slice(&fail.stdout).unwrap();
assert_eq!(e["error"]["code"], "bad_input");
}
/// After the tool name, `--project` is the tool's own option when it has one (it used to be taken
/// as the global investigation folder, which was then created there).
#[test]
fn a_tools_own_project_option_reaches_the_tool() {
let cfg = tempfile::tempdir().unwrap();
let folder = tempfile::tempdir().unwrap();
let out = cli(&["project-show", "--project", folder.path().to_str().unwrap()], cfg.path());
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
// project_show read the folder (it isn't a project, so it says so) instead of missing its option.
let msg = v["error"]["message"].as_str().unwrap_or_default();
assert!(!msg.contains("missing field") && !msg.contains("`project`"), "{v}");
assert_eq!(std::fs::read_dir(folder.path()).unwrap().count(), 0, "no investigation was created in the folder");
}
#[test]
fn target_tools_open_then_close_and_project_journal() {
let cfg = tempfile::tempdir().unwrap();
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("sample.bin");
std::fs::write(&file, b"\x7fELF not really").unwrap();
let proj = dir.path().join("p.cany");
let out = cli(&["--deep", "native-cursor-show", file.to_str().unwrap(), "--format", "json", "--project", proj.to_str().unwrap()], cfg.path());
assert!(out.success, "{}", out.stdout_text());
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(v["result"]["document"], "sample.bin");
let days: Vec<_> = std::fs::read_dir(proj.join("journal")).unwrap().collect();
assert_eq!(days.len(), 1);
}
#[test]
fn clean_room_refuses_to_look_inside_and_says_how_to_turn_on_deep_mode() {
let cfg = tempfile::tempdir().unwrap();
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("sample.bin");
std::fs::write(&file, b"\x7fELF not really").unwrap();
let out = cli(&["core-target-open", file.to_str().unwrap()], cfg.path());
assert_eq!(out.code, Some(1), "{}", out.stdout_text());
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(v["error"]["details"]["reason"], "clean_room", "{v}");
assert!(v["error"]["remediation"].as_str().unwrap_or_default().contains("--deep"), "{v}");
// --deep is for this run only: nothing is saved.
assert!(cli(&["--deep", "core-target-open", file.to_str().unwrap()], cfg.path()).success);
assert!(!cfg.path().join("config.toml").exists(), "the run's mode isn't saved");
assert_eq!(cli(&["--deep", "--clean-room", "core-session-show"], cfg.path()).code, Some(2));
assert_eq!(cli(&["core-session-show", "--deep", "--clean-room"], cfg.path()).code, Some(2));
}
#[test]
fn mcp_over_stdio() {
let cfg = tempfile::tempdir().unwrap();
let input = [
json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}}),
json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}),
json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "core_session_show", "arguments": {}}}),
]
.iter()
.map(|v| format!("{v}\n"))
.collect::<String>();
let out = Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
.arg("mcp")
.env("CRAFT_ANYTHING_CONFIG_DIR", cfg.path())
.stdin_bytes(input)
.timeout(Duration::from_secs(30))
.run()
.unwrap();
assert!(out.success);
let msgs: Vec<Value> = out.stdout_text().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
let by_id = |id: u64| msgs.iter().find(|m| m["id"] == json!(id)).unwrap().clone();
assert_eq!(by_id(1)["result"]["serverInfo"]["name"], "craft-anything");
assert!(by_id(2)["result"]["tools"].as_array().unwrap().iter().any(|t| t["name"] == "core_session_show"));
assert_eq!(by_id(3)["result"]["isError"], false);
}
#[test]
fn raw_binary_open_params_tool_format_and_project_evidence_across_processes() {
let cfg = tempfile::tempdir().unwrap();
let dir = tempfile::tempdir().unwrap();
let raw = dir.path().join("raw.bin");
// push rbp; mov rbp, rsp; xor eax, eax; pop rbp; ret
std::fs::write(&raw, [0x55, 0x48, 0x89, 0xe5, 0x31, 0xc0, 0x5d, 0xc3]).unwrap();
let raw = raw.to_str().unwrap();
let proj = dir.path().join("p.cany");
let proj = proj.to_str().unwrap();
// A tool's own --format reaches the tool; the output format has --output-format.
let out = cli(
&["core-target-open", raw, "--format", "raw-binary", "--architecture", "x86_64", "--entry-point", "0x1000", "--output-format", "json", "--deep"],
cfg.path(),
);
assert!(out.success, "{}", out.stdout_text());
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
assert_eq!(v["result"]["kind"], "raw-binary", "{v}");
// A target tool reopens the path with the raw-binary options.
let out = cli(
&["--deep", "native-function-pseudocode", raw, "--architecture", "x86_64", "--entry-point", "0x1000", "--function", "0x1000", "--project", proj],
cfg.path(),
);
assert!(out.success, "{}", out.stdout_text());
// A new process on the same project sees the stored evidence.
let out = cli(&["core-evidence-show", "--detail", "summary", "--project", proj], cfg.path());
assert!(out.success, "{}", out.stdout_text());
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
assert!(v["result"]["total"].as_u64().unwrap() >= 1, "{v}");
let out = cli(&["core-session-show", "--project", proj], cfg.path());
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
assert!(v["result"]["evidence_records"].as_u64().unwrap() >= 1, "{v}");
}
fn cli_with_stdin(args: &[&str], config: &std::path::Path, input: &[u8]) -> Output {
Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
.args(args)
.env("CRAFT_ANYTHING_CONFIG_DIR", config)
.stdin_bytes(input.to_vec())
.timeout(Duration::from_secs(60))
.run()
.unwrap()
}
/// `--json -` takes a tool's parameters from a pipe, and `-` isn't read as the shorthand for JSON output.
#[test]
fn parameters_can_come_from_a_pipe() {
let cfg = tempfile::tempdir().unwrap();
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("plain.txt");
std::fs::write(&file, b"nothing packed here").unwrap();
let params = json!({"path": file}).to_string();
let out = cli_with_stdin(&["core-packed-files-list", "--deep", "--json", "-"], cfg.path(), params.as_bytes());
let v: Value = serde_json::from_slice(&out.stdout).unwrap();
// The file reached the tool: it says the file isn't packed, not that the path is missing.
assert_eq!(v["error"]["code"], "not_supported", "{v}");
let bad = cli_with_stdin(&["core-packed-files-list", "--deep", "--json", "-"], cfg.path(), b"not json");
assert_eq!(bad.code, Some(2), "{}", String::from_utf8_lossy(&bad.stderr));
let empty = cli_with_stdin(&["core-packed-files-list", "--deep", "--json", "-"], cfg.path(), b"");
assert_eq!(empty.code, Some(2), "an empty pipe is an error, not a wait");
}
#[test]
fn csv_and_tsv_output_show_a_tools_rows() {
let cfg = tempfile::tempdir().unwrap();
let out = cli(&["core-session-show", "--output-format", "csv"], cfg.path());
assert!(out.success);
let text = String::from_utf8_lossy(&out.stdout);
let mut lines = text.lines();
assert!(lines.next().unwrap().split(',').any(|c| c == "clean_room"), "{text}");
let tsv = cli(&["core-session-show", "--output-format", "tsv"], cfg.path());
assert!(String::from_utf8_lossy(&tsv.stdout).lines().next().unwrap().split('\t').any(|c| c == "clean_room"));
}
/// A bare argument is the file, not whichever string option sorts first (`contains`, `detail`).
#[test]
fn a_bare_argument_is_the_path_even_when_other_options_sort_first() {
let cfg = tempfile::tempdir().unwrap();
let dir = tempfile::tempdir().unwrap();
let file = dir.path().join("plain.txt");
std::fs::write(&file, b"nothing packed here").unwrap();
let path = file.to_str().unwrap();
let packed: Value = serde_json::from_slice(&cli(&["core-packed-files-list", "--deep", path], cfg.path()).stdout).unwrap();
assert_eq!(packed["error"]["code"], "not_supported", "the file was read: {packed}");
let model: Value = serde_json::from_slice(&cli(&["formats-ai-weights-show", "--deep", path], cfg.path()).stdout).unwrap();
assert!(!model["error"]["message"].as_str().unwrap_or_default().contains("unknown variant"), "{model}");
}
@@ -0,0 +1,47 @@
//! Live end-to-end rebuild with a real coding agent. Opt-in: it needs network access, a
//! signed-in Claude Code (`claude auth login`) and spends the person's usage, so it only runs
//! with `CRAFT_E2E=1`:
//!
//! ```sh
//! CRAFT_E2E=1 cargo test -p craft-anything-cli --test live_rebuild -- --nocapture
//! ```
use craft_anything_platform::process::Process;
use serde_json::Value;
use std::time::Duration;
fn enabled() -> bool {
let on = std::env::var("CRAFT_E2E").is_ok_and(|v| v == "1");
if !on {
eprintln!("skipped: set CRAFT_E2E=1 to run the live rebuild");
}
on
}
#[test]
fn website_clone_reaches_ready_and_looks_alike() {
if !enabled() {
return;
}
let projects = tempfile::tempdir().unwrap();
let out = Process::new(env!("CARGO_BIN_EXE_craft-anything-cli"))
.args(["rebuild", "https://example.com", "Clone this website", "--rounds", "1", "--unattended", "--format", "text"])
.arg("--projects-dir")
.arg(projects.path())
.timeout(Duration::from_secs(45 * 60))
.idle_timeout(Duration::from_secs(15 * 60))
.run()
.unwrap();
let log = out.stdout_text();
assert!(out.success, "rebuild failed:\n{log}");
let dirs: Vec<_> = std::fs::read_dir(projects.path()).unwrap().filter_map(Result::ok).filter(|e| e.path().is_dir()).collect();
assert_eq!(dirs.len(), 1, "one project folder");
let root = dirs[0].path();
let manifest: Value = serde_json::from_slice(&std::fs::read(root.join("craft.json")).unwrap()).unwrap();
assert_eq!(manifest["status"], "ready", "{log}");
assert_eq!(manifest["target"]["kind"], "website");
let best = manifest["checks"].as_array().unwrap().iter().filter_map(|c| c["similarity"].as_f64()).fold(0.0, f64::max);
assert!(best >= 80.0, "best likeness {best:.0}%:\n{log}");
assert!(["dist", "out", "build"].iter().any(|d| root.join("app").join(d).join("index.html").is_file()), "a built site in app/dist, app/out or app/build");
}
+56
View File
@@ -0,0 +1,56 @@
//! Plugins end to end: Craft Anything's own MCP server (`craft-anything-cli mcp`) configured as a
//! plugin, refreshed, listed and called through the CLI. Everything stays in temp folders.
use craft_anything_platform::process::{Output, Process};
use serde_json::Value;
use std::time::Duration;
fn cli(args: &[&str], config: &std::path::Path) -> Output {
Process::new(env!("CARGO_BIN_EXE_craft-anything-cli")).args(args).env("CRAFT_ANYTHING_CONFIG_DIR", config).timeout(Duration::from_secs(120)).run().unwrap()
}
#[test]
fn an_mcp_server_becomes_a_toolset_of_proxied_tools() {
let cfg = tempfile::tempdir().unwrap();
let projects = tempfile::tempdir().unwrap();
let exe = env!("CARGO_BIN_EXE_craft-anything-cli");
std::fs::write(
cfg.path().join("config.toml"),
format!("version = 1\n\n[[plugins.mcp]]\nid = \"selfmcp\"\nname = \"Itself\"\ncommand = '{exe}'\nargs = [\"mcp\", \"--all-tools\"]\nconsent = false\n"),
)
.unwrap();
// Before a refresh nothing is cached, so no proxied tools.
let list = cli(&["plugins-list", "--format", "json"], cfg.path());
assert!(list.success, "{}", list.stdout_text());
let v: Value = serde_json::from_slice(&list.stdout).unwrap();
assert_eq!(v["result"]["plugins"][0]["id"], "selfmcp");
assert_eq!(v["result"]["plugins"][0]["cached_tools"].as_array().map(Vec::len), Some(0));
// Refreshing starts the server (it's a program, so it needs --allow-run) and caches its tools.
assert!(!cli(&["plugins-refresh", "--format", "json"], cfg.path()).success, "refused without consent");
let r = cli(&["plugins-refresh", "--allow-run", "--format", "json"], cfg.path());
assert!(r.success, "{}", r.stdout_text());
let v: Value = serde_json::from_slice(&r.stdout).unwrap();
let tools = v["result"]["refreshed"][0]["tools"].as_array().cloned().unwrap_or_default();
assert!(tools.iter().any(|t| t == "project_list"), "{v}");
// The next start offers them as a toolset of its own.
let c = cli(&["commands", "--format", "json"], cfg.path());
let v: Value = serde_json::from_slice(&c.stdout).unwrap();
let ours = v.as_array().unwrap().iter().find(|c| c["command"] == "selfmcp-project-list").cloned();
assert_eq!(ours.as_ref().map(|c| c["toolset"].clone()), Some(Value::from("selfmcp")), "{v}");
// A plugin's tool may look at anything, so Clean room doesn't run it.
let dir = projects.path().to_str().unwrap();
let refused = cli(&["selfmcp-project-list", "--projects-dir", dir, "--format", "json"], cfg.path());
let v: Value = serde_json::from_slice(&refused.stdout).unwrap();
assert_eq!(v["error"]["details"]["reason"], "clean_room", "{v}");
// In Deep mode a call goes through the server and comes back as evidence from an external service.
let call = cli(&["--deep", "selfmcp-project-list", "--projects-dir", dir, "--format", "json"], cfg.path());
assert!(call.success, "{}", call.stdout_text());
let v: Value = serde_json::from_slice(&call.stdout).unwrap();
assert_eq!(v["authority"], "outside-service", "{v}");
assert!(v.to_string().contains("projects_dir"), "{v}");
}
+32
View File
@@ -0,0 +1,32 @@
[package]
name = "craft-anything-web"
description = "Craft Anything in the browser: drop a file to see what it is (eframe web runner, WebGPU with WebGL2 fallback)"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lints]
workspace = true
[[bin]]
name = "craft-anything-web"
path = "src/main.rs"
[dependencies]
# Only the wasm-safe crates (`cargo xtask wasm`): no engine, platform, AI or desktop UI.
craft-anything-evidence = { workspace = true }
craft-anything-formats = { workspace = true }
craft-anything-analysis = { workspace = true }
egui = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit"] }
# Open button: the browser's file picker (an <input type="file">, read in memory).
rfd = { workspace = true }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location"] }
+10
View File
@@ -0,0 +1,10 @@
# Build with: trunk build --release (from apps/craft-anything-web)
[build]
target = "index.html"
dist = "../../dist/web"
public_url = "./"
filehash = true
[serve]
addresses = ["127.0.0.1"]
port = 8771
+19
View File
@@ -0,0 +1,19 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>Craft Anything</title>
<link data-trunk rel="rust" data-bin="craft-anything-web" data-cargo-profile="web-release" data-wasm-opt="z" data-wasm-opt-params="--enable-bulk-memory --enable-bulk-memory-opt --enable-nontrapping-float-to-int --enable-sign-ext --enable-reference-types --enable-multivalue" data-weak-refs />
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #0e0e0f; }
#craft_anything_canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
#craft_anything_loading { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;
color: #a9a9b2; font: 14px system-ui, sans-serif; pointer-events: none; }
</style>
</head>
<body>
<canvas id="craft_anything_canvas"></canvas>
<div id="craft_anything_loading">Loading Craft Anything&hellip;</div>
</body>
</html>
+27
View File
@@ -0,0 +1,27 @@
//! Craft Anything in the browser: a small viewer that tells you what a file is.
//!
//! It runs only the wasm-safe crates (formats, analysis, evidence), entirely in the page: the file
//! never leaves the browser. Native programs (ELF, PE, Mach-O, DOS) get the same plain-English
//! triage as the desktop app's `triage_binary`; other files are identified by their signature. The
//! desktop app does everything else (disassembly, JavaScript apps, Android, devices, AI).
//!
//! Build with `trunk build --release` from this directory; the site lands in `dist/web`.
//! URL query flag: `?webgl` forces the WebGL2 backend instead of WebGPU.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
// The viewer and triage only run in the browser; natively they're compiled (and tested) but unused.
#![cfg_attr(not(target_arch = "wasm32"), allow(dead_code))]
mod triage;
mod viewer;
#[cfg(target_arch = "wasm32")]
mod web;
#[cfg(target_arch = "wasm32")]
fn main() {
web::start();
}
#[cfg(not(target_arch = "wasm32"))]
fn main() {
eprintln!("craft-anything-web only runs in the browser: build it with `trunk build --release` in apps/craft-anything-web");
}
+145
View File
@@ -0,0 +1,145 @@
//! What a dropped file is: native triage for programs, a signature check for everything else.
//!
//! Pure and synchronous (no clock, threads or file system), so it is safe in the browser.
use craft_anything_analysis::js_inventory::sniff_kind;
use craft_anything_analysis::native;
use craft_anything_evidence::{Confidence, sha256_hex};
use craft_anything_formats::{entropy, parse_binary};
use serde_json::Value;
/// Largest file the page reads (browser memory is the limit; the desktop app has none).
pub const MAX_BYTES: usize = 512 * 1024 * 1024;
/// The answer for one file.
pub struct Look {
pub file_name: String,
/// One or two plain sentences.
pub summary: String,
pub confidence: Confidence,
/// Label/value pairs shown as a table.
pub facts: Vec<(String, String)>,
pub limitations: Vec<String>,
/// The full result, pretty-printed (empty when there is none beyond the facts).
pub details: String,
}
pub fn look(file_name: &str, bytes: &[u8]) -> Look {
let mut facts = vec![("Size".to_string(), size_text(bytes.len())), ("SHA-256".to_string(), sha256_hex(bytes))];
let sample = bytes.get(..bytes.len().min(4 * 1024 * 1024)).unwrap_or_default();
facts.push(("Entropy (first 4 MB)".to_string(), format!("{:.2} bits per byte", entropy(sample))));
let kind = sniff_kind(bytes, file_name);
if let Ok(bin) = parse_binary(bytes) {
let report = native::triage(&bin, bytes, file_name);
let field = |k: &str| report.result.get(k).and_then(Value::as_str).map(str::to_string);
let mut native_facts = Vec::new();
for (label, key) in
[("Format", "format_name"), ("Runs on", "operating_system"), ("Kind", "kind"), ("Architecture", "architecture"), ("Entry point", "entry_point")]
{
if let Some(v) = field(key) {
native_facts.push((label.to_string(), v));
}
}
if let Some(s) = report.result.get("stripped").and_then(Value::as_bool) {
native_facts.push(("Names removed (stripped)".to_string(), if s { "yes" } else { "no" }.to_string()));
}
native_facts.append(&mut facts);
return Look {
file_name: file_name.to_string(),
summary: report.summary,
confidence: report.confidence,
facts: native_facts,
limitations: report.limitations.into_iter().map(|l| l.message).collect(),
details: serde_json::to_string_pretty(&report.result).unwrap_or_default(),
};
}
let (what, next) = describe(kind);
facts.insert(0, ("Detected as".to_string(), kind.to_string()));
Look {
file_name: file_name.to_string(),
summary: format!("{file_name} looks like {what}. {next}"),
confidence: if matches!(kind, "text" | "binary") { Confidence::Inferred } else { Confidence::Observed },
facts,
limitations: vec!["identified from its first bytes and name only; the web viewer doesn't open containers or code".to_string()],
details: String::new(),
}
}
/// A plain description of a sniffed kind, and where to look next.
fn describe(kind: &str) -> (&'static str, &'static str) {
const DESKTOP: &str = "Open it in the Craft Anything desktop app to look inside.";
match kind {
"wasm" => ("a WebAssembly module (code that runs in browsers and other hosts)", DESKTOP),
"dex" => ("Android app code (a DEX file)", DESKTOP),
"apk" => ("an Android app package", DESKTOP),
"ipa" => ("an iPhone/iPad app package", DESKTOP),
"jar" => ("a Java archive", DESKTOP),
"java-class" => ("a compiled Java class", DESKTOP),
"msix" => ("a Windows app package (MSIX/AppX)", DESKTOP),
"hap" => ("a HarmonyOS app package", DESKTOP),
"zip" => ("a ZIP archive", DESKTOP),
"asar" => ("an Electron app archive (app.asar): the app's JavaScript lives here", DESKTOP),
"native-addon" => ("a Node.js native add-on", DESKTOP),
"javascript" | "typescript" => ("JavaScript or TypeScript source", DESKTOP),
"source-map" => ("a source map (links bundled JavaScript back to its sources)", DESKTOP),
"binary-plist" | "xml-plist" => ("an Apple property list (settings or app metadata)", DESKTOP),
"gzip" => ("gzip-compressed data", DESKTOP),
"xar" => ("a XAR archive (macOS installer packages use it)", DESKTOP),
"sqlite" => ("an SQLite database", DESKTOP),
"png" | "jpeg" | "gif" | "svg" => ("an image", "There's no code to look at in an image."),
"pdf" => ("a PDF document", "There's no program to look at here."),
"json" | "html" | "css" | "xml" | "text" => ("text", DESKTOP),
_ => ("data we don't recognise", "The desktop app has many more ways to identify files."),
}
}
fn size_text(n: usize) -> String {
const UNITS: [&str; 4] = ["KB", "MB", "GB", "TB"];
if n < 1024 {
return format!("{n} bytes");
}
let mut v = n as f64 / 1024.0;
let mut unit = UNITS[0];
for u in UNITS.iter().skip(1) {
if v < 1024.0 {
break;
}
v /= 1024.0;
unit = u;
}
format!("{v:.1} {unit} ({n} bytes)")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn empty_and_garbage_never_crash() {
for bytes in [&b""[..], b"\x7fELF", b"MZ\0\0\0\0", &[0xcf, 0xfa, 0xed, 0xfe, 1, 2], &[0xca, 0xfe, 0xba, 0xbe, 0, 0, 0, 9]] {
let l = look("x", bytes);
assert!(!l.summary.is_empty());
}
}
#[test]
fn signatures() {
assert!(look("a.png", b"\x89PNG\r\n\x1a\n").summary.contains("image"));
assert!(look("m.wasm", b"\0asm\x01\0\0\0").summary.contains("WebAssembly"));
}
#[test]
fn host_program() {
let Ok(bytes) = std::fs::read("/bin/ls") else { return };
let l = look("ls", &bytes);
assert!(l.summary.starts_with("ls is a program"), "{}", l.summary);
assert!(l.facts.iter().any(|(k, _)| k == "Architecture"));
assert!(!l.details.is_empty());
}
#[test]
fn sizes() {
assert_eq!(size_text(10), "10 bytes");
assert_eq!(size_text(2048), "2.0 KB (2048 bytes)");
}
}
+163
View File
@@ -0,0 +1,163 @@
//! The page: a welcome screen, drag and drop (and an Open button), then the answer.
use crate::triage::{Look, MAX_BYTES, look};
use craft_anything_evidence::Confidence;
use egui::{Color32, RichText};
use std::sync::{Arc, Mutex, PoisonError};
// A few tokens copied from the desktop app's Studio theme (crates/ui-egui/src/theme.rs).
const CANVAS: Color32 = Color32::from_rgb(0x0e, 0x0e, 0x0f);
const CARD: Color32 = Color32::from_rgb(0x1a, 0x1a, 0x1c);
const CARD_BORDER: Color32 = Color32::from_rgb(0x2a, 0x2a, 0x2e);
const TEXT: Color32 = Color32::from_rgb(0xec, 0xec, 0xf0);
const TEXT_DIM: Color32 = Color32::from_rgb(0xa9, 0xa9, 0xb2);
/// The app colour (getartcraft.com's deep accent), as in the desktop app.
const BRAND: Color32 = Color32::from_rgb(0x16, 0x59, 0xc4);
/// The app colour as text on the dark background (getartcraft.com's light accent).
const BRAND_INK: Color32 = Color32::from_rgb(0x74, 0xaa, 0xff);
const SEEN_IT: Color32 = Color32::from_rgb(0x3f, 0xb2, 0x7f);
const WORKED_OUT: Color32 = Color32::from_rgb(0x5b, 0x8d, 0xef);
const BEST_GUESS: Color32 = Color32::from_rgb(0xe0, 0xa2, 0x3a);
/// A file handed over from outside a frame (the browser's file picker).
/// A file (name and contents), or a plain message saying why it couldn't be read.
pub type Inbox = Arc<Mutex<Option<Result<(String, Vec<u8>), String>>>>;
pub struct Viewer {
look: Option<Look>,
error: Option<String>,
inbox: Inbox,
/// Opens the browser's file picker; its result arrives in `inbox`.
open: Box<dyn Fn()>,
/// Reads a dropped file (asynchronously in the browser); its contents arrive in `inbox`.
read_drop: Box<dyn Fn(egui::DroppedFileHandle)>,
}
impl Viewer {
pub fn new(inbox: Inbox, open: Box<dyn Fn()>, read_drop: Box<dyn Fn(egui::DroppedFileHandle)>) -> Self {
Viewer { look: None, error: None, inbox, open, read_drop }
}
pub fn setup(ctx: &egui::Context) {
let mut visuals = egui::Visuals::dark();
visuals.panel_fill = CANVAS;
visuals.window_fill = CARD;
visuals.override_text_color = Some(TEXT);
visuals.selection.bg_fill = BRAND;
visuals.hyperlink_color = BRAND_INK;
// The desktop app's Studio theme is dark; don't follow the system's light preference.
ctx.set_theme(egui::ThemePreference::Dark);
ctx.set_visuals_of(egui::Theme::Dark, visuals);
}
fn take(&mut self, name: String, bytes: &[u8]) {
if bytes.len() > MAX_BYTES {
self.error = Some(format!("{name} is larger than {} MB, which is more than the web viewer reads.", MAX_BYTES / (1024 * 1024)));
return;
}
self.error = None;
self.look = Some(look(&name, bytes));
}
pub fn ui(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
let dropped = ctx.input_mut(|i| std::mem::take(&mut i.raw.dropped_files));
if let Some(f) = dropped.into_iter().next() {
(self.read_drop)(f);
}
let picked = self.inbox.lock().unwrap_or_else(PoisonError::into_inner).take();
match picked {
Some(Ok((name, bytes))) => self.take(name, &bytes),
Some(Err(e)) => self.error = Some(e),
None => {}
}
let hovering = ctx.input(|i| !i.raw.hovered_files.is_empty());
egui::CentralPanel::default().show(ui, |ui| {
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
ui.set_max_width(ui.available_width().min(860.0));
ui.add_space(24.0);
ui.horizontal(|ui| {
ui.label(RichText::new("Craft Anything").size(26.0).strong());
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(RichText::new("Open a file…").size(15.0)).clicked() {
(self.open)();
}
});
});
ui.label(RichText::new("Drop a file to see what it is.").size(17.0).color(TEXT_DIM));
ui.add_space(16.0);
if hovering {
card(ui, |ui| {
ui.label(RichText::new("Let go to look at it").size(18.0).color(BRAND_INK));
});
} else if let Some(e) = &self.error {
card(ui, |ui| {
ui.label(RichText::new(e).color(BEST_GUESS));
});
} else if let Some(l) = &self.look {
show_look(ui, l);
} else {
card(ui, |ui| {
ui.label(
"Drop a program, app, library or any file here. Craft Anything tells you what it is, what it runs on and what it was made with.",
);
ui.add_space(6.0);
ui.label(RichText::new("Everything happens in this page: your file is never uploaded.").color(TEXT_DIM));
});
}
ui.add_space(16.0);
ui.label(
RichText::new(
"This is the small web version. The desktop app does much more: disassembly, functions and call graphs, \
JavaScript and Electron apps, Android, websites, devices, and an AI that explains what it finds.",
)
.color(TEXT_DIM),
);
ui.hyperlink_to("Get the desktop app", "https://github.com/storytold/craft-anything/releases/latest");
});
});
}
}
fn card(ui: &mut egui::Ui, add: impl FnOnce(&mut egui::Ui)) {
egui::Frame::new().fill(CARD).stroke(egui::Stroke::new(1.0, CARD_BORDER)).corner_radius(12.0).inner_margin(18.0).show(ui, |ui| {
ui.set_width(ui.available_width());
add(ui);
});
}
fn show_look(ui: &mut egui::Ui, l: &Look) {
card(ui, |ui| {
ui.label(RichText::new(&l.file_name).size(18.0).strong());
let (color, label) = match l.confidence {
Confidence::Observed => (SEEN_IT, "Seen it"),
Confidence::Derived => (WORKED_OUT, "Worked it out"),
Confidence::Inferred => (BEST_GUESS, "Best guess"),
};
ui.label(RichText::new(label).color(color).small());
ui.add_space(6.0);
ui.label(RichText::new(&l.summary).size(15.0));
ui.add_space(10.0);
egui::Grid::new("facts").num_columns(2).spacing([16.0, 6.0]).striped(true).show(ui, |ui| {
for (k, v) in &l.facts {
ui.label(RichText::new(k).color(TEXT_DIM));
ui.add(egui::Label::new(RichText::new(v).monospace()).wrap());
ui.end_row();
}
});
if !l.limitations.is_empty() {
ui.add_space(10.0);
ui.label(RichText::new("What this can't tell you").color(TEXT_DIM));
for m in &l.limitations {
ui.label(format!("• {m}"));
}
}
if !l.details.is_empty() {
ui.add_space(10.0);
egui::CollapsingHeader::new("All details (JSON)").show(ui, |ui| {
ui.add(egui::Label::new(RichText::new(&l.details).monospace().size(12.0)).wrap());
});
}
});
}
+98
View File
@@ -0,0 +1,98 @@
//! The browser shell: the eframe web runner and the file picker.
use crate::viewer::{Inbox, Viewer};
use wasm_bindgen::JsCast as _;
const CANVAS_ID: &str = "craft_anything_canvas";
const LOADING_ID: &str = "craft_anything_loading";
pub fn start() {
eframe::WebLogger::init(log::LevelFilter::Info).ok();
wasm_bindgen_futures::spawn_local(async {
let Some(document) = web_sys::window().and_then(|w| w.document()) else {
log::error!("no document");
return;
};
let Some(canvas) = document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
};
let mut options = eframe::WebOptions::default();
// `?webgl`: force the WebGL2 backend (troubleshooting, and headless browsers whose WebGPU
// adapter request returns nothing).
if query().contains("webgl")
&& let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
{
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
}
let result = eframe::WebRunner::new()
.start(
canvas,
options,
Box::new(|cc| {
if let Some(rs) = &cc.wgpu_render_state {
log::info!("craft-anything-web: wgpu backend {:?}", rs.adapter.get_info().backend);
}
Viewer::setup(&cc.egui_ctx);
let inbox = Inbox::default();
let open = open_picker(inbox.clone(), cc.egui_ctx.clone());
let read_drop = read_dropped(inbox.clone(), cc.egui_ctx.clone());
Ok(Box::new(Shell { viewer: Viewer::new(inbox, open, read_drop) }))
}),
)
.await;
if let Some(el) = document.get_element_by_id(LOADING_ID) {
match result {
Ok(()) => el.remove(),
Err(e) => el.set_inner_html(&format!("<p>Craft Anything failed to start: {e:?}</p><p>A browser with WebGPU or WebGL2 is required.</p>")),
}
}
});
}
/// The Open button: the browser's file picker, read into memory, then handed to the next frame.
fn open_picker(inbox: Inbox, ctx: egui::Context) -> Box<dyn Fn()> {
Box::new(move || {
let inbox = inbox.clone();
let ctx = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let Some(file) = rfd::AsyncFileDialog::new().pick_file().await else { return };
let bytes = file.read().await;
deliver(&inbox, &ctx, Ok((file.file_name(), bytes)));
});
})
}
/// A dropped file: browsers only read file contents asynchronously.
fn read_dropped(inbox: Inbox, ctx: egui::Context) -> Box<dyn Fn(egui::DroppedFileHandle)> {
Box::new(move |file| {
let inbox = inbox.clone();
let ctx = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
let name = file.path().file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_else(|| "the file".to_string());
let got = file.bytes_async().await.map(|b| (name.clone(), b)).map_err(|e| format!("The browser couldn't read {name}: {e}"));
deliver(&inbox, &ctx, got);
});
})
}
fn deliver(inbox: &Inbox, ctx: &egui::Context, got: Result<(String, Vec<u8>), String>) {
if let Ok(mut slot) = inbox.lock() {
*slot = Some(got);
}
ctx.request_repaint();
}
fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
struct Shell {
viewer: Viewer,
}
impl eframe::App for Shell {
fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
self.viewer.ui(ui);
}
}
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "craft-anything"
description = "Craft Anything: find out how any software works, then craft your own"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
build = "build.rs"
[lints]
workspace = true
[dependencies]
craft-anything-engine = { workspace = true }
craft-anything-ai = { workspace = true }
craft-anything-setup = { workspace = true }
craft-anything-ui-egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] }
log = { workspace = true }
[features]
wasm-plugins = ["craft-anything-engine/wasm-plugins"]
[build-dependencies]
# Icon + VERSIONINFO for craft-anything.exe; build.rs only uses it when targeting Windows.
winresource = "0.1"
+28
View File
@@ -0,0 +1,28 @@
//! Windows only: embed the app icon and version info (VERSIONINFO) into `craft-anything.exe`.
//!
//! On every other target this does nothing. A missing resource compiler is a warning, so a
//! cross-compile from macOS or Linux still links, unless `CRAFT_ANYTHING_REQUIRE_WINRES=1` (set by
//! the release workflow) turns it into an error.
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=../../assets/app-icon/craft-anything.ico");
println!("cargo:rerun-if-env-changed=CRAFT_ANYTHING_REQUIRE_WINRES");
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
return;
}
let mut res = winresource::WindowsResource::new();
res.set_icon("../../assets/app-icon/craft-anything.ico")
.set("ProductName", "Craft Anything")
.set("FileDescription", "Craft Anything: find out how any software works")
.set("LegalCopyright", "Copyright (c) the ArtCraft Team and the Craft Anything contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", "craft-anything.exe")
.set("InternalName", "craft-anything");
if let Err(e) = res.compile() {
if std::env::var_os("CRAFT_ANYTHING_REQUIRE_WINRES").is_some() {
println!("cargo:error=embedding Windows resources failed: {e}");
return;
}
println!("cargo:warning=craft-anything.exe built without icon/version resources: {e}");
}
}
+105
View File
@@ -0,0 +1,105 @@
//! The Craft Anything desktop app.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use craft_anything_ai::AiHub;
use craft_anything_engine::{Engine, Session, Settings};
use craft_anything_ui_egui::CraftApp;
use std::path::PathBuf;
use std::sync::Arc;
fn main() -> eframe::Result {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.iter().any(|a| a == "--version" || a == "-V") {
println!("craft-anything {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
// A path on the command line (or from "Open with…") opens as the first target.
let open: Option<PathBuf> = args.iter().find(|a| !a.starts_with('-')).map(PathBuf::from);
// The window app has no console: what goes wrong before (or instead of) a window is kept in
// desktop.log beside the settings, so a start that shows nothing leaves a trace.
log_to_file();
log::info!("starting {} (pid {})", env!("CARGO_PKG_VERSION"), std::process::id());
let settings = Settings::load();
let mut session = Session::new(settings);
let plugins = craft_anything_engine::plugins::install(&mut session);
let mut layer_tools = craft_anything_ai::tools();
layer_tools.extend(craft_anything_setup::tools::specs());
let engine = Engine::shared_with(session, layer_tools, plugins);
let hub = Arc::new(AiHub::new(engine.clone()));
log::info!("engine and AI ready; opening the window");
let mut viewport = eframe::egui::ViewportBuilder::default()
.with_title("Craft Anything")
.with_app_id("ai.storyteller.craft-anything")
.with_inner_size([1360.0, 860.0])
.with_min_inner_size([760.0, 520.0])
// Our own title bar draws the window controls, moves and resizes the window.
.with_decorations(false)
.with_resizable(true)
.with_drag_and_drop(true);
if let Ok(icon) = eframe::icon_data::from_png_bytes(craft_anything_ui_egui::APP_ICON_PNG) {
viewport = viewport.with_icon(Arc::new(icon));
}
let options = eframe::NativeOptions { viewport, ..Default::default() };
let run = eframe::run_native(
"Craft Anything",
options,
Box::new(move |cc| {
log::info!("window open");
CraftApp::setup_context(&cc.egui_ctx);
let mut app = CraftApp::new(engine, hub);
app.load_prefs(cc.storage);
if let Some(p) = open {
app.open_path(p);
}
Ok(Box::new(app))
}),
);
match &run {
Ok(()) => log::info!("closed"),
Err(e) => log::error!("the window couldn't start: {e}"),
}
run
}
/// Kept small: started afresh once it passes this size.
const LOG_MAX: u64 = 512 * 1024;
/// Warnings and errors from everything, plus our own progress, appended to `desktop.log`; and
/// panics, which would otherwise vanish with the window.
fn log_to_file() {
use std::io::Write as _;
struct FileLog(std::sync::Mutex<Option<std::fs::File>>);
impl log::Log for FileLog {
fn enabled(&self, m: &log::Metadata<'_>) -> bool {
m.level() <= log::Level::Warn || (m.level() <= log::Level::Info && m.target().starts_with("craft_anything"))
}
fn log(&self, r: &log::Record<'_>) {
if !self.enabled(r.metadata()) {
return;
}
let at = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
if let Ok(mut f) = self.0.lock()
&& let Some(f) = f.as_mut()
{
let _ = writeln!(f, "{at} [{}] {}: {}", r.level(), r.target(), r.args());
}
}
fn flush(&self) {}
}
let dir = craft_anything_engine::settings::config_dir();
let path = dir.join("desktop.log");
let _ = std::fs::create_dir_all(&dir);
let fresh = std::fs::metadata(&path).is_ok_and(|m| m.len() > LOG_MAX);
let file = std::fs::OpenOptions::new().create(true).append(!fresh).write(true).truncate(fresh).open(&path).ok();
if log::set_logger(Box::leak(Box::new(FileLog(std::sync::Mutex::new(file))))).is_ok() {
log::set_max_level(log::LevelFilter::Info);
}
let default_hook = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
log::error!("panic: {info}");
default_hook(info);
}));
}
+10
View File
@@ -0,0 +1,10 @@
Craft Anything app icon (craft-anything.svg and every file derived from it in this
directory: craft-anything-1024.png, craft-anything.icns, craft-anything.ico and
hicolor/).
This is the raven, the Crafting Apps' shared icon, made by the ArtCraft team. It is NOT covered
by Craft Anything's MIT OR Apache-2.0 license. It is used on the same terms as the ArtCraft
brand assets in docs/brand/LICENSE-brand.txt, which also say what forks and modified versions
must do: replace it with their own icon.
trace.py is a tool, covered by the repository's MIT OR Apache-2.0 license.
+37
View File
@@ -0,0 +1,37 @@
# Craft Anything app icon
The **raven**: the Crafting Apps' shared icon, made by the ArtCraft team. An engraved raven head
in getartcraft.com's ink `#101014` with paper `#f2f1ee` highlights, on a rounded tile in
ArtCraft's mark blue `#4e7bfb`. It is not open source: see `LICENSE.txt`.
The interface follows getartcraft.com too (`theme.rs`): its warm near-black and paper
backgrounds and ink, its deep accent `#1659c4` (`theme::BRAND`) for filled controls so white text
on them passes WCAG AA, its bright accent `#2d81ff` for hover and its light accent `#74aaff` for
blue text on dark surfaces. Headings and text are DM Sans.
## Geometry
A 512-unit tile with 110-unit corners (the source's 21.5 %), the raven clipped to it. The macOS
icons pad the tile onto Apple's 824/1024 icon grid; every other render uses the full tile.
## Files
- `craft-anything.svg`: the master SVG (also the hicolor scalable icon), about 100 KB.
- `craft-anything-1024.png`: 1024 px render of the tile.
- `craft-anything.icns`: macOS bundle icon.
- `craft-anything.ico`: Windows icon (16, 20, 24, 32, 40, 48, 64, 128, 256).
- `hicolor/<size>/apps/ai.storyteller.craft-anything.png` (16–512) and
`hicolor/scalable/apps/ai.storyteller.craft-anything.svg`: Linux icon theme.
- `trace.py`: traces the raven artwork (a 2000 px raster) into the SVG with vtracer.
- `packaging/icons.sh`: makes every other file above from the SVG. The app draws the SVG itself
at the exact pixel size (title bar, welcome screen); the window icon is the 256 px PNG.
## Regenerate
```sh
# From the 2000 px raven artwork (needs numpy, Pillow and vtracer; svgo 3.3.2 shrinks the paths):
python trace.py raven.webp master.svg 1000 6 0
npx svgo@3.3.2 -p 1 master.svg -o craft-anything.svg
# Every render (needs resvg on PATH; the .icns needs macOS's iconutil):
packaging/icons.sh
```
Binary file not shown.

After

Width:  |  Height:  |  Size: 224 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><clipPath id="a"><rect width="512" height="512" rx="110"/></clipPath><rect width="512" height="512" fill="#4e7bfb" rx="110"/><g fill-rule="evenodd" clip-path="url(#a)"><path fill="#f2f1ee" d="M234 52.2q5.1.4 10.1 2l2.8.7 1.5.5 5.7 1.6q9.8 2.6 19.1 6.3l3.3 1.3q5.8 2.1 11.2 5l1.7 1c14.7 7.7 14.7 7.7 17.8 9.8l1.7.2c4 1 7.2 5 9.9 7.8 1.2 1.2 1.2 1.2 2.5 1.7 1.8.8 2.5 2.2 3.5 3.9l.5.9c1.4 2.2 1.4 2.2 1.4 3.4h1l-1-3.6c.9.3.9.3 2 1q1.5 3.2 2 6.7l.9-.4 1.2-.1 1.4 1.2a12 12 0 0 0 5.6 2.6l1.2.3q17.2 4 34.6 6.5l4.3.7v1h-2v1l1.8-.3c2.2-.3 3.7.1 5.8.8l2.8.8 2.4.7v1H388v1.1h1c2.7.3 5.3.6 7.3 2.8 1.2 1 2.2 1.3 3.6 1.9l1.7.5 1.8.6c9.5 3.5 18.7 7.5 27 13.1l1 .7 8.9 6.1c9 6.4 17 14.8 22.4 24.5.2.1.2.1.7 1a49 49 0 0 1 6.6 24.6v1.4c0 2.4 0 4.5-1.1 6.8-1 .7-1 .7-2 1a40 40 0 0 1-7.3-7.6c-1-1.1-1-1.1-2.5-2.1-1.4 0-1.4 0-3.4.3a352 352 0 0 1-45 2.8H407q-14.4 0-28.6-.6v1c-2 .7-3.7.5-5.7.4l-1.1-.1c-2.8-.2-2.8-.2-4-.8v1l1.2.3a7 7 0 0 1 2.4.8v1l-4.2-1q-.7 0-1.3-.3l-1.2-.2-1-.3-2.5-.8v1l1.3.5q2.5.9 4.8 2.1v1q-5.8-1-11.3-3.5v1l1 .4 4.4 2.6.8.6v1q-3.3-1-6.3-2.9c-2.8-1.7-2.8-1.7-4.5-2.2l3.1 4.6c-1.8 0-2-.3-3.4-1.5-1.6-1.5-1.6-1.5-2.7-2.1 1.8 3 3.5 5.8 6.1 8.2v1c-2.3-.7-3.6-1.9-5.3-3.6l-1.4-1.4-1-1.1c.4 2 1.4 3.4 2.6 5.1h-1.6l-1.8-2.3c-1.6-2.3-1.6-2.3-2.8-2.8v7.1h-1l-.3-1.2q0-.8-.4-1.5l-.4-1.6c-.4-1.3-.4-1.3-1.4-1.8l-1.6 10.8h-1c-.6-1.9-.6-3.3-.6-5.3v-3.5q-3.5 3.4-4.2 8.2 0 6.5 1.2 12.8h-1a31 31 0 0 1-2-9.7h-1.6v-3h-1l-.7 3.8-.2 1.1q-.7 3.4-1.2 6.8h-1l-.5-9.2c-.8 2.7-1.2 4.4-1.2 7v2l-.1 2v2l-.2 5h-1l-1.6-8.3h-1l.5 18h-1l-1-4.5-.4-1.2a26 26 0 0 1-.7-7.2H315v1h-1l-.6 19.5h-1l-.7-4.5-.3-1.2-.2-1.3-.2-1.1-.1-3.1h-1l-.1 7v2.4a36 36 0 0 0 5 20l1.6 2.9.8 1.5 2.5 4.7.8 1.6 1.5 3q3.6 7.1 9.9 12.2l1.1.8 3.4 2.7 1.3 1q5.8 4.5 12 8.4a88 88 0 0 1 20.1 16q4.7 4.3 8.4 9.2 5.1 6.4 11 12c3.2 3.2 6 6.2 8.7 9.8l2 2.3q4.2 5.5 7.8 11.5l.8 1.4c1.1 1.8 1.8 3.3 2.1 5.4.5 2.5 1.6 4.1 3 6.2l1.3 2.1.7 1.2c8 12.5 13 25.8 16.9 40l.4 1.2.7 2.8c1.5 5.4 4 10.2 6.4 15.3 3.9 7.7 7.6 15.5 10.1 23.8q2 5.3 4.7 10.2l2 4.2.6 1.3c.4 1.1.4 1.1.4 3.2a119 119 0 0 1-62.2 17H115.6a109 109 0 0 1-92-47.8l-1-1.4A100 100 0 0 1 9 426.1l-.4-1.3c-3-12-2.9-24.5-3-36.9v-14.3q0-8.3-.2-16.5v-11.7l-.1-6.9v-8.9c-.2-5.8-.2-5.8 1.4-8q2.7-2.6 6-4.7l2.4-1.7 2-1.3 1-.8q2-1.4 4.1-2.5c1.9-1.2 3-3 4.2-4.8l.8-1.2C31.7 298 38.4 288 38.4 280l-.4.7-1.5 3.6-.6 1.2-.6 1.2-.4 1c-.6 1-.6 1-2.1 2q.5-4 2-7.7l.4-1.2 1.4-3.7 1.3-3.6 1-2.3 2-6.6-1.9 2.9-1.1 1.6-2.6 4.7h-1c.5-5.2 2.6-9.7 4.7-14.4l1-2.5-1 .5q.3-3 1.4-6.1l-.8 1.7-4.8 9.6h-1c2-10.2 7-19.4 11.6-28.5a108 108 0 0 0 5.8-14h-1l-.4 1.3a24 24 0 0 1-2.7 5l-1.2 1.6-.8 1.3c-.7-2-.3-2.4.6-4.2l.8-1.6.8-1.6 1.6-3.2.7-1.5q.7-1.5 1-3.3-.9 1.4-2 2.7c0 .3 0 .3-1 1.6l-2 2.9h-1C47 213 52 205.7 57 198.9q1.9-2.9 3.4-5.9l-.6.8-3.2 3.3-1 1.2-1 1.1-1 1c-.9.8-.9.8-1.9.8.8-3.1 2.6-5.4 4.4-8l1.9-2.6.8-1.2c.6-1 .6-1 .6-2.5a99 99 0 0 0-6.4 10l-.8 1.2h-1c1.9-6.5 5-12 9.2-17.4l1.2-1.6a184 184 0 0 1 8-9.8l3.1-4q-4.4 3.3-8.2 7.2L64 171c2.3-4.2 6.6-7.6 10-11q4-3.8 7.4-8.4-6.4 4.2-12.3 9.2l-1-1 2.6-3 .8-.7q2.5-2.8 5.2-5.4c.6-.7.6-.7.6-2.2l-1 .8q-3.7 3-7.7 5.8c0-3.2 3.6-6 5.7-8.3l4.8-5q3.2-3.6 7-7.1a29 29 0 0 0-6.7 4h-1c2-4.8 8.1-8 12.2-11.2L85 130a10 10 0 0 1 2.6-3.5c-2.8.7-4.5 1.9-6.7 3.5 0-1.5 0-1.5 1.1-2.7l1.6-1.4.9-.8q4-3.5 8.2-6.8l3.1-2.6 2.5-2q-3.3 1-6.2 2.8c-3 1.8-3 1.8-4 1.8.7-2.2 2.4-3.2 4.2-4.4l2-1.4 1-.7q2.3-1.4 4.4-3.2l.9-.6 12-8.7q-3.2.7-6.3 2.1l-1 .4-2.4 1.1v-1.5q1.4-1.2 3.2-2.2l1-.6q3-1.9 6-3.3c3.5-1.7 6.7-4 9.9-6l4.4-3 1.4-1 2.8-1.8H129c1.8-2.1 3.9-3.1 6.3-4.2l1.1-.7 2.9-1.3c-1.4 0-2.3.2-3.6.5.6-2 2-2.5 3.8-3.5l1-.5c10.2-5.2 10.2-5.2 14.6-5.2v-1l-4 .5v-1l5-1.6 1.3-.4 1.4-.4 1.3-.4c1.2-.3 1.2-.3 3.2-.3v-1l-5.6.5v-1q4.4-1.8 9.3-2.4l1.3-.3 4.2-.7 2.8-.4 10.7-1.8 1.3-.2 2.4-.3 2.8-.6.5-1h-4.6v-1c4.2-1.4 8.8-1.1 13.1-1.1h1.4q11.2.1 22.6 1.4l4 .4 2.4.3 1.2.1q2.3.2 4.5 1v-1.1l-1.5-.4-1.6-.6zm-171 130 .5 1.1.5-1zm305.6 13.4v1l3 .5 1.6.3q2 .3 4.1.2v-1c-3-.8-5.6-1.1-8.7-1"/><g fill="#101014"><path d="M234 52.2q5.1.4 10.1 2l2.8.7 1.5.5 5.7 1.6q9.8 2.6 19.1 6.3l3.3 1.3q5.8 2.1 11.2 5l1.7 1c14.7 7.7 14.7 7.7 17.8 9.8l1.7.2c4 1 7.2 5 9.9 7.8 1.2 1.2 1.2 1.2 2.5 1.7 1.8.8 2.5 2.2 3.5 3.9l.5.9c1.4 2.2 1.4 2.2 1.4 3.4h1l-1-3.6c.9.3.9.3 2 1q1.5 3.2 2 6.7l.9-.4 1.2-.1 1.4 1.2a12 12 0 0 0 5.6 2.6l1.2.3q17.2 4 34.6 6.5l4.3.7v1h-2v1l1.8-.3c2.2-.3 3.7.1 5.8.8l2.8.8 2.4.7v1H388v1.1h1c2.7.3 5.3.6 7.3 2.8 1.2 1 2.2 1.3 3.6 1.9l1.7.5 1.8.6c9.5 3.5 18.7 7.5 27 13.1l1 .7 8.9 6.1c9 6.4 17 14.8 22.4 24.5.2.1.2.1.7 1a49 49 0 0 1 6.6 24.6v1.4c0 2.4 0 4.5-1.1 6.8-1 .7-1 .7-2 1a40 40 0 0 1-7.3-7.6c-1-1.1-1-1.1-2.5-2.1-1.4 0-1.4 0-3.4.3a352 352 0 0 1-45 2.8H407q-14.4 0-28.6-.6v1c-2 .7-3.7.5-5.7.4l-1.1-.1c-2.8-.2-2.8-.2-4-.8v1l1.2.3a7 7 0 0 1 2.4.8v1l-4.2-1q-.7 0-1.3-.3l-1.2-.2-1-.3-2.5-.8v1l1.3.5q2.5.9 4.8 2.1v1q-5.8-1-11.3-3.5v1l1 .4 4.4 2.6.8.6v1q-3.3-1-6.3-2.9c-2.8-1.7-2.8-1.7-4.5-2.2l3.1 4.6c-1.8 0-2-.3-3.4-1.5-1.6-1.5-1.6-1.5-2.7-2.1 1.8 3 3.5 5.8 6.1 8.2v1c-2.3-.7-3.6-1.9-5.3-3.6l-1.4-1.4-1-1.1c.4 2 1.4 3.4 2.6 5.1h-1.6l-1.8-2.3c-1.6-2.3-1.6Line truncated

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 754 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 97 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><clipPath id="a"><rect width="512" height="512" rx="110"/></clipPath><rect width="512" height="512" fill="#4e7bfb" rx="110"/><g fill-rule="evenodd" clip-path="url(#a)"><path fill="#f2f1ee" d="M234 52.2q5.1.4 10.1 2l2.8.7 1.5.5 5.7 1.6q9.8 2.6 19.1 6.3l3.3 1.3q5.8 2.1 11.2 5l1.7 1c14.7 7.7 14.7 7.7 17.8 9.8l1.7.2c4 1 7.2 5 9.9 7.8 1.2 1.2 1.2 1.2 2.5 1.7 1.8.8 2.5 2.2 3.5 3.9l.5.9c1.4 2.2 1.4 2.2 1.4 3.4h1l-1-3.6c.9.3.9.3 2 1q1.5 3.2 2 6.7l.9-.4 1.2-.1 1.4 1.2a12 12 0 0 0 5.6 2.6l1.2.3q17.2 4 34.6 6.5l4.3.7v1h-2v1l1.8-.3c2.2-.3 3.7.1 5.8.8l2.8.8 2.4.7v1H388v1.1h1c2.7.3 5.3.6 7.3 2.8 1.2 1 2.2 1.3 3.6 1.9l1.7.5 1.8.6c9.5 3.5 18.7 7.5 27 13.1l1 .7 8.9 6.1c9 6.4 17 14.8 22.4 24.5.2.1.2.1.7 1a49 49 0 0 1 6.6 24.6v1.4c0 2.4 0 4.5-1.1 6.8-1 .7-1 .7-2 1a40 40 0 0 1-7.3-7.6c-1-1.1-1-1.1-2.5-2.1-1.4 0-1.4 0-3.4.3a352 352 0 0 1-45 2.8H407q-14.4 0-28.6-.6v1c-2 .7-3.7.5-5.7.4l-1.1-.1c-2.8-.2-2.8-.2-4-.8v1l1.2.3a7 7 0 0 1 2.4.8v1l-4.2-1q-.7 0-1.3-.3l-1.2-.2-1-.3-2.5-.8v1l1.3.5q2.5.9 4.8 2.1v1q-5.8-1-11.3-3.5v1l1 .4 4.4 2.6.8.6v1q-3.3-1-6.3-2.9c-2.8-1.7-2.8-1.7-4.5-2.2l3.1 4.6c-1.8 0-2-.3-3.4-1.5-1.6-1.5-1.6-1.5-2.7-2.1 1.8 3 3.5 5.8 6.1 8.2v1c-2.3-.7-3.6-1.9-5.3-3.6l-1.4-1.4-1-1.1c.4 2 1.4 3.4 2.6 5.1h-1.6l-1.8-2.3c-1.6-2.3-1.6-2.3-2.8-2.8v7.1h-1l-.3-1.2q0-.8-.4-1.5l-.4-1.6c-.4-1.3-.4-1.3-1.4-1.8l-1.6 10.8h-1c-.6-1.9-.6-3.3-.6-5.3v-3.5q-3.5 3.4-4.2 8.2 0 6.5 1.2 12.8h-1a31 31 0 0 1-2-9.7h-1.6v-3h-1l-.7 3.8-.2 1.1q-.7 3.4-1.2 6.8h-1l-.5-9.2c-.8 2.7-1.2 4.4-1.2 7v2l-.1 2v2l-.2 5h-1l-1.6-8.3h-1l.5 18h-1l-1-4.5-.4-1.2a26 26 0 0 1-.7-7.2H315v1h-1l-.6 19.5h-1l-.7-4.5-.3-1.2-.2-1.3-.2-1.1-.1-3.1h-1l-.1 7v2.4a36 36 0 0 0 5 20l1.6 2.9.8 1.5 2.5 4.7.8 1.6 1.5 3q3.6 7.1 9.9 12.2l1.1.8 3.4 2.7 1.3 1q5.8 4.5 12 8.4a88 88 0 0 1 20.1 16q4.7 4.3 8.4 9.2 5.1 6.4 11 12c3.2 3.2 6 6.2 8.7 9.8l2 2.3q4.2 5.5 7.8 11.5l.8 1.4c1.1 1.8 1.8 3.3 2.1 5.4.5 2.5 1.6 4.1 3 6.2l1.3 2.1.7 1.2c8 12.5 13 25.8 16.9 40l.4 1.2.7 2.8c1.5 5.4 4 10.2 6.4 15.3 3.9 7.7 7.6 15.5 10.1 23.8q2 5.3 4.7 10.2l2 4.2.6 1.3c.4 1.1.4 1.1.4 3.2a119 119 0 0 1-62.2 17H115.6a109 109 0 0 1-92-47.8l-1-1.4A100 100 0 0 1 9 426.1l-.4-1.3c-3-12-2.9-24.5-3-36.9v-14.3q0-8.3-.2-16.5v-11.7l-.1-6.9v-8.9c-.2-5.8-.2-5.8 1.4-8q2.7-2.6 6-4.7l2.4-1.7 2-1.3 1-.8q2-1.4 4.1-2.5c1.9-1.2 3-3 4.2-4.8l.8-1.2C31.7 298 38.4 288 38.4 280l-.4.7-1.5 3.6-.6 1.2-.6 1.2-.4 1c-.6 1-.6 1-2.1 2q.5-4 2-7.7l.4-1.2 1.4-3.7 1.3-3.6 1-2.3 2-6.6-1.9 2.9-1.1 1.6-2.6 4.7h-1c.5-5.2 2.6-9.7 4.7-14.4l1-2.5-1 .5q.3-3 1.4-6.1l-.8 1.7-4.8 9.6h-1c2-10.2 7-19.4 11.6-28.5a108 108 0 0 0 5.8-14h-1l-.4 1.3a24 24 0 0 1-2.7 5l-1.2 1.6-.8 1.3c-.7-2-.3-2.4.6-4.2l.8-1.6.8-1.6 1.6-3.2.7-1.5q.7-1.5 1-3.3-.9 1.4-2 2.7c0 .3 0 .3-1 1.6l-2 2.9h-1C47 213 52 205.7 57 198.9q1.9-2.9 3.4-5.9l-.6.8-3.2 3.3-1 1.2-1 1.1-1 1c-.9.8-.9.8-1.9.8.8-3.1 2.6-5.4 4.4-8l1.9-2.6.8-1.2c.6-1 .6-1 .6-2.5a99 99 0 0 0-6.4 10l-.8 1.2h-1c1.9-6.5 5-12 9.2-17.4l1.2-1.6a184 184 0 0 1 8-9.8l3.1-4q-4.4 3.3-8.2 7.2L64 171c2.3-4.2 6.6-7.6 10-11q4-3.8 7.4-8.4-6.4 4.2-12.3 9.2l-1-1 2.6-3 .8-.7q2.5-2.8 5.2-5.4c.6-.7.6-.7.6-2.2l-1 .8q-3.7 3-7.7 5.8c0-3.2 3.6-6 5.7-8.3l4.8-5q3.2-3.6 7-7.1a29 29 0 0 0-6.7 4h-1c2-4.8 8.1-8 12.2-11.2L85 130a10 10 0 0 1 2.6-3.5c-2.8.7-4.5 1.9-6.7 3.5 0-1.5 0-1.5 1.1-2.7l1.6-1.4.9-.8q4-3.5 8.2-6.8l3.1-2.6 2.5-2q-3.3 1-6.2 2.8c-3 1.8-3 1.8-4 1.8.7-2.2 2.4-3.2 4.2-4.4l2-1.4 1-.7q2.3-1.4 4.4-3.2l.9-.6 12-8.7q-3.2.7-6.3 2.1l-1 .4-2.4 1.1v-1.5q1.4-1.2 3.2-2.2l1-.6q3-1.9 6-3.3c3.5-1.7 6.7-4 9.9-6l4.4-3 1.4-1 2.8-1.8H129c1.8-2.1 3.9-3.1 6.3-4.2l1.1-.7 2.9-1.3c-1.4 0-2.3.2-3.6.5.6-2 2-2.5 3.8-3.5l1-.5c10.2-5.2 10.2-5.2 14.6-5.2v-1l-4 .5v-1l5-1.6 1.3-.4 1.4-.4 1.3-.4c1.2-.3 1.2-.3 3.2-.3v-1l-5.6.5v-1q4.4-1.8 9.3-2.4l1.3-.3 4.2-.7 2.8-.4 10.7-1.8 1.3-.2 2.4-.3 2.8-.6.5-1h-4.6v-1c4.2-1.4 8.8-1.1 13.1-1.1h1.4q11.2.1 22.6 1.4l4 .4 2.4.3 1.2.1q2.3.2 4.5 1v-1.1l-1.5-.4-1.6-.6zm-171 130 .5 1.1.5-1zm305.6 13.4v1l3 .5 1.6.3q2 .3 4.1.2v-1c-3-.8-5.6-1.1-8.7-1"/><g fill="#101014"><path d="M234 52.2q5.1.4 10.1 2l2.8.7 1.5.5 5.7 1.6q9.8 2.6 19.1 6.3l3.3 1.3q5.8 2.1 11.2 5l1.7 1c14.7 7.7 14.7 7.7 17.8 9.8l1.7.2c4 1 7.2 5 9.9 7.8 1.2 1.2 1.2 1.2 2.5 1.7 1.8.8 2.5 2.2 3.5 3.9l.5.9c1.4 2.2 1.4 2.2 1.4 3.4h1l-1-3.6c.9.3.9.3 2 1q1.5 3.2 2 6.7l.9-.4 1.2-.1 1.4 1.2a12 12 0 0 0 5.6 2.6l1.2.3q17.2 4 34.6 6.5l4.3.7v1h-2v1l1.8-.3c2.2-.3 3.7.1 5.8.8l2.8.8 2.4.7v1H388v1.1h1c2.7.3 5.3.6 7.3 2.8 1.2 1 2.2 1.3 3.6 1.9l1.7.5 1.8.6c9.5 3.5 18.7 7.5 27 13.1l1 .7 8.9 6.1c9 6.4 17 14.8 22.4 24.5.2.1.2.1.7 1a49 49 0 0 1 6.6 24.6v1.4c0 2.4 0 4.5-1.1 6.8-1 .7-1 .7-2 1a40 40 0 0 1-7.3-7.6c-1-1.1-1-1.1-2.5-2.1-1.4 0-1.4 0-3.4.3a352 352 0 0 1-45 2.8H407q-14.4 0-28.6-.6v1c-2 .7-3.7.5-5.7.4l-1.1-.1c-2.8-.2-2.8-.2-4-.8v1l1.2.3a7 7 0 0 1 2.4.8v1l-4.2-1q-.7 0-1.3-.3l-1.2-.2-1-.3-2.5-.8v1l1.3.5q2.5.9 4.8 2.1v1q-5.8-1-11.3-3.5v1l1 .4 4.4 2.6.8.6v1q-3.3-1-6.3-2.9c-2.8-1.7-2.8-1.7-4.5-2.2l3.1 4.6c-1.8 0-2-.3-3.4-1.5-1.6-1.5-1.6-1.5-2.7-2.1 1.8 3 3.5 5.8 6.1 8.2v1c-2.3-.7-3.6-1.9-5.3-3.6l-1.4-1.4-1-1.1c.4 2 1.4 3.4 2.6 5.1h-1.6l-1.8-2.3c-1.6-2.3-1.6Line truncated

After

Width:  |  Height:  |  Size: 96 KiB

+60
View File
@@ -0,0 +1,60 @@
"""Trace the raven artwork into the app icon's master SVG.
Needs numpy, Pillow and vtracer (`pip install vtracer`); see README.md for the exact runs.
usage: python trace.py SOURCE OUT_SVG WORK_PX SPECKLE BLUR
"""
import re
import sys
import tempfile
from pathlib import Path
import numpy as np
import vtracer
from PIL import Image, ImageFilter
INK, PAPER, BLUE = "#101014", "#f2f1ee", "#4e7bfb"
def trace(mask: np.ndarray, speckle: int, d: Path) -> str:
"""One colour layer: vtracer's binary trace of `mask`, as path elements."""
png, svg = d / "mask.png", d / "mask.svg"
Image.fromarray(np.where(mask, 0, 255).astype(np.uint8)).filter(ImageFilter.MedianFilter(3)).save(png)
vtracer.convert_image_to_svg_py(
str(png), str(svg), colormode="binary", mode="spline", filter_speckle=speckle,
corner_threshold=60, length_threshold=4.0, splice_threshold=45, path_precision=1,
)
found = re.findall(r'<path d="([^"]+)"[^>]*transform="translate\(([-\d.]+),([-\d.]+)\)"', svg.read_text())
return "".join(f'<path transform="translate({x} {y})" d="{p.strip()}"/>' for p, x, y in found)
def main() -> None:
src, out, n, speckle, blur = sys.argv[1], Path(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]), float(sys.argv[5])
im = Image.open(src).convert("RGB").resize((n, n), Image.LANCZOS)
if blur:
im = im.filter(ImageFilter.GaussianBlur(blur))
a = np.asarray(im).astype(np.int32)
r, g, b = a[..., 0], a[..., 1], a[..., 2]
blue = (b - r > 70) & (b > 150)
dark = 0.299 * r + 0.587 * g + 0.114 * b < 128
# Only what lies inside the source's rounded tile (21.5 % corner radius).
rad = 0.215 * n
yy, xx = np.mgrid[0:n, 0:n] + 0.5
inside = (xx - np.clip(xx, rad, n - rad)) ** 2 + (yy - np.clip(yy, rad, n - rad)) ** 2 <= (rad - 2) ** 2
with tempfile.TemporaryDirectory() as d:
bird = trace(inside & ~blue, speckle, Path(d))
ink = trace(inside & ~blue & dark, speckle, Path(d))
out.write_text(
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">'
'<clipPath id="t"><rect width="512" height="512" rx="110"/></clipPath>'
f'<rect width="512" height="512" rx="110" fill="{BLUE}"/>'
f'<g clip-path="url(#t)"><g transform="scale({512 / n:g})" fill-rule="evenodd">'
f'<g fill="{PAPER}">{bird}</g><g fill="{INK}">{ink}</g></g></g></svg>\n',
encoding="utf-8",
)
if __name__ == "__main__":
main()
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2014-2017 Indian Type Foundry (info@indiantypefoundry.com). Copyright 2019 Google LLC.
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2024 The Geist Project Authors (https://github.com/vercel/geist-font)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+93
View File
@@ -0,0 +1,93 @@
Copyright 2020 The JetBrains Mono Project Authors (https://github.com/JetBrains/JetBrainsMono)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+43
View File
@@ -0,0 +1,43 @@
ISC License
Copyright (c) 2026 Lucide Icons and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---
The following Lucide icons are derived from the Feather project:
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
The MIT License (MIT) (for the icons listed above)
Copyright (c) 2013-present Cole Bemis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+15
View File
@@ -0,0 +1,15 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-activity"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" />
</svg>

After

Width:  |  Height:  |  Size: 426 B

+18
View File
@@ -0,0 +1,18 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-app-window"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="2" y="4" width="20" height="16" rx="2" />
<path d="M10 4v4" />
<path d="M2 8h20" />
<path d="M6 4v4" />
</svg>

After

Width:  |  Height:  |  Size: 411 B

+20
View File
@@ -0,0 +1,20 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-binary"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect x="14" y="14" width="4" height="6" rx="2" />
<rect x="6" y="4" width="4" height="6" rx="2" />
<path d="M6 20h4" />
<path d="M14 10h4" />
<path d="M6 14h2v6" />
<path d="M14 4h2v6" />
</svg>

After

Width:  |  Height:  |  Size: 487 B

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-book-open"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 7v14" />
<path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
</svg>

After

Width:  |  Height:  |  Size: 459 B

+20
View File
@@ -0,0 +1,20 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-bot"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M12 8V4H8" />
<rect width="16" height="12" x="4" y="8" rx="2" />
<path d="M2 14h2" />
<path d="M20 14h2" />
<path d="M15 13v2" />
<path d="M9 13v2" />
</svg>

After

Width:  |  Height:  |  Size: 455 B

+26
View File
@@ -0,0 +1,26 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-boxes"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z" />
<path d="m7 16.5-4.74-2.85" />
<path d="m7 16.5 5-3" />
<path d="M7 16.5v5.17" />
<path d="M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z" />
<path d="m17 16.5-5-3" />
<path d="m17 16.5 4.74-2.85" />
<path d="M17 16.5v5.17" />
<path d="M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z" />
<path d="M12 8 7.26 5.15" />
<path d="m12 8 4.74-2.85" />
<path d="M12 13.5V8" />
</svg>

After

Width:  |  Height:  |  Size: 901 B

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-braces"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1" />
<path d="M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1" />
</svg>

After

Width:  |  Height:  |  Size: 458 B

+25
View File
@@ -0,0 +1,25 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-bug"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m8 2 1.88 1.88" />
<path d="M14.12 3.88 16 2" />
<path d="M9 7.13v-1a3.003 3.003 0 1 1 6 0v1" />
<path d="M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6" />
<path d="M12 20v-9" />
<path d="M6.53 9C4.6 8.8 3 7.1 3 5" />
<path d="M6 13H2" />
<path d="M3 21c0-2.1 1.7-3.9 3.8-4" />
<path d="M20.97 5c0 2.1-1.6 3.8-3.5 4" />
<path d="M22 13h-4" />
<path d="M17.2 17c2.1.1 3.8 1.9 3.8 4" />
</svg>

After

Width:  |  Height:  |  Size: 728 B

+19
View File
@@ -0,0 +1,19 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-cable"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M17 21v-2a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1" />
<path d="M19 15V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V9" />
<path d="M21 21v-2h-4" />
<path d="M3 5h4V3" />
<path d="M7 5a1 1 0 0 1 1 1v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1V3" />
</svg>

After

Width:  |  Height:  |  Size: 568 B

+15
View File
@@ -0,0 +1,15 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-check"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M20 6 9 17l-5-5" />
</svg>

After

Width:  |  Height:  |  Size: 316 B

+15
View File
@@ -0,0 +1,15 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-chevron-down"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m6 9 6 6 6-6" />
</svg>

After

Width:  |  Height:  |  Size: 320 B

+15
View File
@@ -0,0 +1,15 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-chevron-right"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m9 18 6-6-6-6" />
</svg>

After

Width:  |  Height:  |  Size: 322 B

+15
View File
@@ -0,0 +1,15 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-chevron-up"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="m18 15-6-6-6 6" />
</svg>

After

Width:  |  Height:  |  Size: 320 B

+17
View File
@@ -0,0 +1,17 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-circle-help"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
<path d="M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3" />
<path d="M12 17h.01" />
</svg>

After

Width:  |  Height:  |  Size: 405 B

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-circle-stop"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<circle cx="12" cy="12" r="10" />
<rect x="9" y="9" width="6" height="6" rx="1" />
</svg>

After

Width:  |  Height:  |  Size: 378 B

+20
View File
@@ -0,0 +1,20 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-clipboard-list"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="8" height="4" x="8" y="2" rx="1" ry="1" />
<path d="M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2" />
<path d="M12 11h4" />
<path d="M12 16h4" />
<path d="M8 11h.01" />
<path d="M8 16h.01" />
</svg>

After

Width:  |  Height:  |  Size: 538 B

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-code"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<polyline points="16 18 22 12 16 6" />
<polyline points="8 6 2 12 8 18" />
</svg>

After

Width:  |  Height:  |  Size: 363 B

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-copy"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="14" height="14" x="8" y="8" rx="2" ry="2" />
<path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2" />
</svg>

After

Width:  |  Height:  |  Size: 415 B

+24
View File
@@ -0,0 +1,24 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-cpu"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<rect width="16" height="16" x="4" y="4" rx="2" />
<rect width="6" height="6" x="9" y="9" rx="1" />
<path d="M15 2v2" />
<path d="M15 20v2" />
<path d="M2 15h2" />
<path d="M2 9h2" />
<path d="M20 15h2" />
<path d="M20 9h2" />
<path d="M9 2v2" />
<path d="M9 20v2" />
</svg>

After

Width:  |  Height:  |  Size: 571 B

+17
View File
@@ -0,0 +1,17 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-database"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<ellipse cx="12" cy="5" rx="9" ry="3" />
<path d="M3 5V19A9 3 0 0 0 21 19V5" />
<path d="M3 12A9 3 0 0 0 21 12" />
</svg>

After

Width:  |  Height:  |  Size: 409 B

+17
View File
@@ -0,0 +1,17 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-download"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
<polyline points="7 10 12 15 17 10" />
<line x1="12" x2="12" y1="15" y2="3" />
</svg>

After

Width:  |  Height:  |  Size: 428 B

+17
View File
@@ -0,0 +1,17 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-external-link"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M15 3h6v6" />
<path d="M10 14 21 3" />
<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" />
</svg>

After

Width:  |  Height:  |  Size: 417 B

+18
View File
@@ -0,0 +1,18 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-eye-off"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49" />
<path d="M14.084 14.158a3 3 0 0 1-4.242-4.242" />
<path d="M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143" />
<path d="m2 2 20 20" />
</svg>

After

Width:  |  Height:  |  Size: 583 B

+16
View File
@@ -0,0 +1,16 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-eye"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0" />
<circle cx="12" cy="12" r="3" />
</svg>

After

Width:  |  Height:  |  Size: 435 B

+18
View File
@@ -0,0 +1,18 @@
<!-- @license lucide-static v0.469.0 - ISC -->
<svg
class="lucide lucide-file-code"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M10 12.5 8 15l2 2.5" />
<path d="m14 12.5 2 2.5-2 2.5" />
<path d="M14 2v4a2 2 0 0 0 2 2h4" />
<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z" />
</svg>

After

Width:  |  Height:  |  Size: 473 B

Loaded 100 of 597 files, more files were not shown because too many files have changed in this diff. Show more