# Overview
Source: https://docs.truffle.net/client/overview
Symphony
Symphony is available for Windows, macOS (Intel and Apple Silicon), and Linux. Download the version for your operating system below.
## Download
> [card] [Apple Intel](https://truffle.net/client/download/mac-x64)
> [card] [Apple Silicon](https://truffle.net/client/download/mac-arm64)
> [card] [Windows](https://truffle.net/client/download/win)
> [card] [Linux](https://truffle.net/client/download/linux)
> [!NOTE]
>
> Need help? Check out our [Discord](https://discord.gg/itsalltruffles) or reach out to [support@deepshard.org](mailto:support@deepshard.org) for questions.
# General
Source: https://docs.truffle.net/faqs/general
Frequently asked questions
> [!NOTE]
>
> FAQs coming soon.
# Overview
Source: https://docs.truffle.net/hardware/overview
Truffle¹ hardware
> [!NOTE]
>
> Documentation for Truffle¹ hardware is coming soon.
# Release notes
Source: https://docs.truffle.net/release-notes/index
Weekly Truffle releases!
> [accordion] November 14, 2026
>
> Latest release
>
> Truffle
>
> ### Desktop notifications and more apps!
>
>
>
>
>
**Desktop notifications.** Your Truffle can now reach you anywhere on your Mac. Turn on desktop notifications in Symphony under Settings → Account.
>
**More apps.** Use Claude, ChatGPT, Robinhood, WhatsApp, Discord, and more with your Truffle.
>
> [accordion] November 5, 2026
>
> Previous release
>
> Truffle
>
> ### A new Context map, interactive cards, Browser Use, and dreams.
>
>
>
>
>
**A new iteration of Context map.** View and search across everything your Truffle knows about you. This still isn’t the final version, so please share your feedback.
>
**Interactive cards on Home.** Control your music, track an Uber order, and interact with apps directly from your Home screen.
>
**Your Truffle can now use the browser.** Browser Use gives your Truffle access to a cloud browser while credentials for sites you sign into remain stored locally on your Truffle.
>
**More apps.** Uber, Uber Eats, Amazon, Erewhon, and more are now available in Truffle.
>
**Your Truffle can now dream.** Head to Settings to choose your preferred dream duration.
>
> [accordion] October 23, 2026
>
> Previous release
>
> Symphony
>
> ### Talk to your cards, and explore your world with Context map.
>
>
>
>
>
**Talk to your cards on Home.** Every card now has its own Ask Truffle bar, so you can reply, follow up, or ask Truffle to take action without opening a new chat.
>
**Introducing Context map.** Explore the people, projects, meetings, and notes Truffle knows about. Switch between All time and Now, hover over anything for more context, or ask the map questions like “What project was I working on last week?”
>
**Eleven new apps.** Granola, Figma, Mercury, Kalshi, X, PhotoCraft, LightCraft, SoundCraft, Spotify, Apple Music, and Calendly are now available in Truffle.
>
>
> Head to Home or Context map in Symphony, or paste this prompt to your Truffle:
>
> ```text theme={null}
> hey, looks like i can talk to my cards on Home now and there's a new Context map. give me a quick rundown of both, and show me the new apps i can connect
> ```
> [accordion] September 28, 2026
>
> Previous release
>
> Radiance
>
> ### Radiance, now redesigned on iOS.
>
>
>
>
>
A new Onboarding, plus a redesigned Convo and Settings.
>
Dictation, now on iOS: tap or hold to talk to your Truffle.
>
Introducing Side chats: branch off any message without losing your place.
>
Home Screen widgets.
>
>
> Update Radiance through TestFlight to get the new version.
> [accordion] September 23, 2026
>
> Previous release
>
> Symphony
>
> ### Symphony, redesigned.
>
>
>
>
>
A new onboarding, a new Home screen, and a revamped Convo.
>
Dictate to your Truffle directly from Symphony.
>
Your Truffle can now sit in on your meetings, both online and in person.
>
A new Settings UI, with a lot more configuration, like audio controls.
>
> [accordion] August 29, 2026
>
> Previous release
>
> Symphony
>
> ### Multiple app accounts and tool permissions are here.
>
> You can now connect multiple accounts to your apps in Truffle. Bring in multiple Slack workspaces and connect both your personal and work Gmail accounts.
>
> Tool permissions are finally here! Permissions are scoped to each account and default to read-only. Set permissions for each app connection, or choose a global permission: **Read only**, **Read and write**, or **Auto review**.
>
> Head to your app settings in Symphony, or paste the following prompt to your Truffle:
>
> ```text theme={null}
> hey seems like you can now connect to multiple accounts and there are tool permissions. Please give me a rundown of how these two features work!
> ```
> [accordion] August 17, 2026
>
> Previous release
>
> Symphony
>
> ### Quick actions are now available from the Symphony system tray.
>
>
>
Open Conductor, Convo, or the full Symphony app from the system tray.
>
Create a schedule or memory without opening the full Symphony window.
>
Manage remote access and LEDs, disconnect your Truffle, or quit Symphony from one place.
>
>
> 
>
> Apps
>
> ### Apps now stay up to date automatically, with two new additions.
>
>
>
Apps update automatically, so you always have the latest available version.
>
Your Truffle lets you know when an app requires you to sign in.
>
Ask your Truffle to install or delete apps available on the App Store.
>
>
> 
>
> #### Higgsfield
>
> Create AI-powered images and videos with your Truffle.
>
> 
>
> #### Pinterest
>
> Find ideas, inspiration, and visual references with your Truffle.
> [accordion] August 10, 2026
>
> Previous release
>
> Truffile / SDK
>
> ### Convo replaces the legacy Chat and Task-backed CLI.
>
>
>
`truffile convo` replaces `truffile chat` and uses only the authenticated user's Convo backend.
>
The cutover is one-way: old Task histories are not migrated or listed.
>
Bare launches begin in an unsent side-thread draft. Main is thread `0` and requires explicit selection with `/main` or `--main`.
>
Use `/new`, `/threads`, and `/rename` to create, switch, and name threads.
>
`/hide` and `/restore` manage reversible device/user-scoped local visibility. Hiding is not server deletion.
>
One-shot mode now supports targeting, actions, machine-readable JSON, and opt-in settlement timeouts.
>
Interactive `/apps` and per-chat app selection were removed. Installed-app listing is discovery only, and Convo cannot attach or restrict an app to a thread.
>
Temporary Task compatibility spellings such as `--task-id`, `--list-tasks`, `/tasks`, and the `task_id` JSON key carry only decimal Convo thread IDs.
>
> [accordion] August 1, 2026
>
> Previous release
>
> Truffle
>
> ### Truffle is more proactive, faster, and easier to personalize.
>
>
>
Truffle takes more initiative, helping you stay ahead of tasks with less prompting.
>
Scheduled tasks are now more reliable, with fixes for issues that prevented them from running correctly.
>
New reminder tools make it easier for Truffle to remember and follow up on important things.
>
Faster performance makes conversations and everyday actions feel more responsive.
>
Ask Truffle to install apps directly from Convo. Every app except VNC can be installed this way on both Symphony and Radiance.
>
A more personalized onboarding experience helps Truffle get to know you naturally as you use it.
>
App installation can trigger background research, giving Truffle richer context for future interactions.
>
>
> Radiance
>
> ### Radiance brings app installation and Truffle widgets to iOS.
>
>
>
Install apps directly from Radiance on iOS.
>
Add Truffle as a widget on your iPhone Home Screen or Lock Screen for quicker access.
>
> [accordion] July 28, 2026
>
> Previous release
>
> Symphony
>
> ### Configure your Truffle with Symphony.
>
>
>
> You can now:
>
>
>
View and edit **User profile** memory, a special category your Truffle weighs heavily when understanding who you are.
>
Search memories, filter by tags, and autocomplete tags when creating or editing memories.
>
View and edit **Custom instructions** in Settings, giving you a persistent way to guide how your Truffle responds.
>
>
>
>
Increased response streaming speed in Convo.
>
Paste files from your clipboard directly into the prompt bar.
>
Prompt bar drafts persist as you navigate between screens.
>
Convo search clearly highlights matching text.
>
Improved rendering performance for file and link previews in Convo.
>
Unified the new-account username and password flow with the existing login experience.
>
General UI polish and bug fixes.
>
> [accordion] July 11, 2026
>
> Previous release
>
> Radiance
>
> ### Radiance has a new look and smoother everyday workflows.
>
>
>
Refreshed visual style throughout the app, including a new background and updated interface.
>
Cleaner message bar with refreshed voice input.
>
Quick menu above the message bar for Search, Schedules, and Settings, with a subtle hint to help you find it.
>
Paste copied images or files straight into the message bar.
>
Conversation view redesign with cleaner messages, threads, timestamps, replies, and attachments shown under your messages.
>
Search redesign for finding things in your conversations faster.
>
Schedules redesign for browsing, sorting/filtering, and creating or editing automations.
>
Settings redesign across device, account, apps, and recovery code screens.
>
Launches straight into your conversation instead of a loading screen.
>
More polish across quoted replies, link previews, and keyboard behavior.
>
>
> Symphony
>
> ### Symphony is smaller, faster, and streams responses.
>
>
>
Reduced application size from a large internal refactor.
>
Convo response streaming.
>
Minor bug fixes and polish.
>
> [accordion] July 4, 2026
>
> Previous release
>
> Apps and SDK
>
> ### Two new apps are available this week.
>
> 
>
> #### Alpha Vantage
>
> Ask your Truffle for market data, symbol search, quotes, historical prices, company fundamentals, market news, movers, and economic indicators.
>
> 
>
> #### Internet Archives
>
> Search public archives, old web snapshots, open books, readable text, and public-domain reading packs from Internet Archive, Wayback Machine, Open Library, and Project Gutenberg.
> [accordion] June 26, 2026
>
> Previous release
>
> Symphony
>
> ### Stability and app installation improvements.
>
>
>
Device and Wi-Fi connection stability improvements. No infinite loading spinners.
>
Remote access stability improvements.
>
App installation UX improvements. OAuth is smoother to onboard now.
>
App install VNC window bug fix. VNC now works as normal when Symphony is in full screen mode.
>
>
> Apps and SDK
>
> ### Three new apps are available this week.
>
> 
>
> #### Daily News
>
> Get daily news every day at 9am. Ask your Truffle to use the app and set your interests first so you get curated news.
>
> 
>
> #### X
>
> Have your Truffle browse X for you and surface posts that you would find interesting.
>
> 
>
> #### Firecrawl
>
> Use Firecrawl with your Truffle for cleaner web extraction and app workflows.
>
> You can now reset Convo and clear stale users with Truffile:
>
> ```bash theme={null}
> # soft reset: restart Convo while keeping history
> truffile convo reset
>
> # hard reset: clear persisted Convo state
> truffile convo reset --hard
>
> # delete old users and keep your current primary account
> truffile users clear-other
> ```
>
> Truffle
>
> ### Control your LEDs with your Truffle.
>
> Prompts to try:
>
> ```text theme={null}
> hey Truffle can you set a scheduled task to keep your LEDs dimmed every night from 8 pm to 6 am!
> ```
>
> ```text theme={null}
> read the LED skill then overhaul every single action + state, remember that you're the representation of convo. I would like you to change the whole LED theme to follow a Tron-like vibe!
> ```
>
> ### RunToolScript
>
> Your Truffle can write its own tools and save them for doing your favorite workflows.
>
> ```text theme={null}
> Build me a tool that shows today's FIFA World Cup 2026 match schedule — the teams playing, times, and stadiums. Use WebSearch or any reliable web source to fetch the data.
> ```
>
> ```text theme={null}
> hey Truffle make a tool where every time there's a GitHub PR assigned to me I want you to message me in my personal DM on Slack
> ```
>
> ```text theme={null}
> make a tool that goes through my weekly emails and puts all marketing and spam emails that are not important to me in a separate folder that I can manually delete later. Don't delete them, just sort them for me to review.
> ```
> [accordion] May 11, 2026
>
> Previous release
>
> Symphony
>
> ### Queue and steer!
>
>
>
You can now queue messages and steer the model mid-conversation.
>
Bug fixes including: Check for Update, toggling LED off and on, app installation!
>
You can now set up a password and use that as your primary method of signing in, with recovery codes as a fallback.
>
>
> Truffle
>
> ### Improved agent on your Truffle!
>
>
>
Improved memory with an embeddings model running locally on your Truffle.
>
A good time to have a chat with your Truffle and get it to know you.
>
Larger context window! Truffle now has a much larger context window, so long-running tasks should feel much better.
>
> [accordion] April 26, 2026
>
> Previous release
>
> Apps
>
> ### Have your Truffle connect to new apps this week!
>
> 
> [accordion] April 19, 2026
>
> Previous release
>
> Truffle
>
> 
>
> ### now runs on your Truffle!
>
>
>
> Apps and SDK
>
> ### Introducing Obsidian:
>
>
>
> Read more on using the truffile sdk [here](/sdk/installation).
>
> Note: once installed to your Truffle using the CLI, you can use it with Truffile and Symphony!
>
> ### Upload images and use vision on Truffle!
>
>
>
> Coming next week
>
> ### What's coming next week!
>
>
>
> Radiance on iOS:
>
>
>
>
>
Complete revamp of Memory and the agent running on your Truffle.
>
Truffle being able to make its own apps and install them for itself.
>
App skills!
>
File upload so you can send your Truffle documents to process.
>
# Accounts and authentication
Source: https://docs.truffle.net/sdk/accounts
Build apps with separate accounts, connection-scoped credentials, OAuth, and remote MCP connectors
An installed app has one bundle identity and one or more account connections.
Shared code is installed once. Credentials, account identity, and permission
choices belong to each connection.
## Choose the authentication flow
| Flow | Installer setup | CLI interaction |
| - | - | - |
| Public service | Files/dependencies and optional welcome step | Continue when prompted |
| API key, token, or configuration form | `text` step with `scope: connection` | Enter fields; password fields are hidden |
| Browser OAuth | Connection-scoped `oauth` step | Open the authorization URL and complete the callback/code prompt |
| Remote MCP OAuth | Native connector plus connection-scoped OAuth | Same browser flow; firmware handles discovery, registration, and token storage |
| Device-code approval | Provider-specific native setup plan | Open the approval link; CLI waits for completion |
| Browser/VNC setup | Provider-specific native setup plan | Open the device setup URL and complete the displayed steps |
The CLI drives the setup plan supplied by firmware. Provider endpoints, client
registration, scopes, and callback URLs must match the provider's requirements.
Supporting a setup card does not establish that every provider works with it.
## Separate installation from account setup
For a process-based app, use `truffile_version: 4` and `connections: multi` when
multiple accounts are supported. Install-scoped steps prepare shared code;
connection-scoped steps collect or validate credentials for the first account,
additional accounts, and reconnections.
```yaml theme={null}
truffile_version: 4
connections: multi
# Include your metadata and foreground/background process configuration.
steps:
- name: Copy code
type: files
scope: install
files:
- source: service.py
destination: ./service.py
- name: Connect account
type: text
scope: connection
fields:
- name: api_key
label: API key
type: password
env: SERVICE_API_KEY
```
This is a setup fragment, not a complete app. Add a provider validation step
before reporting the account as connected. The selected connection's runtime
receives its own `SERVICE_API_KEY`; do not embed secrets in the manifest or
shared app files. For custom Python apps, expose provider-confirmed identity
through `truffle://user-info` so account labels are meaningful.
## A remote MCP connector with OAuth
A native connector uses `truffile_version: 5` and
`metadata.foreground.connector`. Firmware connects to the upstream MCP server;
you do not need to write a Python proxy for this example.
Create a directory containing `icon.png` and this `truffile.yaml`. Use your own
unique bundle ID if you adapt the example for distribution.
```yaml theme={null}
truffile_version: 5
connections: multi
metadata:
name: Todoist Tutorial
bundle_id: org.example.todoist.tutorial
description: Connect Todoist accounts through its remote MCP service.
icon_file: icon.png
foreground:
connector:
upstream_url: https://ai.todoist.net/mcp
transport:
request_timeout_seconds: 45
max_read_retries: 1
retry_delay_seconds: 1
auth:
mode: oauth
app_var_key: todoist_oauth_state
token_endpoint: https://todoist.com/oauth/access_token
resource: https://ai.todoist.net/mcp
overlay: {}
identity:
sources:
- tool: user-info
map:
provider_subject: userId
email: email
display_name: fullName
steps:
- name: Sign in to Todoist
type: oauth
scope: connection
provider: remote_mcp
description: Authorize Todoist, then return to the terminal.
redirect_uri: http://localhost:18791/callback
scopes:
- data:read_write
dynamic_client_registration: true
resource_metadata_endpoint: https://ai.todoist.net/.well-known/oauth-protected-resource/mcp
authorization_server_metadata_endpoint: https://todoist.com/.well-known/oauth-authorization-server
registration_endpoint: https://todoist.com/oauth/register
oauth_resource: https://ai.todoist.net/mcp
client_name: Todoist Tutorial
auth_endpoint: https://todoist.com/oauth/authorize
token_endpoint: https://todoist.com/oauth/access_token
token_endpoint_auth_method: none
client_id_env: TODOIST_CLIENT_ID
client_secret_env: null
app_var_key: todoist_oauth_state
prompt: null
access_type: null
include_granted_scopes: false
alias_from:
- identity.email
- identity.display_name
```
This follows the Todoist flow verified with two separate accounts. The
connector and OAuth step use the same `app_var_key`, which identifies
connection-scoped token state. The `identity` mapping reads Todoist's
`user-info` tool; other providers need their own verified identity mapping.
```bash theme={null}
truffile validate ./todoist-tutorial
truffile deploy ./todoist-tutorial
truffile connections add "Todoist Tutorial"
truffile connections list "Todoist Tutorial" --json
truffile connections permissions "Todoist Tutorial" read-only
```
The permissions command prompts for the account. Repeat it for each account
you want to restrict. The provider's OAuth scopes and Truffle's account
permissions are separate: granting a provider scope does not override Truffle's
permission settings.
## OAuth callbacks and credentials
If the browser runs on the same computer as the CLI, the local callback
listener can receive a registered localhost redirect. If you open the browser
on another computer, copy its final localhost callback URL into the waiting
CLI prompt, even if that browser cannot load the callback page. The CLI
validates the state against the pending request.
Use the current sign-in link. Firmware may expire a setup after 15 minutes;
a longer CLI timeout does not extend that window. Start a fresh setup after
expiry. Never reuse a previous callback for another account.
Firmware exchanges and stores native OAuth credentials. Custom Python apps
should use the matching runtime credential helpers; connection-scoped tokens
must not be copied into app-global variables or source files. Native connectors
handle credential use and refresh through firmware.
## Account lifecycle and permissions
```bash theme={null}
truffile connections reconnect "Todoist Tutorial"
truffile connections rename "Todoist Tutorial" Work
truffile connections permissions "Todoist Tutorial" Work auto-review --notes "Review external writes"
truffile connections delete "Todoist Tutorial" Work
truffile deploy ./todoist-tutorial --update
```
Friendly app names, bundle IDs, and app UUIDs work. An omitted account opens a
picker. In the rename example, choose an account and name it `Work`. To avoid
prompting, supply an exact account alias or connection UUID; deletion also
requires `--yes` in scripts.
New accounts use device policy unless an account override exists. Set an
override with `read-only`, `read-write`, or `auto-review`; `default` removes the
override and inherits device policy. The CLI does not change device-wide
defaults or offer an atomic install-and-set-permissions option. Tool annotations
such as `readOnlyHint` describe tool behavior; they are not permission grants.
An uploaded `--update` preserves installed accounts and their settings.
`--replace` intentionally resets accounts after confirmation. Test both accounts
after an update and verify that reconnecting one leaves the other intact.
See [deployment and account commands](/sdk/deployment) for cancellation,
noninteractive forms, packaging rules, and firmware requirements.
# Build a Background App
Source: https://docs.truffle.net/sdk/ambient-app
Run on a schedule and submit context to the proactive agent on your Truffle
Background apps run on a schedule and feed **context** into Truffle's proactive agent. Foreground apps are callable tools; background apps are context producers.
You subclass `BackgroundWorkerApp`, implement a handful of methods, and call `app.main()`. The runtime handles the schedule, retries, and the gRPC plumbing.
> The richer and more concrete your submissions are, the better proactive behavior you'll get. "FED-RATE-SEP moved up 12c (was 41c, now 53c)" routes much better than "market alert".
***
## Background patterns in the examples
The bundled examples use background apps in a few distinct ways:
| Example | Shape | What the background does |
| - | - | - |
| `arxiv` | Hybrid | Uses text-configured research interests to find relevant papers and submit recommendation context. |
| `notion` | Hybrid | Uses remote MCP OAuth state to scan workspace changes and submit digest context. |
| `viator` | Hybrid | Runs without auth and submits travel/location context around Viator search tools. |
| `whoop` | Hybrid | Shares OAuth token helpers with the foreground and submits health/recovery summaries. |
The common pattern is: keep API/auth clients in shared modules, keep polling/diffing logic in a plain worker, and keep runtime submission logic in the `BackgroundWorkerApp` subclass.
***
## The worker + app split
Reference apps consistently keep the *work* (API calls, parsing, diffing) in a plain `Worker` class, and the *SDK wiring* in a small `BackgroundWorkerApp` subclass. This makes the worker easy to unit test without touching the runtime.
```
my_app/
├── bg_worker.py # plain class: verify(), run_cycle() → CycleResult
├── my_app_background.py # BackgroundWorkerApp subclass + app.main()
└── truffile.yaml
```
***
## Minimal example
### The worker (`bg_worker.py`)
The worker knows nothing about the SDK. It returns a `CycleResult` dataclass describing what happened.
```python theme={null}
# bg_worker.py
from __future__ import annotations
import os
from dataclasses import dataclass, field
import httpx
@dataclass(frozen=True)
class CycleResult:
summary: str | None = None
uris: tuple[str, ...] = ()
priority: int = 0
changed: bool = False
auth_error: str | None = None
error: str | None = None
class MyBackgroundWorker:
def __init__(self) -> None:
self._http = httpx.Client(timeout=30.0)
self._last_fingerprint: str | None = None
def close(self) -> None:
try:
self._http.close()
except Exception:
pass
def verify(self) -> tuple[bool, str]:
"""Called by `truffile deploy` (and `--verify`) to check credentials."""
token = os.getenv("MY_APP_ACCESS_TOKEN", "").strip()
if not token:
return False, "MY_APP_ACCESS_TOKEN is not set"
try:
response = self._http.get(
"https://api.example.com/me",
headers={"Authorization": f"Bearer {token}"},
)
if response.status_code in (401, 403):
return False, "MY_APP_ACCESS_TOKEN is invalid or expired"
response.raise_for_status()
user = response.json().get("login", "unknown")
return True, f"Verified as @{user}"
except Exception as exc:
return False, f"Verify request failed: {exc}"
def run_cycle(self) -> CycleResult:
token = os.getenv("MY_APP_ACCESS_TOKEN", "").strip()
if not token:
return CycleResult(auth_error="MY_APP_ACCESS_TOKEN is not set")
try:
response = self._http.get(
"https://api.example.com/activity",
headers={"Authorization": f"Bearer {token}"},
)
if response.status_code in (401, 403):
return CycleResult(auth_error=f"API returned {response.status_code}")
response.raise_for_status()
items = response.json().get("items", [])
except Exception as exc:
return CycleResult(error=str(exc))
# Skip if nothing has changed since the last cycle.
fingerprint = repr(items)
if fingerprint == self._last_fingerprint:
return CycleResult(changed=False)
self._last_fingerprint = fingerprint
if not items:
return CycleResult(changed=False)
summary = "\n".join(f"- {item['title']} ({item['url']})" for item in items[:5])
uris = tuple(item["url"] for item in items[:5])
return CycleResult(summary=summary, uris=uris, priority=1, changed=True)
```
### The app (`my_app_background.py`)
```python theme={null}
# my_app_background.py
from __future__ import annotations
import atexit
from truffile.app_runtime import BackgroundWorkerApp
from bg_worker import CycleResult, MyBackgroundWorker
class MyBackgroundApp(BackgroundWorkerApp[MyBackgroundWorker, CycleResult]):
def __init__(self) -> None:
super().__init__("myapp", logger_name="myapp.background")
def build_worker(self) -> MyBackgroundWorker:
return MyBackgroundWorker()
def verify_worker(self, worker: MyBackgroundWorker) -> tuple[bool, str]:
return worker.verify()
def run_cycle(self, worker: MyBackgroundWorker) -> CycleResult:
return worker.run_cycle()
def handle_cycle_result(self, ctx, result: CycleResult) -> None:
if result.auth_error:
self.report_auth_failure(ctx, result.auth_error)
return
self.reset_auth_failures()
if result.error:
self.logger.error("Cycle failed: %s", result.error)
return
if not result.changed or not result.summary:
return
self.submit_text(
ctx,
content=result.summary,
uris=result.uris,
priority=result.priority,
)
app = MyBackgroundApp()
def _cleanup() -> None:
worker = getattr(app, "_worker", None)
if worker is not None:
close = getattr(worker, "close", None)
if callable(close):
try:
close()
except Exception:
pass
atexit.register(_cleanup)
if __name__ == "__main__":
app.main()
```
That's the whole pattern. Everything below explains each method.
***
## The `BackgroundWorkerApp` base class
Subclass `BackgroundWorkerApp[WorkerT, ResultT]` with the two types of your worker and your cycle result. Call `super().__init__(name, logger_name=...)`.
You implement four methods:
| Method | What it does |
| - | - |
| `build_worker()` | Returns an instance of your worker. Called once and cached. |
| `verify_worker(worker)` | Returns `(ok, message)` — used during deploy and `--verify`. |
| `run_cycle(worker)` | Runs one iteration. Returns your cycle result. |
| `handle_cycle_result(ctx, result)` | Inspects the result and decides whether to submit context or report an error. |
And you get these helpers for free:
| Helper | What it does |
| - | - |
| `self.submit_text(ctx, content=..., uris=..., priority=...)` | Queue text context for the proactive agent. |
| `self.report_auth_failure(ctx, description)` | Dedup auth failures; after `AUTH_FAILURE_THRESHOLD` (default 3) consecutive failures, reports to the runtime with `needs_intervention=True`. |
| `self.reset_auth_failures()` | Clear the counter after a successful cycle. |
| `self.logger` | A pre-configured logger. |
***
## `app.main()` and `--verify`
`app.main()` is the entry point:
```python theme={null}
if __name__ == "__main__":
app.main()
```
It handles two modes automatically:
* **Normal mode** — starts the background loop and blocks. The runtime calls `run_cycle()` on each schedule tick.
* **`--verify` mode** — when `--verify` is in `sys.argv`, `main()` calls `verify_worker()`, prints the result, and exits with `0` (ok) or `1` (failed). `truffile deploy` uses this to check credentials immediately after your `text` step collects them:
```yaml theme={null}
- name: Configure access token
type: text
fields:
- name: my_app_access_token
label: Access Token
type: password
env: MY_APP_ACCESS_TOKEN
validator:
type: bash
run: python ./my_app_background.py --verify
```
***
## Handling cycle results
`handle_cycle_result(ctx, result)` is where you decide what to do with each cycle's output. The pattern is roughly:
1. If it's an **auth error**, report it (deduped) and return.
2. Otherwise, reset the auth failure counter.
3. If it's a **runtime error**, log it and return. (The runtime will still retry next cycle.)
4. If nothing changed, return without submitting.
5. Otherwise, call `submit_text(...)` with a well-formed context string.
```python theme={null}
def handle_cycle_result(self, ctx, result: CycleResult) -> None:
if result.auth_error:
self.report_auth_failure(ctx, result.auth_error)
return
self.reset_auth_failures()
if result.error:
self.logger.error("Cycle failed: %s", result.error)
return
if not result.changed or not result.summary:
return
self.submit_text(
ctx,
content=result.summary,
uris=result.uris,
priority=result.priority,
)
```
### Auth failure dedup
Background apps poll often. If a token goes bad, you don't want a noisy failure report every 30 minutes — you want one clear report once the situation is clearly stuck.
`self.report_auth_failure(ctx, description)` handles this for you:
* Logs a warning on the first few failures
* After `AUTH_FAILURE_THRESHOLD` (default: 3) consecutive failures, reports to the runtime with `needs_intervention=True` so the user is prompted
* Subsequent failures stay suppressed until a successful cycle calls `self.reset_auth_failures()`
You can override `AUTH_FAILURE_THRESHOLD` on your subclass if 3 is too few or too many.
***
## Calling your own foreground tools from the background
If your app already has a foreground with tools like `gmail_search`, `github_list_issues`, or `kalshi_get_positions`, your background doesn't need to reimplement that logic — it can call its own foreground tools directly and reuse all the auth, parsing, and error handling that lives there.
The runtime gives your background a lease on the foreground container via **`ctx.connect_foreground()`**. It returns a `ForegroundConnection` that speaks MCP to your foreground.
### Basic shape
```python theme={null}
from __future__ import annotations
import asyncio
from truffile.app_runtime.background import (
BackgroundRunContext,
run_background,
)
async def _run_cycle(ctx: BackgroundRunContext) -> None:
fg = await ctx.connect_foreground()
try:
# call any tool your foreground app exposes, by name
result = await fg.call_tool("my_tool", query="hello", limit=5)
...
finally:
await fg.close()
def my_background(ctx: BackgroundRunContext) -> None:
asyncio.run(_run_cycle(ctx))
if __name__ == "__main__":
run_background(my_background)
```
Key points:
* `ctx.connect_foreground()` is **async**, so your cycle has to be too. The standard pattern is a sync entry point (`def my_background(ctx)`) that calls `asyncio.run(_run_cycle(ctx))` into an async worker.
* `fg.call_tool(name, **kwargs)` takes the tool name and any keyword arguments. The kwargs become the tool's input — exactly the same as if the agent had called it.
* Always call `await fg.close()` in a `finally` block so the lease is released when the cycle ends.
> [!NOTE]
>
> Because this pattern needs an async function with direct access to `ctx`, it's easiest to write with the lower-level `run_background(fn)` entry point instead of `BackgroundWorkerApp`.
### Real example: reuse foreground auth
The most common reason to reach into the foreground is to reuse its auth check. Instead of rewriting token loading and validation in `bg_worker.py`, just call your foreground's `check_auth` tool:
```python theme={null}
async def _run_cycle(ctx: BackgroundRunContext) -> None:
fg = await ctx.connect_foreground()
try:
# 1. reuse the foreground's auth check
auth_result = await fg.call_tool("google_check_auth")
auth_text = _extract_text(auth_result)
if "error" in auth_text.lower() or "not authenticated" in auth_text.lower():
_handle_auth_failure(ctx, auth_text)
return
# 2. now make domain calls through foreground tools
search_result = await fg.call_tool(
"gmail_search",
query="is:inbox is:unread -from:me",
max_results=30,
)
messages = _parse_search_results(_extract_text(search_result))
# 3. drill into each thread via another foreground tool
unanswered = []
for msg in messages[:10]:
thread = await fg.call_tool("gmail_get_thread", thread_id=msg["thread_id"])
if not _user_has_replied(_extract_text(thread)):
unanswered.append(msg)
# 4. submit a context message the same way any other bg cycle would
if unanswered:
ctx.bg.submit_context(
content=_build_digest(unanswered),
uris=[f"https://mail.google.com/mail/u/0/#inbox/{m['thread_id']}" for m in unanswered],
priority=1,
)
finally:
await fg.close()
```
### What `call_tool` returns
`call_tool(name, **kwargs)` returns an MCP `CallToolResult` object. The result content is a list of content blocks — for text tools, that's usually one or more `TextContent` blocks. A small helper to extract the text:
```python theme={null}
def _extract_text(result) -> str:
if hasattr(result, "content"):
parts = []
for block in result.content:
if hasattr(block, "text"):
parts.append(block.text)
return "\n".join(parts)
return str(result)
```
If your foreground tools return JSON with `ok(...)` / `err(...)`, parse the extracted text with `json.loads`.
### Listing available tools
If you need to discover what tools the foreground exposes (useful during development or for dynamic dispatch):
```python theme={null}
tools = await fg.list_tools()
for tool in tools:
print(tool.name, "-", tool.description)
```
### Always close the connection
Wrap your foreground calls in a `try` / `finally` and call `await fg.close()` when you're done — even on exceptions. Skipping this leaves the foreground container held open longer than it needs to be.
```python theme={null}
fg = await ctx.connect_foreground()
try:
...
finally:
await fg.close()
```
### Using this with `BackgroundWorkerApp`
The `run_background(fn)` entry point is the cleanest fit for foreground calls because it's async-native. If you're already using `BackgroundWorkerApp` for a simpler cycle and want to mix in a foreground call, bridge from sync to async inside `handle_cycle_result`:
```python theme={null}
import asyncio
class MyBackgroundApp(BackgroundWorkerApp[MyWorker, CycleResult]):
...
def handle_cycle_result(self, ctx, result: CycleResult) -> None:
if result.needs_foreground_followup:
asyncio.run(self._followup(ctx, result))
async def _followup(self, ctx, result: CycleResult) -> None:
fg = await ctx.connect_foreground()
try:
await fg.call_tool("my_refresh_tool")
finally:
await fg.close()
```
The tradeoff is one extra event loop per cycle. For apps that *mostly* live in foreground calls, prefer the `run_background(fn)` pattern end-to-end.
***
## Writing good context submissions
The quality of your background context *directly* affects how proactive behavior feels. Rich, concrete items win every time.
**Weak:**
> Market alert
**Strong:**
> Price alert: FED-RATE-SEP moved up 12c (was 41c, now 53c)
> Related: [https://kalshi.com/markets/FED-RATE-SEP](https://kalshi.com/markets/FED-RATE-SEP)
**Weak:**
> New PRs in your repos
**Strong:**
> @octocat opened PR #342 in truffle-ai/pyfw-codex: "Fix mDNS timeout on retry"
> 2 files changed, +18/-4. Requested reviews: @alice, @bob
> [https://github.com/truffle-ai/pyfw-codex/pull/342](https://github.com/truffle-ai/pyfw-codex/pull/342)
A few guidelines:
* **Include the entities.** Names, tickers, IDs, usernames, repo paths, order numbers.
* **Include numbers with context.** `$12k` alone is useless; `$12k (was $8.4k yesterday)` is actionable.
* **Include links.** Pass them in `uris=(...)` so the agent can open them if it decides to act.
* **Pick priority honestly.** Default priority is fine for most things. Bump it for genuine urgency (alerts, settlements, revoked tokens).
* **Don't spam.** Use a fingerprint or diff to skip cycles where nothing meaningfully changed — return a `CycleResult` with `changed=False` and don't submit.
> [!NOTE]
>
> Background context can trigger action in *any* app, not just yours. If an Instagram message about an Amazon order lands in the proactive agent's context, Truffle might use your Amazon app to add the item to cart. Write submissions with that in mind.
***
## Schedule configuration
The `default_schedule` block in `truffile.yaml` under `metadata.background` controls when your cycle runs. Three policy types are supported: **`interval`**, **`always`**, and **`times`**.
### `interval` — run every N minutes/hours
The most common mode. Your cycle runs, yields, sleeps for the configured duration, then runs again.
```yaml theme={null}
metadata:
background:
process:
cmd: ["python", "my_app_background.py"]
working_directory: /
environment:
PYTHONUNBUFFERED: "1"
default_schedule:
type: interval
interval:
duration: 30m
schedule:
daily_window: "00:00-23:59"
```
* **`duration`** — interval between runs. Accepts `ms`, `s`, `m`, `h`, `d` suffixes (e.g. `5m`, `30m`, `2h`, `1d`).
* **`schedule.daily_window`** — optional time window that gates execution. `"09:00-18:00"` only runs during business hours; `"00:00-23:59"` (the effective default) runs any time.
* **`schedule.allowed_days`** — optional list like `[mon, tue, wed, thu, fri]` to restrict to specific weekdays.
* **`schedule.forbidden_days`** — optional inverse: list of days to skip (e.g. `[sat, sun]`). Mutually exclusive with `allowed_days`.
> [!TIP]
>
> During development, set `duration: 1m` so you can see results quickly. Bump it back up before shipping.
### `always` — keep running as long as there's work
For apps that need to react to live data the moment it arrives. The runtime keeps your process alive continuously instead of running-then-sleeping. Use it when a fixed interval would either miss updates (too slow) or burn cycles (too fast).
```yaml theme={null}
metadata:
background:
process:
cmd: ["python", "my_app_background.py"]
working_directory: /
default_schedule:
type: always
```
No duration, no schedule block — just `type: always`.
Good fits:
* Watching a websocket or server-sent event stream (market data, chat messages, push notifications)
* Apps that need to submit context to the proactive agent **the moment** something happens — e.g. a Kalshi watcher that fires a high-priority submission the instant a position moves, not 30 minutes later
* Any integration where the upstream service pushes data instead of you polling for it
> [!WARNING]
>
> Under `always`, your cycle function is expected to block (on a websocket read, a queue, whatever) rather than return quickly. If you return immediately, the runtime will just call you again and you'll burn CPU doing nothing. Write your loop to stay inside `run_cycle` for as long as the connection is alive, and return only when you want the runtime to restart you.
### `times` — run at specific times of day
For apps that should run at fixed clock times (e.g. a daily 9am digest):
```yaml theme={null}
metadata:
background:
process:
cmd: ["python", "my_app_background.py"]
default_schedule:
type: times
times:
run_times:
- "09:00"
- "17:00"
allowed_days: [mon, tue, wed, thu, fri]
```
* **`run_times`** — list of `HH:MM` (or `HH:MM:SS`) times of day, each triggers one cycle.
* **`allowed_days`** / **`forbidden_days`** — optional day-of-week gating, same semantics as `interval`.
***
## Cleanup on shutdown
Close your worker's network clients on exit:
```python theme={null}
import atexit
def _cleanup() -> None:
worker = getattr(app, "_worker", None)
if worker is not None:
close = getattr(worker, "close", None)
if callable(close):
try:
close()
except Exception:
pass
atexit.register(_cleanup)
```
This isn't optional. Leaving HTTP connections and other resources open at process exit is the most common source of flaky redeploys.
***
## Deploy and verify
```bash theme={null}
truffile validate ./my-app
truffile deploy --dry-run ./my-app
truffile deploy ./my-app
```
Once deployed:
* Your `run_cycle()` will be invoked on the configured interval
* `handle_cycle_result()` decides what to submit
* `submit_text(...)` calls land in the proactive agent's context
* Auth failures past the threshold surface as "needs intervention" in the app UI
***
## When to build a background app
Use a background app when you want:
* **Periodic polling** of an external system (new messages, new PRs, new fills, new feed items)
* **Monitoring** with thresholds (price alerts, rate changes, error budgets)
* **Digest generation** (daily/weekly/hourly summaries)
* **Context emission** that feeds proactive actions in other apps
If you *also* need callable tools, add a `foreground` section to the same `truffile.yaml` — it becomes a hybrid app. Use the same shared client/auth module from both entry points, and keep background-specific diffing or polling logic in a plain worker class so it stays easy to test.
# Building Truffle Apps
Source: https://docs.truffle.net/sdk/building-apps
An overview of how Truffle apps work and how to build your own
A Truffle app is a containerized Python program that runs on your Truffle and extends what the on-device agent can do. Apps come in three shapes:
| Shape | When it runs | What it does |
| - | - | - |
| **Foreground** | On demand | Exposes MCP tools the agent can call during a Convo request |
| **Background** | On a schedule | Submits context to the proactive agent |
| **Hybrid** | On demand + on a schedule | Both: tools *and* scheduled context |
You pick the shape with `metadata.foreground`, `metadata.background`, or both
in `truffile.yaml`. Foreground apps can run Python tools or use a native remote
MCP connector. See [accounts and authentication](/sdk/accounts) for a complete
connector example and connection-scoped credentials.
The supported development loop is intentionally CLI-first: scaffold locally,
check the bundle locally, preview the upload, then deploy through the native
installer and builders. Use `--update` for later code changes that preserve
installed accounts.
The bundled examples live under `truffile/app-store/` in the `truffile` repo. Treat them as reference implementations:
| Example | Shape | Auth/install pattern | Foreground style |
| - | - | - | - |
| `exa` | Foreground | `text` API key | Native `ForegroundApp` wrapper around a remote JSON-RPC MCP service |
| `home-assistant` | Foreground | `text` URL + long-lived token | Native `ForegroundApp` with safety wrappers over Home Assistant MCP |
| `obsidian` | Foreground | `text` bridge URL + token, usually prefilled by `truffile obsidian deploy` | Native `ForegroundApp` talking to a local bridge |
| `arxiv` | Hybrid | `text` research interests | Native `ForegroundApp` tools plus scheduled recommendations |
| `whoop` | Hybrid | Standard `oauth` | Native `ForegroundApp` and `BackgroundWorkerApp` sharing OAuth token helpers |
| `notion` | Hybrid | Remote MCP `oauth` with dynamic client registration | Remote MCP proxy/wrapper plus background digest worker |
| `viator` | Hybrid | No auth; `welcome` step | Remote MCP proxy/wrapper plus travel context background |
***
## The SDK import surface
App code imports everything it needs from **`truffile.app_runtime`**. This is the module that ships with the `truffile` package when you `pip install truffile`.
```python theme={null}
from truffile.app_runtime import (
ForegroundApp,
BackgroundWorkerApp,
ToolSpec,
Submission,
ok,
err,
phosphor_icon_url,
AppAuthError,
AppRuntimeFailure,
)
```
The runtime is copied from PyFW into the release wheel; it is not tracked in
the SDK source checkout. It ships as `truffile.app_runtime` in the installed package. Once you `pip install truffile`, the same runtime is importable from app code running on your device.
There are two other entry points that import the same names:
* `from truffile.sdk import ...` — a curated re-export module with nice grouping. Use this if you prefer one obvious "public API" import.
* `from truffile import ForegroundApp, BackgroundWorkerApp, ToolSpec, ok, err, OAuth, AppHarness` — the most common names are also re-exported at the top level.
All three forms resolve to the same objects. Pick whichever reads best for you. The examples in this guide use `truffile.app_runtime` because it is the clearest app-authoring import surface.
***
## Scaffold a new app
The fastest way to start:
```bash theme={null}
truffile create my-app
```
```text theme={null}
✓ Created app scaffold: ./my-app
Files:
→ truffile.yaml
→ my_app_foreground.py
→ my_app_background.py
→ icon.png
Next: truffile validate ./my-app
```
Flags:
* `truffile create ` — set the name, prompt for base path
* `truffile create --path ` — set name and base path
* `truffile create` — fully interactive
The foreground starter includes a ping tool. The background starter is a
placeholder that you must implement before relying on scheduled work. Delete whichever you don't need — the app type is inferred from which `foreground` / `background` sections you keep in `truffile.yaml`.
***
## Let an agent build the app for you
If you're working in the truffile repo with a coding agent — **Claude Code**, **Codex**, or any other agent that can read skill files — there's a built-in skill it can follow to build a Truffle app end-to-end: **`truffle-app-creator`** (at `truffile/skills/truffle-app-creator/SKILL.md`).
It's the fastest path for things like:
* *"Create a Truffle app that talks to \"*
* *"Port this MCP server to Truffle"*
* *"Build an integration with \ and run it in the background"*
The skill handles architecture decisions (foreground/background/hybrid, auth type, base image), uses `truffile create` to scaffold, implements the client/auth/tools, writes tests, and runs `truffile validate` + `truffile deploy` for you. Just describe the service you want to connect and it takes over from there.
***
## `truffile.yaml` structure
Every app needs a `truffile.yaml`. This authenticated process example assumes
you implement the Python entrypoints, including a `--verify` mode that checks
the API key and exits. For a first ping test, use the generated scaffold as-is.
```yaml theme={null}
truffile_version: 4
connections: multi
metadata:
name: My App
bundle_id: org.example.myapp
description: |
What this app does, in one short paragraph.
icon_file: ./icon.png
foreground:
process:
cmd: ["python", "my_app_foreground.py"]
working_directory: /
environment:
PYTHONUNBUFFERED: "1"
background:
process:
cmd: ["python", "my_app_background.py"]
working_directory: /
environment:
PYTHONUNBUFFERED: "1"
default_schedule:
type: interval
interval:
duration: 30m
daily_window: "00:00-23:59"
steps:
- name: Install dependencies
type: bash
scope: install
run: |
pip install --no-cache-dir httpx
- name: Copy app files
type: files
scope: install
files:
- source: ./my_app_foreground.py
destination: ./my_app_foreground.py
- source: ./my_app_background.py
destination: ./my_app_background.py
- name: Configure access token
type: text
scope: connection
content: |
Enter an API key from https://example.com/settings/tokens
fields:
- name: api_key
label: API Key
type: password
env: MY_APP_API_KEY
validator:
type: bash
run: python ./my_app_foreground.py --verify
timeout: 90
error_message: |
Could not verify MY_APP_API_KEY. Check the key is valid.
```
### Supported step types
Steps run during installation on the device, in order. The manifest supports:
| Type | What it does |
| - | - |
| `bash` | Run a shell command in the app's container (for dependencies, setup) |
| `files` | Copy files from your repo into the container |
| `text` | Collect input from the user and expose it as env vars on the process |
| `oauth` | Run an OAuth install flow and persist token state for the app |
| `welcome` | Show a simple informational install step |
See the [Install steps reference](/sdk/install-steps) for every option on each type — field shapes, validators, exit code semantics, and multi-field examples.
> [!NOTE]
>
> Native deployment can present browser/VNC setup cards from firmware. Open the
> shown setup URL and follow the app's flow. The explicit legacy builder supports
> only its older step subset; use normal deploy for modern manifests.
***
## Auth patterns
Pick the smallest auth surface that matches the upstream service:
| Pattern | Use it when | Step type | Example |
| - | - | - | - |
| No auth | The upstream service is public or the app only needs static defaults | `welcome` or no auth step | `viator` |
| Text/config | The user can paste an API key, token, URL, or local bridge value | `text` | `exa`, `home-assistant`, `obsidian`, `arxiv` |
| Standard OAuth | The provider has normal auth/token endpoints and fixed client metadata | `oauth` | `whoop` |
| Remote MCP OAuth | The upstream MCP server owns OAuth metadata or dynamic client registration | `oauth` with resource metadata / DCR fields | `notion` |
| Local bridge | The app on the device needs to talk back to a process on the user's computer | usually `text`, often prefilled by a helper command | `obsidian` |
For `text` auth, implement a provider check and call it from a connection-scoped
validator. Native OAuth stores tokens for the selected connection. Custom Python
apps use runtime credential helpers; native connectors declare an OAuth
`app_var_key` matching their connection step. See the [account guide](/sdk/accounts)
for the complete connector recipe. Older bundled token-file examples should not
be copied into shared state for a multi-account app.
If an update reaches an auth step that cannot be refreshed non-interactively, fail clearly and ask the user to run `truffile connections reconnect "My App"`.
***
## Build and deploy flow
```bash theme={null}
truffile validate ./my-app
truffile deploy --dry-run ./my-app
truffile deploy ./my-app
```
* **`validate`** checks bundle structure and basic metadata. Use `python -m compileall -q ./my-app` separately for Python syntax.
* **`deploy --dry-run`** packages and describes the bundle without changing the device.
* **`deploy`** sends the original manifest to firmware for semantic validation, builder execution and account setup.
After editing app code, run `truffile deploy ./my-app --update`. This preserves
accounts, credentials and saved settings. `--replace` deliberately resets
accounts after confirmation. Current firmware is required for uploaded updates
and replacements; the CLI checks support before either operation.
`--interactive` opens the explicit legacy builder's shell. Ordinary native
sign-in prompts do not require that flag. See [deployment](/sdk/deployment)
for packaging exclusions, timeouts, account selection and scripted setup.
After deployment, use an agent-safe one-shot request as a routing smoke test:
```bash theme={null}
truffile convo --new --json --quiet --timeout 120 \
"Use and summarize the result"
```
Inspect `tool_calls` in the JSON result. This tests normal agent discovery and
tool routing only. Convo has no per-thread app allowlist, so the CLI cannot
attach the newly deployed app or guarantee that this request uses it. Use
`truffile infer --mcp ` before deployment when you need deterministic
local selection of the app's MCP server.
***
## Runtime stability pattern
Whatever network clients your app opens — HTTP sessions, database connections, MCP subprocesses — close them on shutdown:
```python theme={null}
import atexit
def _cleanup() -> None:
try:
client.close()
except Exception:
pass
atexit.register(_cleanup)
```
Leaving outbound connections open at process exit is the most common source of flaky redeploys and container runtime crashes. Every example app in the repo does this.
***
## Next steps
> [card] [Build a Foreground App](/sdk/focus-app)
>
> Use `ForegroundApp` to expose MCP tools the agent can call on demand.
> [card] [Build a Background App](/sdk/ambient-app)
>
> Use `BackgroundWorkerApp` to run on a schedule and submit context to the proactive agent.
# Truffile CLI
Source: https://docs.truffle.net/sdk/cli
The complete guide to using the truffile CLI — device connection, Convo, inference, app management, and more
## Overview
The `truffile` CLI is your interface to Truffle. Use it to discover and connect to devices, use Convo with the on-device agent, run raw model inference, and deploy apps.
```bash theme={null}
pip install truffile
```
Running `truffile` with no arguments opens the [Convo REPL](#convo-mode) in an
unsent side-thread draft.
***
## Scriptable commands
Most workflows can be driven with explicit arguments, which makes them easy to
test in CI or from another agent:
```bash theme={null}
truffile connect 6272 --user-id "$TRUFFLE_USER_ID"
truffile list devices
truffile list apps --json
truffile load all
truffile create my-app --path ./apps
truffile validate ./apps/my-app
truffile deploy ./apps/my-app --dry-run --json
truffile deploy ./apps/my-app --update --json --non-interactive
truffile delete my-app
truffile convo --new --json --quiet --timeout 60 "Summarize my installed apps"
truffile infer "Say pong" --json --no-stream --quiet
truffile infer --list-models --json
```
Interactive commands still exist for normal human use. Prefer the explicit
forms above when you are writing tests, scripts, or agent tools.
***
## Connecting to Your Truffle
You need to connect to a device before you can use Convo, run inference, or manage apps.
### Scan for devices
```bash theme={null}
truffile scan
```
```
✓ Scanning for Truffle devices (5s)
Found 3 Truffle device(s):
1. truffle-1234 (192.0.2.10)
2. truffle-5678 (192.0.2.11) [connected]
3. truffle-9012 (192.0.2.12)
Select device to connect (1-3) or press Enter to cancel:
```
Select a device by number to start the connection flow.
### Connect directly
If you already know your device name:
```bash theme={null}
truffile connect 6272 --user-id "$TRUFFLE_USER_ID"
```
Enter your User ID from Symphony Settings when prompted, then approve the connection on your device.
Credentials are saved locally — subsequent connections are automatic.
> [!NOTE]
>
> Before `truffile connect`, onboard the device in the Symphony desktop client. Download Symphony from [the client overview](/client/overview) and finish device onboarding there. The CLI will ask for your User ID from Symphony Settings before you approve the session on your device.
***
## Loading agent resources
`truffile` ships with agent-readable skills and example apps. Copy them into
your current workspace when you want a coding agent to inspect them directly:
```bash theme={null}
truffile load all
```
This creates:
```text theme={null}
./truffile/
skills/
examples/
```
Use narrower forms when needed:
```bash theme={null}
truffile load skills
truffile load examples
truffile load all --force
truffile load all --json
```
The copied skills cover CLI usage, one-shot Convo, raw inference, and app
creation. The examples are real bundled apps that show foreground tools,
background workers, text auth, OAuth, no-auth apps, and local bridge patterns.
### Disconnect
```bash theme={null}
# disconnect from a specific device
truffile disconnect truffle-1234
# disconnect from all devices and clear all saved credentials
truffile disconnect all
```
> [!WARNING]
>
> `disconnect all` clears all saved credentials. You'll need to go through the full approval flow again next time.
***
## Convo Mode
Convo connects to the authenticated user's stateful on-device agent. Main is
thread `0`; user conversations otherwise live in side threads. Legacy Task
histories are not migrated or listed after the one-way cutover.
```bash theme={null}
truffile convo
```
This is also the default. A bare launch starts in an unsent side-thread draft,
and the first send creates that thread. Use `/new` for another draft or
`/main` to opt into Main explicitly.
### Sending messages
Type your message and press **Enter** to send. Use **Alt+Enter** for multi-line input.
```
you> What can you help me with?
thinking: considering user's question about capabilities...
• tool: get_system_info — checking available apps
I can help you with several things...
```
Responses stream in real-time with a thinking orb animation while the model reasons. Tool calls appear inline above the response.
### Threads and history
Use `/threads` to list and switch among user-visible threads. System and
Bulletin threads are omitted. Messages and replies remain in the selected
thread, and `/history` shows its durable history.
Type `/help` inside Convo to see all commands.
| Command | What it does |
| - | - |
| `/threads` | Pick from visible Convo threads |
| `/new` | Start an unsent side-thread draft |
| `/main` | Explicitly select Main |
| `/history` | Show the selected thread's history |
| `/title` | Show the selected thread's title |
| `/rename ` | Rename the selected thread |
| `/interrupt` | Interrupt work in the selected thread |
| `/hide [name\|id]` | Locally hide a side thread |
| `/restore [name\|id]` | Restore a locally hidden thread |
| `/deploy ` | Deploy an app to the device from within Convo |
| `/delete app [name]` | Delete an installed app (interactive picker if no name given) |
| `/delete task` | Compatibility alias that locally hides a side thread; reversible and not server deletion |
| `/create ` | Scaffold a new app |
| `/devices` | List connected devices |
`/tasks`, `/resume`, and `/switch` are temporary compatibility spellings for
the Convo thread picker. They do not access the retired Task backend.
### Installed apps
Inspect installed apps with either discovery-only command:
```bash theme={null}
truffile list apps
truffile convo --list-apps
```
Convo has no per-chat app allowlist: no app is attached to or restricted for a
thread. Interactive `/apps`, `--app`, and dynamic `/` sends are
unavailable. The agent can still discover installed tools and decide whether
to use them through normal routing.
For all targeting, listing, action, JSON, and exit-code details, see
[Convo automation](/sdk/convo-automation). For the complete interactive model,
see [Convo](/sdk/convo).
#### Exiting
| Command | What it does |
| - | - |
| `/exit` | Exit Convo |
| `/quit` | Exit Convo |
| **Ctrl+D** | Exit Convo |
***
## Infer Mode
Infer mode gives you direct access to model inference with full control over generation parameters, MCP tool integration, and image input.
```bash theme={null}
truffile infer
```
### CLI flags
| Flag | What it does |
| - | - |
| `--model ` | Pre-select a model |
| `--system ` | Set an initial system prompt |
| `--no-stream` | Disable streaming (get the full response at once) |
| `--no-tools` | Disable built-in tools (`web_search`, `web_fetch`) |
| `--mcp ` | Connect an MCP server at startup (can be repeated) |
```bash theme={null}
# start with a specific model and system prompt
truffile infer --model my-model --system "You are a helpful coding assistant"
# start with MCP server pre-connected
truffile infer --mcp http://127.0.0.1:8000/mcp
```
### Generation controls
All settings can be viewed and changed live inside the REPL. Run the command without an argument to see the current value.
| Command | What it does | Default |
| - | - | - |
| `/reasoning on\|off` | Show model reasoning/thinking | `on` |
| `/stream on\|off` | Stream tokens as they're generated | `on` |
| `/json on\|off` | JSON response mode | `off` |
| `/tools on\|off` | Enable built-in tools (`web_search`, `web_fetch`) | `on` |
| `/max_tokens ` | Max output tokens | `2048` |
| `/temperature ` | Sampling temperature | `None` |
| `/top_p ` | Top-p (nucleus) sampling | `None` |
| `/max_rounds ` | Max tool call rounds per turn | `8` |
| `/system ` | Set or clear the system prompt | `None` |
```
> /config
chat config
model: llama-3.1-8b
reasoning: True
stream: True
json: False
tools: True
max_tokens: 2048
temperature: None
top_p: None
max_rounds: 8
system:
mcp:
```
### Built-in tools
When tools are enabled (`/tools on`, the default), the model can use:
* **`web_search`** — search the web and return top results
* **`web_fetch`** — fetch a URL and extract readable text
Tool calls are displayed inline:
```
> What's the latest news about SpaceX?
🔨 tool web_search
🔨 tool web_fetch
Here's what I found...
---
tokens [142/580/722] | decode 48.2 t/s | ttft 312ms
```
Token usage stats are printed after each response.
### Image attachments
Attach an image to your next message with `/attach`:
```
> /attach ./screenshot.png
✓ attachment ready: path=/Users/me/screenshot.png size=142.3 KiB mime=image/png
> What's in this image?
[attach] sending with image: path=/Users/me/screenshot.png size=142.3 KiB mime=image/png
The image shows...
```
You can also attach from a URL:
```
> /attach https://example.com/photo.jpg
✓ attachment ready: url=https://example.com/photo.jpg size=89.1 KiB mime=image/jpeg
```
The attachment is sent with the next message, then cleared automatically.
Supported formats: **JPEG**, **PNG**, **BMP** natively. Other formats (WebP, TIFF, etc.) are transcoded via Pillow if installed.
### MCP integration
Connect external [MCP](https://modelcontextprotocol.io) servers to give the model additional tools. Only **streamable HTTP** transport is supported.
| Command | What it does |
| - | - |
| `/mcp status` | Show connection status and tool count |
| `/mcp connect ` | Connect to an MCP server |
| `/mcp tools` | List available tools from connected server |
| `/mcp disconnect` | Disconnect the MCP session |
```
> /mcp connect http://127.0.0.1:8000/mcp
/mcp connect ✓ http://127.0.0.1:8000/mcp (5 tools)
> /mcp tools
/mcp tools get_markets, get_market, get_orderbook, create_order, cancel_order
```
MCP tools and built-in tools work together — the model picks the right tool for each request.
> [!TIP]
>
> This is a great way to **test your app's MCP server locally** before deploying to the device. Start your MCP server, connect it via `/mcp connect`, and test with real prompts.
### Conversation management
| Command | What it does |
| - | - |
| `/history` | Show conversation history (role + content summary) |
| `/reset` | Clear conversation history and pending attachments |
| `/models` | Open the interactive model picker |
| `/config` | Show all current settings |
| `/create ` | Scaffold a new app |
| `/exit` | Exit infer |
***
## Keyboard Shortcuts
These work in both Convo and Infer modes.
| Key | What it does |
| - | - |
| **Enter** | Send message |
| **Alt+Enter** | Insert a new line (multi-line input) |
| **Tab** | Autocomplete slash commands |
| **Esc** | Interrupt a streaming response |
| **Ctrl+C** | Interrupt current operation (press twice within 3s to exit) |
| **Ctrl+D** | Exit the REPL |
***
## App Management
### Create a new app
```bash theme={null}
# interactive — prompts for name
truffile create
# with a name
truffile create my-app
# in a specific directory
truffile create my-app --path ./apps
```
Creates a scaffold with `truffile.yaml`, foreground/background entry points, and a default icon.
### Validate and deploy
```bash theme={null}
truffile validate ./my-app
truffile deploy ./my-app --dry-run
truffile deploy ./my-app
```
`validate` and `--dry-run` check bundle structure and basic manifest metadata.
Firmware validates full manifest semantics during installation. For Python
syntax, also run `python -m compileall -q ./my-app`.
Normal deploy uploads your directory or `.truffle` bundle to the native
installer, which runs its builders and account setup. Text/password forms are
shown in the terminal; OAuth opens a sign-in flow with a callback/code handoff;
browser/VNC setup cards expose the device setup URL. Actual provider support
depends on the firmware and app's setup plan.
### Update or replace
```bash theme={null}
truffile deploy ./my-app --update
truffile deploy ./my-app --replace
```
Keep the same bundle ID. Update preserves accounts and settings. Replace runs
fresh setup and resets accounts after confirmation; scripts must add `--yes`.
Both require firmware with developer-upload support. Normal deploy refuses an
existing bundle ID until you choose a mode.
`--legacy-builder` retains the old direct builder for fresh installations.
`--interactive` opens that legacy builder's debug shell. It is not the flag
for normal interactive sign-in and does not support native connectors.
### Accounts and permissions
```bash theme={null}
truffile connections list "My App" --json
truffile connections add "My App"
truffile connections reconnect "My App"
truffile connections rename "My App" Work
truffile connections permissions "My App" Work read-only
truffile connections delete "My App" Work
```
App names, bundle IDs and UUIDs work. Omit the account for a picker; the rename
example picks an account and calls it `Work`. Scripts must supply an unambiguous
account alias or UUID. `--json` and `--non-interactive` never prompt.
Permission modes are `default`, `read-only`, `read-write`, and `auto-review`.
`default` removes an account override and inherits device policy. `--notes`
sets review notes; omitting it keeps saved notes. New accounts start with device
policy, and the CLI does not modify device-wide defaults.
Supply `--answers-file /private/answers.json` to automate text/password setup.
Keep that JSON map of field names to values outside your app directory. OAuth
requires interactive approval; credentials remain with the device's installer.
On expiry or disconnect, inspect the installed app before retrying.
See [deployment](/sdk/deployment) for all lifecycle options and
[accounts and authentication](/sdk/accounts) for authoring patterns.
### List apps and devices
```bash theme={null}
truffile list apps # installed apps on the connected device
truffile list devices # devices you have saved credentials for
```
### Delete apps
```bash theme={null}
# interactive picker
truffile delete
# delete all apps
truffile delete all
# delete by index (1-based, as shown in the app list)
truffile delete 1 2 3
# comma-separated works too
truffile delete 1,3,5
# pipe selection
echo "all" | truffile delete
echo "1 2" | truffile delete
```
If you pass indices that are out of range or invalid, the CLI falls back to the interactive picker (when running in a terminal).
### List models
```bash theme={null}
truffile models
```
Shows all inference models available on the connected device.
***
## Convo vs Infer
Both modes let you talk to models on your Truffle, but they serve different purposes:
| | Convo | Infer |
| - | - | - |
| **What it is** | Stateful agent over Main and side threads | Direct model inference REPL |
| **Command** | `truffile convo` (or just `truffile`) | `truffile infer` |
| **Conversations** | Durable Convo threads | In-memory history, cleared on exit |
| **Apps** | Agent can discover installed tools; no per-thread app restriction | No app integration |
| **MCP** | No MCP (apps provide tools) | Full MCP support via `/mcp connect` |
| **Image input** | Not available | `/attach ` |
| **Generation control** | Managed by the agent | Full control (`/reasoning`, `/stream`, `/temperature`, etc.) |
| **Built-in tools** | Agent decides tool use | `web_search` + `web_fetch` (toggleable) |
| **Best for** | Using your Truffle day-to-day | Testing models, MCP servers, and prompts |
***
## Command Reference
| Command | Description |
| - | - |
| `truffile` | Start Convo in an unsent side-thread draft (default) |
| `truffile scan` | Scan network for Truffle devices |
| `truffile connect ` | Connect to a device |
| `truffile disconnect [device\|all]` | Disconnect and clear credentials |
| `truffile create [name] [--path ]` | Scaffold a new app |
| `truffile validate [path]` | Check bundle structure and basic manifest metadata |
| `truffile deploy [path]` | Deploy app to connected device |
| `truffile deploy --dry-run` | Inspect the bundle without changing the device |
| `truffile deploy [path] --update` | Upload code while preserving accounts |
| `truffile deploy [path] --replace` | Run fresh setup and reset accounts after confirmation |
| `truffile connections ` | List, add, reconnect, rename, delete, or set account permissions |
| `truffile deploy --interactive` | Open the legacy builder debug shell |
| `truffile list apps` | List installed apps |
| `truffile list devices` | List connected devices |
| `truffile delete [all\|1 2 3]` | Delete apps (interactive, by index, or all) |
| `truffile models` | List models on connected device |
| `truffile convo [PROMPT...] [--prompt-file FILE\|--stdin] [--main\|--thread NAME\|--thread-id ID\|--resume-last\|--new]` | Open the Convo REPL or send a targeted one-shot prompt |
| `truffile convo [--rename NAME\|--history\|--interrupt\|--hide THREAD\|--restore THREAD] [--include-hidden]` | Act on Convo threads |
| `truffile convo [--list-chats [N]\|--list-threads [N]\|--list-apps] [--json]` | List Convo threads or installed apps |
| `truffile infer [--model M] [--system S]` | Raw inference REPL |
| `truffile help` | Show help |
# Convo
Source: https://docs.truffle.net/sdk/convo
Use the stateful on-device agent through Main and side threads
`truffile convo` opens the authenticated user's Convo on the connected device.
Convo is the only backend for this command. Chats from the retired `Task_*`
backend are not migrated or listed after the one-way cutover.
For scripts and coding agents, see the [one-shot and automation reference](/sdk/convo-automation).
## Main and side threads
Main is thread `0`. A bare launch does not select Main: it opens an unsent
side-thread draft instead.
```bash theme={null}
truffile convo
```
The first message creates that side thread. Use `/new` whenever you want
another unsent side-thread draft. Main always requires an explicit opt-in:
```bash theme={null}
truffile convo --main
```
Inside the REPL, `/main` selects Main and `/threads` lists and switches among
user-visible threads. System and Bulletin threads, including thread `-1`, are
not shown and cannot be selected.
Messages and replies remain in the selected thread, so follow-up messages use
its durable history until you switch threads or start a new draft.
## Interactive commands
Type `/help` in the REPL to show the commands supported by your installed
Truffile version.
| Command | What it does |
| - | - |
| `/threads` | List and switch among visible Convo threads |
| `/new` | Start an unsent side-thread draft |
| `/main` | Explicitly switch to Main (thread `0`) |
| `/history` | Show history for the selected thread |
| `/title` | Show the selected thread's title |
| `/rename ` | Rename the selected thread |
| `/interrupt` | Request interruption of work in the selected thread |
| `/hide [name\|id]` | Hide a side thread on this machine |
| `/restore [name\|id]` | Restore a locally hidden thread |
| `/deploy ` | Deploy an app from inside Convo |
| `/delete app [name]` | Delete an installed app |
| `/create ` | Scaffold an app |
| `/devices` | List connected devices |
| `/exit` | Exit Convo |
`/tasks`, `/resume`, and `/switch` temporarily open the same Convo thread
picker as `/threads`; they do not access legacy Task chats. `/delete task` is
also a compatibility entry, but it only performs the reversible local hide
described below. It does not delete anything from the server.
## Local hide and restore
`/hide` removes a side thread from this Truffile installation's normal picker.
The hidden-thread state is local, reversible, and scoped to the device and
authenticated user. It never deletes a Convo thread from the server. Main and
system threads cannot be hidden.
Use `/restore` to return a hidden thread to the normal list. In automation,
`--hide`, `--restore`, and `--include-hidden` provide the same local behavior.
## Installed apps and tool routing
Convo has no per-chat or per-thread app allowlist. Nothing is attached to a
thread, and the CLI cannot force or restrict a request to one installed app.
The agent may discover installed tools and decide to use them through its
normal routing.
Interactive `/apps`, dynamic `/` selection, and `--app` are unavailable.
Use either discovery-only command instead:
```bash theme={null}
truffile list apps
truffile convo --list-apps
```
To test an app deterministically before deployment, connect its local MCP
server with [`truffile infer --mcp`](/sdk/cli#mcp-integration).
# Convo automation
Source: https://docs.truffle.net/sdk/convo-automation
One-shot prompts, thread actions, JSON output, and exit codes for agents and scripts
Supplying a prompt or action flag to `truffile convo` uses one-shot mode: the
command performs the request, writes its result, and exits. A prompt without a
target creates a new side thread on first send. Use `--main` only when the user
explicitly wants Main.
```bash theme={null}
truffile convo --new --json --quiet --timeout 60 \
"Summarize my installed apps"
```
## Prompt sources and targets
Positional text, `--prompt-file`, and `--stdin` may be combined; Truffile joins
their non-empty contents with blank lines. With piped stdin and no positional
or file prompt, stdin is read automatically.
| Flag | Behavior |
| - | - |
| `PROMPT...` | Join positional words as prompt text |
| `--prompt-file PATH` | Read prompt text from a file |
| `--stdin` | Read prompt text from stdin |
| `--new` | Explicitly create a side thread on the first send |
| `--main` | Target Main (thread `0`) |
| `--thread NAME_OR_ID` | Select an existing thread by exact title or decimal ID |
| `--thread-id ID` | Select an existing thread by decimal ID |
| `--resume-last` | Select the thread with the newest node |
The target flags are mutually exclusive. Omitting all of them selects a new
side-thread draft. `--thread` title matching is case-insensitive and must be
unambiguous.
```bash theme={null}
truffile convo --thread "Trip research" --json --quiet "continue"
truffile convo --thread-id 123 --json --quiet "continue"
truffile convo --resume-last --json --quiet "continue"
cat instructions.md | truffile convo --stdin --json --quiet --timeout 120
truffile convo --prompt-file instructions.md --json --quiet --timeout 120
```
## Actions and output controls
| Flag | Behavior |
| - | - |
| `--rename NAME` | Rename the selected thread, or a new thread after its first send |
| `--history` | Print selected-thread history; requires an existing-thread target |
| `--interrupt` | Request interruption; requires an existing-thread target |
| `--hide THREAD` | Locally hide a side thread and exit |
| `--restore THREAD` | Restore a locally hidden side thread and exit |
| `--include-hidden` | Include locally hidden threads in listing and selection |
| `--list-chats [N]` | List up to `N` visible threads; default `15` |
| `--list-threads [N]` | Canonical synonym for `--list-chats` |
| `--list-apps` | List installed apps for discovery only |
| `--json` | Write one machine-readable JSON document to stdout |
| `--quiet`, `-q` | Suppress non-result diagnostics |
| `--show-thinking` | Write durable thinking summaries to stderr in text mode |
| `--timeout SECONDS` | Opt into a settlement deadline; must be greater than zero |
Without `--json`, final response content goes to stdout. Diagnostics, durable
thinking requested by `--show-thinking`, and text-mode errors go to stderr.
Use `--json --quiet` when another program will parse stdout.
`--timeout` is opt-in. When it expires, Truffile requests an interrupt, emits
the durable result it has, marks it timed out, and exits `124`.
## JSON contracts
### Turn result
```json theme={null}
{
"task_id": "123",
"thread_id": "123",
"backend": "convo",
"title": "QA debug",
"device": "truffle-1234",
"content": "...",
"thinking": null,
"tool_calls": null,
"pending_user_response": false,
"attached_apps": null,
"status": "ok",
"error": null,
"interrupted": false,
"timed_out": false
}
```
`thinking` and `tool_calls` are arrays when present. `status` can be `ok`,
`error`, `interaction_required`, `interrupted`, `timeout`, or `fence_lost`.
Setup, OAuth, and action nodes that need a supported client set
`pending_user_response` and return `interaction_required`.
### Thread list
```json theme={null}
{
"threads": [
{
"thread_id": "123",
"task_id": "123",
"title": "QA debug",
"thread_kind": "NODE",
"created": "2026-08-10T18:30:00+00:00",
"updated": "2026-08-10T18:31:00+00:00",
"latest_node_id": "456",
"last_read_node_id": "456",
"unread_count": 0,
"has_unread": false,
"hidden_local": false
}
],
"tasks": [
{
"thread_id": "123",
"task_id": "123",
"title": "QA debug",
"thread_kind": "NODE",
"created": "2026-08-10T18:30:00+00:00",
"updated": "2026-08-10T18:31:00+00:00",
"latest_node_id": "456",
"last_read_node_id": "456",
"unread_count": 0,
"has_unread": false,
"hidden_local": false
}
],
"backend": "convo"
}
```
The one-release `tasks` alias contains the same rows as `threads`.
### History
```json theme={null}
{
"history": [
{
"node_id": "456",
"thread_id": "123",
"kind": "ai",
"content": "...",
"thinking": [],
"tool_calls": [],
"created": "2026-08-10T18:31:00+00:00"
}
],
"backend": "convo"
}
```
### Local hide and restore
```json theme={null}
{"thread_id": "123", "hidden_local": true}
```
```json theme={null}
{"thread_id": "123", "restored_local": true}
```
Rename returns `thread_id`, `title`, and `backend`. Interrupt returns
`thread_id` and `interrupted: true`. App listing returns an `apps` array whose
rows contain `name`, `bundle_id`, and `uuid`. JSON failures contain `backend`,
`device`, `status`, and `error` when those values are available.
## Exit codes
| Code | Meaning |
| - | - |
| `0` | Success |
| `1` | Connection, authentication, runtime, or agent error |
| `2` | Invalid input/selection or an unsupported `--app` request |
| `3` | A setup, OAuth, or action interaction must be completed in a supported client |
| `75` | The completion fence was lost; durable output may be partial |
| `124` | The opt-in timeout expired and interruption was requested |
| `130` | The turn or process was interrupted |
If exit code `75` is returned, do not retry or resend automatically. Durable
output was retained, but the lost completion fence means the caller cannot
prove that the original turn finished.
## Compatibility aliases and Task cutoff
`--task-id`, `--list-tasks`, `/tasks`, and the `task_id` JSON key are
one-release compatibility aliases. Their values are decimal Convo thread IDs;
they do not expose the retired Task backend. `/resume` and `/switch` are also
temporary interactive spellings for the Convo thread picker.
A legacy Task UUID fails with this migration error:
```text theme={null}
legacy Task chats are not available after the Convo cutover; --thread-id/--task-id requires a decimal Convo thread id
```
Convo has no per-thread app allowlist. `--app` and dynamic `/` requests
fail, interactive `/apps` does not exist, and no app is attached or restricted.
Use `truffile convo --list-apps` or `truffile list apps` for discovery only.
## Safe follow-ups
Only chain a follow-up after the opening command exits successfully:
```bash theme={null}
response="$(truffile convo --new --json --quiet --timeout 120 "first question")"
thread_id="$(printf '%s' "$response" | jq -r .thread_id)"
truffile convo --thread-id "$thread_id" --json --quiet --timeout 120 \
"follow-up question"
```
# Deploying and managing apps
Source: https://docs.truffle.net/sdk/deployment
Install app bundles, update code, reconnect accounts, and control permissions with Truffile
These commands are available in Truffile 0.3.35 and later. Upgrade with
`python -m pip install --upgrade truffile`.
Normal `deploy` uploads the original bundle to firmware's native installer.
Firmware uses its existing builder containers to run the install plan. The CLI
handles progress, uploads, setup forms, and browser authorization. It does not
reimplement connection isolation or rewrite the manifest into a legacy plan.
```bash theme={null}
truffile connect 6272
truffile validate ./my-app
truffile deploy ./my-app
truffile deploy ./my-app --update
truffile deploy ./my-app --replace
```
`deploy` accepts a directory containing `truffile.yaml` or a `.truffle` ZIP.
For a directory, files are packaged with stable ordering/timestamps. `.git`,
virtual environments, Python caches, `.env`/`.env.*`, and existing `.truffle`
archives are excluded. `.truffleignore` supports relative glob patterns and
directory prefixes, one per line. Symlinks, escaping archive paths and duplicate
archive entries are rejected. Bundles are limited to 200 MiB expanded.
`validate` and `deploy --dry-run` perform local bundle preflight. The manifest
is passed through unchanged: firmware performs full schema and install-plan
validation, including connection scopes, connectors, static resources, base
image, and resource profile. A preflight pass is not proof that a particular
firmware supports every declared feature.
## Install, update, replace
| Command | Meaning |
| - | - |
| `deploy ./app` | Fresh installation. An existing matching bundle ID requires an explicit update or replace choice. |
| `deploy ./app --update` | Rebuild and publish code through firmware's existing developer update path, preserving installed account identities and setup. |
| `deploy ./app --replace` | Use the native reset path with the uploaded bundle; run fresh setup and replace the old accounts. The CLI confirms this reset. |
| `deploy ./app --replace --yes` | Explicitly confirm replacement for automation. |
Both update and replacement require the PyFW developer-upload capability
available on current firmware. The CLI checks support
using a read-only request **before** starting either mutation. Older firmware
gets an upgrade-required error. It never falls back to deleting the app or to
a catalog reset. The server retains its existing behavior for older clients.
Successful CLI deployment verifies the installed bundle hash after completion.
Keep the same `metadata.bundle_id` when updating an installed app.
The direct builder remains available for development/debugging:
```bash theme={null}
truffile deploy ./legacy-app --legacy-builder
truffile deploy ./legacy-app --interactive
truffile validate ./legacy-app --legacy-builder
```
`--interactive` opens the legacy builder shell. Normal native deployment already
prompts for account setup; it does not need that flag. Direct builder deployment
supports the older schema and fresh bundle IDs only. Use normal deployment for
modern manifests, updates and replacements.
## Accounts and permissions
Friendly app names, bundle IDs and UUIDs are accepted. Account aliases and UUIDs
are accepted too. If a name is ambiguous, the terminal shows matching choices.
```bash theme={null}
truffile connections list Google
truffile connections add Google
truffile connections reconnect Google
truffile connections delete Google
truffile connections rename Google Work
truffile connections permissions Google read-only
```
For reconnect/delete/rename/permissions, omitting the account opens a numbered
picker. The rename example chooses an account and names it `Work`; the permission
example chooses an account and makes it read-only. To select directly:
```bash theme={null}
truffile connections reconnect Google "work@example.com"
truffile connections rename Google "work@example.com" Work
truffile connections permissions Google Work auto-review --notes "Review external writes"
truffile connections delete Google Work --yes
```
Deletion asks for confirmation unless `--yes` is provided. Scripts must provide
an unambiguous account and `--yes` for deletion. `--json` and `--non-interactive`
never open a picker or prompt. No selection silently means “all accounts.”
Permission modes are `default`, `read-only`, `read-write`, and `auto-review`.
`default` removes the account override so device policy applies. Omitted
`--notes` preserves the current review notes. These commands do not alter
device-wide defaults or grant an app permission automatically.
## Authentication
Native text/password forms, including API-key setup, are rendered in the
terminal. Password inputs are hidden. For automation, supply a JSON map of
field names to string values:
```bash theme={null}
truffile deploy ./app --non-interactive --json --answers-file /private/setup.json
truffile connections add "My App" --json --answers-file /private/second-account.json
```
Keep answer files outside the source tree. The explicitly supplied answer file
is excluded from directory uploads even if it is inside the tree. Never include
credentials in a prebuilt bundle. Field keys can be `name` or `step_index.name`
when separate steps use the same field name. Supplied values are not printed.
For OAuth, the CLI shows the authorization URL and accepts a callback URL or
provider approval code. URL callbacks must match the pending state. On POSIX,
firmware-provided localhost callbacks can complete automatically; pasting is
also available when the browser is on another computer or the port is busy.
Browser/VNC setup cards show the device setup URL and follow the card's completion
behavior. Native device-code approval displays the link and waits for the
provider process to finish without asking for a callback paste.
Provider-specific consent, token refresh and custom setup still run
through the firmware install plan, not through a new CLI token store.
Interactive authorization is not silently completed in JSON/noninteractive
mode. Missing input returns an interaction-required error and requests
cancellation. Rerun interactively or supply form answers as appropriate.
`--timeout` defaults to 900 seconds for install/add/reconnect. A timeout or
disconnect is not permission to retry blindly: cancellation is requested, but
the operation may already have committed. Inspect the app before retrying.
The device can expire sign-in before the CLI's deadline; increasing `--timeout`
does not extend that authorization window. The CLI continues receiving device
responses while prompting, closes stale prompts/callback listeners on expiry or
disconnect, and reports the device's error. An expired setup needs a new sign-in
link.
Mutations are serialized on firmware, so an immediate follow-up command can
report that another operation is still finishing.
# Build a Foreground App
Source: https://docs.truffle.net/sdk/focus-app
Expose MCP tools the Truffle agent can call on demand
Foreground apps are MCP servers that give the Truffle agent callable tools. You subclass `ForegroundApp`, register tools with a decorator, and call `app.run()`.
> [!NOTE]
>
> Foreground apps serve MCP over **streamable HTTP**. `stdio` transport is not supported for deployed apps.
>
> If you're new to MCP, start with the [protocol docs](https://modelcontextprotocol.io/docs).
***
## Foreground patterns in the examples
There are two common ways to build a foreground app:
| Pattern | Use it when | Examples |
| - | - | - |
| Native `ForegroundApp` | You own the tool functions and can shape inputs/outputs directly. | `arxiv`, `exa`, `home-assistant`, `obsidian`, `whoop` |
| Remote MCP wrapper/proxy | An upstream MCP server already exists, but you need auth, metadata cleanup, argument normalization, safety checks, or compact result formatting. | `notion`, `viator` |
Prefer the native `ForegroundApp` pattern when you are writing the integration yourself. Use the remote MCP wrapper pattern when porting an existing MCP server or when the provider hosts an MCP endpoint.
***
## Minimal example
A complete, working foreground app that exposes one tool:
```python theme={null}
# my_app_foreground.py
from __future__ import annotations
import atexit
import httpx
from mcp.types import CallToolResult, TextContent
from truffile.app_runtime import ForegroundApp, ToolSpec, err
class MyApp(ForegroundApp):
def __init__(self) -> None:
super().__init__("myapp", logger_name="myapp.foreground")
self._http = httpx.AsyncClient(timeout=30.0)
self._register_tools()
def _register_tools(self) -> None:
@self.tool(
ToolSpec(
name="search_web",
description=(
"Search the web and return the top results. "
"Use this when the user asks about current events or recent information."
),
icon="magnifying-glass",
annotations={"readOnlyHint": True, "destructiveHint": False},
)
)
async def search_web(query: str, limit: int = 5) -> CallToolResult | dict:
"""Search the web for `query` and return up to `limit` results."""
if not query.strip():
return err("query is required")
limit = max(1, min(limit, 20))
try:
response = await self._http.get(
"https://api.example.com/search",
params={"q": query, "n": limit},
)
response.raise_for_status()
results = response.json().get("results", [])[:limit]
lines = [f"### Search results for `{query}`"]
for i, item in enumerate(results, 1):
title = item.get("title", "Untitled")
url = item.get("url", "")
snippet = item.get("snippet", "")
lines.append(f"- [{i}] {title} — {url}")
if snippet:
lines.append(f" {snippet[:240]}")
return CallToolResult(
content=[TextContent(type="text", text="\n".join(lines))],
structuredContent={
"query": query,
"results": [
{
"title": item.get("title", ""),
"url": item.get("url", ""),
}
for item in results
],
},
)
except httpx.HTTPStatusError as exc:
return err(f"HTTP {exc.response.status_code}", status_code=exc.response.status_code)
async def aclose(self) -> None:
await self._http.aclose()
app = MyApp()
def _cleanup() -> None:
try:
import asyncio
asyncio.run(app.aclose())
except Exception:
pass
atexit.register(_cleanup)
if __name__ == "__main__":
app.run()
```
That's the whole pattern. The rest of this page explains each piece.
***
## The `ForegroundApp` class
Subclass `ForegroundApp` and call `super().__init__(name, logger_name=...)`. The constructor sets up the MCP server machinery, your logger (`self.logger`), and the internal tool registry.
```python theme={null}
class MyApp(ForegroundApp):
def __init__(self) -> None:
super().__init__("myapp", logger_name="myapp.foreground")
```
* `name` — a short identifier for your app, used in MCP server metadata.
* `logger_name` — optional; defaults to the app name. Use a namespaced logger so your logs are distinguishable in the runtime.
***
## Registering tools
Tools are async functions registered via the `@self.tool(...)` decorator. The decorator takes a `ToolSpec` with the tool's name, description, and icon:
```python theme={null}
from truffile.app_runtime import ToolSpec
@self.tool(
ToolSpec(
name="get_repo",
description=(
"Fetch a GitHub repository's metadata by owner and repo name. "
"Returns stars, default branch, and description."
),
icon="github-logo",
annotations={"readOnlyHint": True, "destructiveHint": False},
)
)
async def get_repo(owner: str, repo: str) -> dict:
...
```
**Fields on `ToolSpec`:**
| Field | Meaning |
| - | - |
| `name` | The tool name the model sees. Use `snake_case`. |
| `description` | Plain English. The model uses this to decide when to call the tool — make it explicit. |
| `icon` | Either a full URL or a [Phosphor icon name](https://phosphoricons.com/) (e.g. `"search"`, `"github-logo"`). |
| `title` | Optional human-readable label. Defaults to `name`. |
| `annotations` | Optional MCP annotations. Use `{"readOnlyHint": True}` for read-only tools and `{"destructiveHint": True}` for tools that delete, send, purchase, publish, or otherwise mutate important state. |
| `structured_output` | Optional FastMCP structured-output flag. Most apps can leave this unset. |
### Icons
Passing a name like `"search"` is equivalent to calling `phosphor_icon_url("search")` — the SDK turns it into a Phosphor SVG URL. If you want a custom icon, pass the full URL instead:
```python theme={null}
ToolSpec(name="...", description="...", icon="https://example.com/icons/myicon.svg")
```
### Type hints are your tool schema
The tool function's **type hints** become the MCP tool's input schema. Keep them concrete:
```python theme={null}
async def search(query: str, limit: int = 5, include_archived: bool = False) -> dict:
...
```
Supported types: `str`, `int`, `float`, `bool`, `list[...]`, `dict[...]`, `Optional[...]`. Give every parameter a sensible default where possible — the model can call the tool with fewer arguments if you do.
***
## Wrapping a remote MCP server
Some apps are mostly adapters around another MCP server. The wrapper still matters because it is where you make the provider useful and safe for the Truffle agent:
* add or override tool titles, descriptions, icons, and annotations
* normalize provider-specific argument names into model-friendly arguments
* strip debug-only fields from tool results
* convert verbose provider JSON into compact markdown plus small `structuredContent`
* report auth/runtime errors through Truffle's app error path
The `notion` example is a remote MCP proxy with OAuth:
```python theme={null}
class NotionForegroundApp:
def list_tools(self) -> list[dict[str, Any]]:
client = self.get_client()
tools = client.list_mcp_tools()
return [_enrich_tool_metadata(tool) for tool in tools]
async def invoke_tool(self, name: str, **arguments: Any) -> Any:
try:
return self.get_client().call_tool(name, arguments)
except Exception as exc:
await self._error_reporter.report_foreground_exception(exc, tool_name=name)
raise
```
The `viator` example goes further: it wraps a remote MCP server, overrides the two public tool schemas, adds local arguments like `include_raw`, and formats compact travel-search results before returning them.
Use this pattern when an upstream MCP is already good enough to call, but not good enough to expose raw.
***
## Returning results
For simple action tools, returning a small dict with `ok()` / `err()` is fine:
```python theme={null}
from truffile.app_runtime import ok, err
return ok("Created draft", draft_id=draft_id)
return err("Rate limit exceeded", retry_after=60)
```
For read tools that can return many rows, prefer an MCP `CallToolResult` with:
* concise markdown in `content`, optimized for the model to read
* small `structuredContent`, only for IDs or fields the model may need for follow-up calls
* no duplicated status/tool-name fields
* no raw provider payloads unless the user explicitly asks for a detailed/debug view
```python theme={null}
from mcp.types import CallToolResult, TextContent
return CallToolResult(
content=[TextContent(type="text", text="### Issues\n- [1] #42 Fix deploy cleanup")],
structuredContent={
"issues": [{"ref": 1, "number": 42, "id": "I_kw..."}],
},
)
```
Plain dict returns are serialized as JSON for the model. That is convenient,
but it gets token-expensive when the dict is large. If a tool returns lists,
messages, search results, documents, or other verbose records, write a compact
text summary yourself.
For remote MCP wrappers, keep the same rule: forward the provider result only when it is already compact. Otherwise, build the model-facing text yourself and keep `structuredContent` to stable IDs, refs, pagination, or fields required for follow-up calls.
***
## Error handling
For errors you expect (bad inputs, HTTP failures, rate limits), return `err(...)`. For authentication failures — where the user needs to reinstall or refresh credentials — raise `AppAuthError`:
```python theme={null}
from truffile.app_runtime import AppAuthError, AppRuntimeFailure, err
async def list_issues(owner: str, repo: str) -> dict:
try:
response = await self._http.get(f"/repos/{owner}/{repo}/issues")
response.raise_for_status()
return ok("Listed issues", issues=response.json())
except httpx.HTTPStatusError as exc:
if exc.response.status_code in (401, 403):
raise AppAuthError("GitHub token is invalid or lacks permissions") from exc
return err(f"GitHub returned HTTP {exc.response.status_code}")
except httpx.HTTPError as exc:
raise AppRuntimeFailure(f"GitHub request failed: {exc}") from exc
```
* **`AppAuthError`** — the runtime classifies this as an auth problem and flags the app as needing user intervention. Use it for 401/403 responses, expired tokens, or missing credentials.
* **`AppRuntimeFailure`** — for generic runtime issues you want to propagate instead of returning as a soft error.
* **Returning `err(...)`** — for expected errors the agent should see and potentially recover from (bad user input, rate limits, upstream 5xx, etc.).
***
## Tool design guidance
A few things we've learned from building the reference apps:
1. **Validate inputs early.** If the caller passes `limit=99999`, clamp it. If an enum arg is invalid, return `err(...)` with the valid values.
2. **Optimize result text for the model.** For read tools, concise markdown beats raw provider JSON. Keep structured payloads small and action-oriented.
3. **Write descriptions the model can route on.** "Search X for Y. Use this when Z." Describe *when* to use the tool, not just *what* it does.
4. **Keep one concept per tool.** `get_market` and `create_order` are better than a single `market_op` with a `mode` arg.
5. **Name parameters clearly.** `ticker` not `t`, `include_text` not `text`.
***
## Testing with `truffile infer`
You can point the inference REPL at your local MCP server and exercise it end-to-end before deploying.
1. Start your app locally:
```bash theme={null}
python my_app_foreground.py
```
It'll listen on `http://127.0.0.1:8000/mcp` by default.
2. In another terminal, open the infer REPL:
```bash theme={null}
truffile infer
```
3. Connect to your MCP server and list the tools:
```
> /mcp connect http://127.0.0.1:8000/mcp
/mcp connect ✓ http://127.0.0.1:8000/mcp (2 tools)
> /mcp tools
/mcp tools search_web, get_repo
```
4. Run a real prompt that should trigger one of your tools:
```
> use the search_web tool to find recent news about SpaceX
```
This is the fastest way to check that your tool descriptions actually route correctly before you deploy.
> [!WARNING]
>
> Never commit real API keys in docs, screenshots, logs, or recordings.
***
## Cleanup on shutdown
Close any HTTP clients, database connections, or subprocesses on exit:
```python theme={null}
import atexit
def _cleanup() -> None:
try:
# close sync clients directly, async clients via asyncio.run
client.close()
except Exception:
pass
atexit.register(_cleanup)
```
Skipping this is the #1 cause of flaky redeploys and container runtime crashes.
***
## Deploy
```bash theme={null}
truffile validate ./my-app
truffile deploy --dry-run ./my-app
truffile deploy ./my-app
```
After deployment, send a one-shot Convo smoke request:
```bash theme={null}
truffile convo --new --json --quiet --timeout 120 \
"Use and summarize the result"
```
Inspect `tool_calls` in the JSON result. The model may discover the installed
tool through normal routing, but Convo cannot attach or restrict an app per
chat, so this is not deterministic enforcement. Before deployment, use
`truffile infer --mcp ` when you need to select and test the local MCP
server directly.
***
## When to build a foreground app
Build a foreground app when you need:
* **Request/response tools** the agent calls during a Convo request (search, fetch, lookup, CRUD operations)
* **Deterministic API integrations** the model should reach for in specific situations
* **Action-style behaviors** (post, create, cancel, trigger)
If instead you want something that runs on a schedule and feeds context to the agent *without* the user asking, you want a [background app](/sdk/ambient-app) — or a hybrid app that has both.
# Inference API
Source: https://docs.truffle.net/sdk/inference
Use the Truffle inference HTTP endpoints directly for model listing and chat completions
Your Truffle exposes an OpenAI-compatible inference API at `/if2/v1/*`. You can use it via the CLI or call the HTTP endpoints directly.
> [!NOTE]
>
> For the interactive CLI experience (`truffile infer`), see the [CLI guide](/sdk/cli#infer-mode). This page covers the raw HTTP endpoints.
***
## List Models
```bash theme={null}
curl -sS http:///if2/v1/models | python -m json.tool
```
Or via the CLI:
```bash theme={null}
truffile models
```
***
## Chat Completions
```bash theme={null}
curl -sS http:///if2/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"model": "",
"messages": [
{"role": "user", "content": "Give me one sentence about Truffle."}
]
}'
```
### Request body
| Field | Type | Description |
| - | - | - |
| `model` | `string` | Model ID or UUID (from `/models`) |
| `messages` | `array` | Conversation messages (`role` + `content`) |
| `stream` | `bool` | Stream response tokens via SSE (default `false`) |
| `max_tokens` | `int` | Maximum output tokens |
| `temperature` | `float` | Sampling temperature |
| `top_p` | `float` | Nucleus sampling parameter |
| `reasoning` | `object` | `{"enabled": true}` to enable reasoning output |
| `tools` | `array` | OpenAI-format tool definitions |
| `tool_choice` | `string` | `"auto"` to let the model decide |
### Streaming
Set `"stream": true` and optionally `"stream_options": {"include_usage": true}` to get token usage in the final event.
The response is an SSE stream of `data: {...}` lines, terminated by `data: [DONE]`.
Each event contains a `choices[0].delta` object with incremental `content`, `reasoning`, and/or `tool_calls`.
### Image input
Pass images as part of a message's `content` array:
```json theme={null}
{
"role": "user",
"content": [
{"type": "text", "text": "What is in this image?"},
{"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}}
]
}
```
Supported image types: `image/jpeg`, `image/png`, `image/bmp`.
***
## MCP Testing with the CLI
`truffile infer` doubles as an MCP test harness. Start your MCP server locally, then:
```
truffile infer
> /mcp connect http://127.0.0.1:8000/mcp
> /mcp tools
> use the get_markets tool to show me current markets
```
See the [CLI guide](/sdk/cli#mcp-integration) for full details.
# Install Steps Reference
Source: https://docs.truffle.net/sdk/install-steps
Every supported install step in truffile.yaml
Install steps run on the device, in order, when `truffile deploy` builds your app. They're declared under the top-level `steps:` array in `truffile.yaml`:
```yaml theme={null}
steps:
- name: Install dependencies
type: bash
run: |
pip install --no-cache-dir httpx
- name: Copy app files
type: files
files:
- source: ./my_app_foreground.py
destination: ./my_app_foreground.py
- name: Configure
type: text
fields:
- name: api_key
label: API Key
type: password
env: MY_APP_API_KEY
```
Common native steps are **`bash`**, **`files`**, **`text`**, **`oauth`**, and
**`welcome`**. Firmware also supports provider-specific browser/VNC setup plans.
Normal deployment uploads the original manifest and lets firmware validate it.
> [!NOTE]
>
> For new authenticated apps, use connection-scoped setup and credentials. See
> [accounts and authentication](/sdk/accounts). Normal CLI deployment relays
> forms and OAuth callbacks to firmware; firmware performs token exchange and
> storage. The explicit `--legacy-builder` path retains older token-file recipes.
## Installation scope and account scope
Use `truffile_version: 4` for a process-based account-aware manifest, or version
5 for a native connector. Declare `connections: multi` when the app supports
multiple accounts. Mark shared dependencies/files with `scope: install`, and
authentication/configuration with `scope: connection`. The connection plan runs
for first setup, adding an account, and reconnecting an account.
An uploaded `--update` preserves existing accounts. Keep credentials out of
install-scoped files and app-global variables. Legacy `update_policy` and
`update_check` examples below describe older recipes; do not substitute them
for connection scope in a new multi-account app.
***
## Step ordering
Steps execute top-to-bottom. The practical rules:
1. **Install dependencies before anything that needs them.** Put your `bash` step that runs `pip install` early.
2. **Copy files before running them.** Any `bash` step or `text` validator that invokes a Python file needs a preceding `files` step that uploads it.
3. **Collect credentials after files are in place.** `text` validators and OAuth verify steps typically call one of your own Python scripts, so those scripts must already be on disk.
4. **Verify OAuth after the OAuth step.** Put a `bash` step after `oauth` that calls `python ./foreground.py --verify` and any background verify script.
A safe default order: `bash` (dependencies) → `files` (copy scripts) → `text` or `oauth` (credentials) → `bash` (verify/finalize).
### Common step fields
Most examples also use these optional fields:
| Field | Applies to | Description |
| - | - | - |
| `update_policy` | all steps | When the step should run on update. Examples use `run_on_update` for steps that should repeat when the app is updated. |
| `update_check` | auth/config steps | Command used to decide whether existing auth/config is still valid before asking again. |
| `ui_state_on_show` | interactive steps | UI state to surface when the step needs user input, often `user_interaction_ready`. |
| `ui_state_on_complete` | interactive steps | UI state after completion, often `move_to_background`. |
***
## `bash`
Runs a shell command inside the app's build container. Use it for installing dependencies, creating directories, pre-warming caches, etc.
```yaml theme={null}
- name: Install dependencies
type: bash
run: |
apk add --no-cache gcc musl-dev libffi-dev openssl-dev
pip install --no-cache-dir "httpx>=0.27.0" "cryptography>=42.0.0"
```
### Options
| Field | Required | Description |
| - | - | - |
| `name` | no | Display label shown while the step runs. Defaults to `"bash"`. |
| `type` | yes | Must be `"bash"`. |
| `run` | yes | Shell command to execute. Use a YAML block scalar (`\|`) for multi-line scripts. |
### Exit codes
If the command exits non-zero, the deploy aborts and the step is reported as failed:
```
✗ Step 'Install dependencies' failed with exit code 1
```
There's no retry. Write commands that are idempotent and handle their own errors — e.g. `mkdir -p` instead of `mkdir`, `pip install --no-cache-dir` instead of rebuilding caches.
### The container environment
The base image is Alpine-based (`apk` is the package manager, not `apt`). Python is preinstalled. Commands run with the working directory set to the app's exec directory (usually `/`).
> [!TIP]
>
> You can open a shell in the container mid-deploy to experiment with commands before codifying them. Run `truffile deploy --interactive ` — after your steps finish, you get an interactive shell inside the same container. Type `exit` or Ctrl+D to finalize the deploy.
***
## `files`
Uploads files from your app directory into the build container.
```yaml theme={null}
- name: Copy app files
type: files
files:
- source: ./config.py
destination: ./config.py
- source: ./auth.py
destination: ./auth.py
- source: ./my_app_foreground.py
destination: ./my_app_foreground.py
```
### Options
| Field | Required | Description |
| - | - | - |
| `name` | no | Display label. |
| `type` | yes | Must be `"files"`. |
| `files` | yes | A list of file entries. |
Each entry in `files`:
| Field | Required | Description |
| - | - | - |
| `source` | yes | Path relative to your app directory. Can be a file or a directory. |
| `destination` | yes | Path in the container (usually relative to the exec cwd). |
### File vs directory
If `source` points to a file, it's uploaded to `destination`.
If `source` points to a **directory**, every file inside it is uploaded recursively. `__pycache__` directories are skipped automatically. The `destination` is treated as a destination directory, and files are placed underneath it preserving the relative structure:
```yaml theme={null}
- name: Copy skills
type: files
files:
- source: ./skills/
destination: ./skills/
```
This uploads `./skills/foo.py` → `./skills/foo.py`, `./skills/subdir/bar.py` → `./skills/subdir/bar.py`, and so on.
### Missing files
If `source` doesn't exist, deploy fails immediately:
```
FileNotFoundError: no such file: /path/to/my-app/missing.py
```
`truffile validate` catches this before you even try to deploy — it resolves every `source` against the app directory and errors if anything is missing.
***
## `text`
Prompts the user for one or more values during deploy, stores them as environment variables on your foreground/background processes, and optionally runs a validator command to verify the inputs immediately.
Use `text` for API keys, access tokens, and other credentials the user can paste directly. Use `oauth` when the provider needs a browser authorization flow.
```yaml theme={null}
- name: Configure GitHub access token
type: text
content: |
Enter a GitHub personal access token so Truffle can talk to GitHub on your behalf.
To create one:
1. Go to https://github.com/settings/tokens
2. Click **Generate new token**
3. Select the scopes you want (recommended: `repo`, `read:org`, `gist`)
4. Copy the token and paste it below
fields:
- name: github_access_token
label: GitHub Access Token
type: password
placeholder: ghp_...
env: GITHUB_ACCESS_TOKEN
validator:
type: bash
run: |
python ./github_foreground.py --verify
error_message: |
Could not verify GITHUB_ACCESS_TOKEN. Check the token is valid and has the required scopes.
```
### Top-level options
| Field | Required | Description |
| - | - | - |
| `name` | no | Display label shown before prompting. |
| `type` | yes | Must be `"text"`. |
| `content` | no | Markdown-ish text shown to the user before the field prompts. Use a block scalar (`\|`) for multi-line content. |
| `fields` | yes | List of input fields. |
| `validator` | no | Optional bash command that runs after all fields are collected. |
### Field options
Each entry in `fields`:
| Field | Required | Description |
| - | - | - |
| `name` | yes | Internal field name. |
| `label` | no | Label shown to the user. Falls back to `name` if omitted. |
| `type` | no | `"text"` (default) or `"password"`. `password` hides input as the user types. |
| `placeholder` | no | Hint shown in parentheses in the prompt, e.g. `API Key (sk_...)`. |
| `default` | no | Value used if the user presses Enter without typing anything. |
| `env` | yes | The environment variable name that receives the collected value. Must match what your app reads via `os.getenv(...)`. |
The value the user enters is exposed to your foreground and background processes via the env var named in `env`. The injection happens at the process level — by the time your Python code runs, `os.getenv("GITHUB_ACCESS_TOKEN")` returns the token the user entered.
### Validator options
The validator runs a bash command *after* all fields are collected, with the collected values already set in the environment. If the command exits non-zero, install fails with your `error_message`.
| Field | Required | Description |
| - | - | - |
| `type` | yes | Must be `"bash"`. |
| `run` | yes | Shell command. Typically calls `python ./your_script.py --verify`. |
| `error_message` | no | Message shown to the user when the validator exits non-zero. |
The env vars from your `fields` are prepended to the command, so `python ./foo.py --verify` runs with `MY_API_KEY='whatever the user typed'` already set.
> [!TIP]
>
> The standard pattern is to add a `--verify` flag to your foreground or background script and call it from the validator. The `BackgroundWorkerApp.main()` entry point handles `--verify` automatically — it calls `verify_worker()`, prints the result, and exits 0 or 1. For foreground apps you wire it up yourself with `argparse`.
### Single-field example
```yaml theme={null}
- name: Configure Exa API key
type: text
content: |
Enter your Exa API key.
Get one at https://dashboard.exa.ai/onboarding.
fields:
- name: exa_api_key
label: Exa API Key
type: password
placeholder: exa_...
env: EXA_API_KEY
validator:
type: bash
run: |
python ./exa_foreground.py --verify
error_message: |
Could not verify EXA_API_KEY. Confirm the key is valid and has access.
```
### Multi-field example
Multiple fields in a single step are all prompted in order, then a single validator runs with all values in the environment:
```yaml theme={null}
- name: Configure Kalshi API credentials
type: text
content: |
Enter your Kalshi API credentials.
Create an API key at https://kalshi.com/account/profile and paste both
the key and the private key PEM below.
fields:
- name: kalshi_api_key
label: Kalshi API Key
type: password
placeholder: 00000000-0000-0000-0000-000000000000
env: KALSHI_API_KEY
- name: kalshi_private_key
label: Kalshi Private Key (PEM)
type: password
placeholder: -----BEGIN PRIVATE KEY-----
env: KALSHI_PRIVATE_KEY
validator:
type: bash
run: |
python ./kalshi_background.py --verify
error_message: |
Could not verify Kalshi credentials. Check both the API key and private key are correct.
```
### Text field with a default
```yaml theme={null}
- name: Configure IMAP server
type: text
fields:
- name: imap_server
label: IMAP Server
type: text
placeholder: imap.gmail.com
default: imap.gmail.com
env: IMAP_SERVER
```
If the user just presses Enter, the value is `imap.gmail.com`.
***
## How env vars reach your process
Values collected by `text` steps are injected into your foreground/background processes *on top of* whatever's already in the `environment:` block under `metadata.foreground.process` or `metadata.background.process`.
For example, this yaml:
```yaml theme={null}
metadata:
foreground:
process:
cmd: ["python", "my_app_foreground.py"]
environment:
PYTHONUNBUFFERED: "1"
steps:
- type: text
fields:
- name: api_key
type: password
env: MY_APP_API_KEY
```
results in a process that sees both `PYTHONUNBUFFERED=1` *and* `MY_APP_API_KEY=` in its environment. You read the user-supplied value the same way as any other env var:
```python theme={null}
import os
api_key = os.getenv("MY_APP_API_KEY", "").strip()
if not api_key:
raise RuntimeError("MY_APP_API_KEY is not set")
```
***
## `oauth`
Runs OAuth authorization for the connection being configured. Firmware stores
native token state for that connection. Older process-based recipes also use a
token file in the app container. Use it when the provider requires browser authorization instead of a pasted API key.
There are two real patterns in the bundled examples:
* **Standard OAuth**: fixed authorization/token endpoints and client metadata, like `whoop`.
* **Remote MCP OAuth**: an MCP server exposes protected-resource metadata or uses dynamic client registration, like `notion`.
### Standard OAuth example
```yaml theme={null}
- name: WHOOP OAuth Sign-In
type: oauth
update_policy: run_on_update
update_check: python ./foreground.py --verify
provider: Whoop
description: Sign in to WHOOP to connect profile, recovery, sleep, and workout data.
client_id: your-client-id
client_secret_env: null
redirect_uri: https://truffle.net/api/oauth/callback
auth_endpoint: https://api.example.com/oauth/authorize
token_endpoint: https://api.example.com/oauth/token
scopes:
- offline
- read:profile
token_output_file: /root/.my-app/oauth.json
token_file_env_name: MY_APP_TOKEN_FILE
app_var_key: oauth_state
```
### Remote MCP OAuth example
```yaml theme={null}
- name: Notion OAuth Sign-In
type: oauth
update_policy: run_on_update
update_check: python ./notion_foreground.py --verify
provider: Notion
description: Sign in to Notion to connect your workspace through Notion MCP.
redirect_uri: https://truffle.net/api/oauth/callback
scopes: []
dynamic_client_registration: true
resource_metadata_endpoint: https://mcp.notion.com/.well-known/oauth-protected-resource
oauth_resource: https://mcp.notion.com
client_name: Truffle
auth_endpoint: https://mcp.notion.com/authorize
token_endpoint: https://mcp.notion.com/token
client_id_env: NOTION_CLIENT_ID
client_secret_env: null
token_output_file: /root/.notion-oauth/tokens.json
token_file_env_name: NOTION_OAUTH_TOKEN_FILE
app_var_key: notion_oauth_state
```
### OAuth fields
| Field | Required | Description |
| - | - | - |
| `provider` | yes | Human-readable provider name shown during auth. |
| `description` | no | Short explanation shown to the user. |
| `redirect_uri` | yes | Callback URL registered with the provider. |
| `auth_endpoint` | yes | Provider authorization endpoint. |
| `token_endpoint` | yes | Provider token endpoint. |
| `scopes` | no | List of OAuth scopes. Use `[]` when the remote MCP server handles its own scope defaults. |
| `client_id` | usually | Static OAuth client ID. |
| `client_id_env` | alternative | Env var where a dynamically registered client ID is written/read. |
| `client_secret` | optional | Static client secret when the app owns one. |
| `client_secret_env` | optional | Env var for the client secret. Use `null` for public/DCR clients with no secret. |
| `dynamic_client_registration` | no | Set `true` for remote MCP OAuth providers that support DCR. |
| `resource_metadata_endpoint` | remote MCP | OAuth protected-resource metadata URL. |
| `oauth_resource` | remote MCP | Resource audience for the remote MCP server. |
| `client_name` | remote MCP | Client display name used during DCR. |
| `token_output_file` | legacy/process recipes | Optional token-file compatibility path; native connectors use connection-scoped token state. |
| `token_file_env_name` | with a token file | Env var exposed to a Python app with its token-file path. |
| `app_var_key` | native OAuth | Credential key within the selected connection; match the connector or runtime helper configuration. |
| `update_check` | no | Verify command to avoid unnecessary reauth when tokens still work. |
### App-side OAuth helper
In Python, subclass `OAuth` for normal providers or `RemoteMcpOAuth` for remote MCP providers. The token helper should load from the env var named by `token_file_env_name`, expose `get_oauth_payload()`, and provide a `--verify` path that exits non-zero when the token is missing or expired.
The `whoop` example uses `WhoopOAuth(OAuth)` and stores tokens at `WHOOP_TOKEN_STORE_PATH`. The `notion` example uses `NotionAuth(RemoteMcpOAuth)` and stores tokens at `NOTION_OAUTH_TOKEN_FILE`.
For public/dynamically registered remote MCP clients, the OAuth installer uses PKCE automatically when no client secret is available. Token JSON also includes refresh metadata such as `client_id`, `client_secret` when present, `redirect_uri`, `token_endpoint`, and `resource`, so app-side helpers can refresh later without needing separate env vars.
***
## `welcome`
Shows informational install content and requires no credentials. Use it when the app is ready to run after files are copied and optional verification has passed.
```yaml theme={null}
- name: Connect Viator
type: welcome
update_policy: run_on_update
ui_state_on_complete: move_to_background
content: |
Viator adds travel experience search and detail lookup tools.
No sign-in is required. Continue to finish installing the app.
```
The `viator` example uses this pattern after a `bash` verify step because its upstream MCP server does not require user auth.
***
## Validating before you deploy
Run `truffile validate ./my-app` and `truffile deploy ./my-app --dry-run` for
local bundle preflight. These check basic metadata, archive paths and packaging
limits; they do not reproduce firmware's complete schema validator or execute
provider checks. Run `python -m compileall -q ./my-app` for Python syntax and
your app's tests for client behavior. Firmware validates the full manifest and
install plan when you deploy.
For an older manifest that explicitly uses the direct builder,
`truffile validate ./my-app --legacy-builder` retains the older schema and
source checks. That validator does not support modern connector/browser plans.
# Installation
Source: https://docs.truffle.net/sdk/installation
Install the Truffile SDK to use Convo and deploy apps to your Truffle
## Prerequisites
* Python 3.12 or higher
* A Truffle¹ device
* The [Symphony desktop client](/client/overview), with your device already onboarded
## Agent setup prompt
If you want Codex, Claude Code, or another coding agent to set up Truffile for you, paste this prompt into the agent from the directory where you want the environment created:
```text theme={null}
Set up Truffile for me in this directory.
Use explicit CLI commands and explain what you are doing as you go.
Requirements:
- Make sure Python 3.12 or newer is available. Prefer `python3.12` when present; otherwise use the newest `python3`/`python` that is >=3.12.
- Prefer `uv` if it is installed. If `uv` is not installed, use the standard library `venv` module.
- Create a local virtual environment named `.venv`.
- Activate/use that virtual environment for all Python and pip commands.
- Install Truffile with `pip install truffile`; if it is already installed, make sure it is upgraded to the latest version.
- Verify the install with `truffile --help`.
- Run `truffile load all` so the bundled skills and example apps are copied into this workspace under `./truffile/skills` and `./truffile/examples`.
- Do not require a Truffle device to finish setup. If no device is connected yet, tell me that I first need to onboard my Truffle through the Symphony desktop client at https://docs.truffle.net/client/overview, then run `truffile scan` and `truffile connect `. During `truffile connect`, I can enter my User ID from Symphony Settings, then approve the new session on my Truffle device.
After `truffile load all`, inspect the local resources before giving me the onboarding:
- Read `./truffile/skills/truffile-cli/SKILL.md` for scan/connect/create/validate/deploy/list/delete/obsidian.
- Read `./truffile/skills/truffile-convo/SKILL.md` for the stateful on-device agent.
- Read `./truffile/skills/truffile-infer/SKILL.md` for raw model inference and MCP testing.
- Read `./truffile/skills/truffle-app-creator/SKILL.md` for creating or porting Truffle apps.
- Skim the example app manifests under `./truffile/examples/*/truffile.yaml` so you know the foreground, background, auth, and install-step patterns available.
- Run `truffile --help`, `truffile deploy --help`, `truffile convo --help`, and `truffile infer --help` so you know the CLI surface.
When setup is complete, give me a short onboarding that covers:
- that connecting requires a Symphony-onboarded Truffle, my User ID from Symphony Settings, and device approval during `truffile connect`
- how to connect a Truffle device
- how to use Convo with the on-device agent, including that old Task histories are not visible after the one-way cutover
- how to use Truffile as an inference endpoint/client
- how to create, validate, deploy, list, and delete apps
- where the copied skills and example apps live in this workspace
- links to the docs:
- https://docs.truffle.net/client/overview
- https://docs.truffle.net/sdk/installation
- https://docs.truffle.net/sdk/cli
- https://docs.truffle.net/sdk/convo
- https://docs.truffle.net/sdk/convo-automation
- https://docs.truffle.net/sdk/building-apps
- End by asking whether I want to start by making a Truffle app.
```
The prompt works because Truffile is CLI-first: every core workflow has explicit arguments, and `truffile load all` gives the agent local skills and example apps to read before it starts building.
## Install Python
> [tab] macOS
>
> ```bash theme={null}
> brew install python@3.12
> ```
>
> Verify:
>
> ```bash theme={null}
> python3 --version
> ```
> [tab] Windows
>
> Download and install Python from [python.org](https://www.python.org/downloads/), or use Chocolatey:
>
> ```powershell theme={null}
> choco install python --version=3.12.0
> ```
>
> Verify:
>
> ```powershell theme={null}
> python --version
> ```
> [tab] Linux
>
> ```bash theme={null}
> sudo apt update
> sudo apt install python3.12 python3.12-venv python3-pip
> ```
>
> Verify:
>
> ```bash theme={null}
> python3 --version
> ```
## Set up a virtual environment
> [tab] venv
>
> ```bash theme={null}
> python3 -m venv .venv
> ```
>
> > [tab] macOS / Linux
> >
> > ```bash theme={null}
> > source .venv/bin/activate
> > ```
>
> > [tab] Windows
> >
> > ```powershell theme={null}
> > .venv\Scripts\Activate.ps1
> > ```
> [tab] uv
>
> If you prefer [uv](https://github.com/astral-sh/uv) for faster package management:
>
> ```bash theme={null}
> # install uv if you don't have it
> curl -LsSf https://astral.sh/uv/install.sh | sh
>
> # create and activate a venv
> uv venv
> source .venv/bin/activate # macOS / Linux
> # or
> .venv\Scripts\Activate.ps1 # Windows
> ```
## Install Truffile
With your environment activated:
```bash theme={null}
python -m pip install --upgrade truffile
```
> [!NOTE]
>
> Before connecting from Truffile, onboard your device through the Symphony desktop client. Download Symphony from [the client overview](/client/overview) and complete device onboarding. When you run `truffile connect`, enter your User ID from Symphony Settings, then approve the new session on your Truffle device.
## Build and manage apps
Truffile 0.3.35 adds native installation, account setup, developer uploads, and
friendly account selection. Use current device firmware for uploaded updates
and replacements; unsupported firmware is detected before those operations.
```bash theme={null}
truffile connect 6272
truffile create my-app --path ./apps
truffile validate ./apps/my-app
truffile deploy ./apps/my-app
truffile deploy ./apps/my-app --update
```
Read [deployment](/sdk/deployment) and [accounts and authentication](/sdk/accounts)
for updates, replacement, OAuth, API keys, and permission controls. After upgrading,
refresh previously exported skills with `truffile load skills --force` only if
you intend to overwrite those exported copies; keep your app source separately.
## Next steps
> [card] [Start a Convo](/sdk/convo)
>
> Connect, open a Convo thread, and talk to the stateful on-device agent.
> [card] [Build your first app](/sdk/building-apps)
>
> Learn how Truffle apps are structured and scaffold one with `truffile create`.