# LatentStack documentation (full text) > LatentStack, by Latent Force Intelligence Private Limited, gives every team the superpower of AI: one secure deployment on infrastructure you own (your cloud, a GPU cloud provider, on-premises, or fully air-gapped), with your data never leaving your walls. Its gateway puts many LLMs behind one API, with access control, rate limits, an audit trail and content guardrails built in; LatentCode, LatentWork and hosted agents run through it. Index of pages: https://latentstack.dev/llms.txt --- # LatentStack documentation LatentStack gives your organization AI tools for coding and everyday work, all going through one gateway that your organization controls. ## What LatentStack is At its center is a gateway you run yourself. It routes requests to the model providers your administrator configures, enforces each organization's policy (which models people can use, rate limits, budgets and guardrails), and meters the tokens and cost of every request. Developers' machines never talk to a model provider directly. On top of the gateway, LatentStack gives you: ### LatentCode A coding agent for your terminal: an interactive TUI for day-to-day work and a CLI for scripts and automation. ### LatentWork A desktop app for everyone on the team, running agentic work on your own machine through the same gateway. ### Admin Console The web console. Admins manage members, tiers, teams, guardrails and providers; everyone gets their API key and sees their usage. ### Agents API Run LatentCode agents in hosted sandboxes from your own code, with TypeScript and Python SDKs. ### Quickstart From nothing to a first coding task and a first hosted agent in a few minutes. ## Get started ### Quickstart Get a key, install, run a task, run a hosted agent. ### Install What the installer puts where, its options, upgrading and uninstalling. ### Concepts Organizations, roles, keys, models, tiers, teams and usage. ## Popular tasks | I want to… | Go to | | --- | --- | | Set up a new machine | Install | | Find or rotate my API key | API keys | | Run an agent from my own code | Agents API quickstart | | Fix a 401, 403, 402 or 429 error | Error reference | | Understand which models I can use | Tiers | | Check what I have spent | My Usage | | Use LatentCode in a team or another organization | Teams | | Run an agent in the cloud | Agents API quickstart | | Remove LatentStack from a machine | Uninstall | ## How the pieces fit together ``` LatentCode LatentWork Agents API │ │ │ └───────────────┼───────────────┘ │ Authorization: Bearer ls-… ▼ LatentStack gateway (your server) key → organization, team, tier guardrails allowed models, rate limits, budgets, credits usage and cost metering │ ▼ model providers (Anthropic, OpenAI, Bedrock, …) ``` - You have one account and one personal API key, starting with `ls-`. Every product uses it. - The key tells the gateway who you are. Your organization and team decide your tier, which in turn decides the models you can use and your limits. - The gateway sends each request to the provider that serves the model, with credentials your administrator set up in the console. You never handle provider keys. - Every request is metered. You see your usage on My Usage; admins see the organization's in the console. ## Install One command installs LatentCode, LatentWork and the editor extension, all from this server: ``` curl -fsSL https://latentstack.dev/install.sh | bash ``` Then follow the Quickstart, or see Install for options. ## Get help Troubleshooting lists the errors you can get from the gateway, LatentCode, LatentWork and the console, with their causes and fixes. Source: https://latentstack.dev/docs --- # Quickstart Get an API key, install LatentCode, run your first coding task, then run a hosted agent from your own code. It takes a few minutes. ## Before you begin - A macOS, Linux or Windows machine where you can run a terminal. You don't need administrator rights. - The address of your LatentStack server. These docs are served from it: `https://latentstack.dev`. ## 1. Get your API key Everything in LatentStack authenticates with a personal API key that starts with `ls-`. You get one automatically when your account is created. - 01Sign in to the consoleOpen https://latentstack.dev/login and sign in with your email and password. If your administrator created your account, the welcome email has a temporary password. If you don't have an account yet, choose Sign up on the sign-in page, or accept the invitation your administrator sent you. - 02Copy your keyOpen the account menu at the top right and choose Account settings. In the API Key card, select Copy. If the card shows Generate API key instead, select it first. - 03Keep it in your shell for this session`export LS_API_KEY="ls-…"` Warning Treat the key like a password Anyone with your key can use models on your account, and the usage is charged to you. If it leaks, select Regenerate on the same card. The old key stops working immediately. ## 2. Install One command installs the LatentCode CLI, the LatentWork desktop app and the editor extension: ``` curl -fsSL https://latentstack.dev/install.sh | bash ``` The installer downloads everything from your server and points LatentCode at it. When it prints `Done.`, open a new terminal so the `latentcode` command is on your `PATH`. To install only the CLI, or for other options, see Install. ## 3. Connect LatentCode ``` latentcode config set api-key $LS_API_KEY ``` ``` ✓ API key saved → /home/you/.config/latentcode/latentcode.jsonc ✓ Imported 6 model(s) (tier: ) ``` LatentCode checks the key against the gateway and imports the models your tier allows. If you skip this step, LatentCode asks for the key the first time it starts. ## 4. Run your first task Go to a project folder and start LatentCode: Bash ``` cd ~/code/my-project latentcode ``` The terminal UI opens. Type a request at the prompt and press Enter, for example: ``` Explain what this project does and how it is organized. ``` LatentCode reads the files it needs and answers in the conversation. It can edit files in the project directly, and it asks before running most shell commands. You can also run one request without the UI and print the answer: ``` latentcode run "List the main entry points of this project" ``` `latentcode run` can't stop to ask you anything, so it declines any action that would need your permission, such as most shell commands, and prints a line saying so. Next, see LatentCode for the TUI, the CLI and configuration. ## 5. Run an agent from your own code The same key runs LatentCode agents in hosted sandboxes through the Agents API. Install the TypeScript or Python SDK, give an agent a task, and read what it did: Give a hosted agent a task ``` import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Answer briefly." }, input: "Write a Python script that prints the first 10 prime numbers, run it, and show me the output.", }) for await (const event of sessions.events(session.id)) { if (event.type === "tool.called") console.log("tool:", event.data?.tool) if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } const { last_seq } = await sessions.get(session.id) await sessions.message(session.id, "Now make it print the first 20.") for await (const event of sessions.events(session.id, { after: last_seq })) { if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } await sessions.delete(session.id) ``` The Agents API quickstart covers installing the SDK and running this end to end. Model calls made by agents show on your My Usage page like any other request. ## Next steps - Concepts: organizations, tiers, teams and how usage is counted. - LatentWork: set up the desktop app with the same key. - Agents API quickstart: run LatentCode agents in the cloud from your own code. Source: https://latentstack.dev/docs/quickstart --- # Install One command installs the LatentCode CLI, the LatentWork desktop app and the editor extension, all downloaded from your own LatentStack server. ## Quick install Run this in a terminal on the machine you want to set up. You don't need administrator rights. ``` curl -fsSL https://latentstack.dev/install.sh | bash ``` The commands on this page point at `https://latentstack.dev`, the server these docs are served from. The installer downloads everything from that same server, so nothing is fetched from a third party, and it sets that server as LatentCode's gateway. When it finishes, the installer prints a summary like this: ``` Done. Coding agent (terminal): latentcode Desktop app: LatentWork (in your app menu / Launchpad) Editor extension: LatentCode (VS Code / Cursor / VSCodium / Windsurf / code-server) Your gateway URL is already configured (https://latentstack.dev/v1). On first launch, just paste your API key — or set it now: latentcode config set api-key ls-your-key-here (from your account page) ``` Open a new terminal so the updated `PATH` takes effect, then continue with Connect to your gateway. ## What gets installed Each part is optional and installed independently. If one part fails, the installer warns and carries on. | Component | What it is | Skip it with | | --- | --- | --- | | latentcode | The LatentCode terminal agent: a single self-contained executable. Node.js and npm are not needed. | `--desktop-only` / `-DesktopOnly` | | LatentWork | The desktop app, with an app menu, Launchpad or Start Menu entry. | `--cli-only` / `-CliOnly` | | Editor extension | The LatentCode extension, installed into every supported editor found on the machine: VS Code, VS Code Insiders, VSCodium, Cursor, Windsurf and code-server. | `--no-vscode` / `-NoVscode` | | Skills | The built-in skills bundle. | `--no-skills` / `-NoSkills` | Note Your administrator may have narrowed the default A deployment can be set to install only the CLI, only the desktop app, or no editor extension. If the summary doesn't list a component, it was left out on purpose. ## Requirements | | macOS | Linux | Windows | | --- | --- | --- | --- | | latentcode | Apple silicon (arm64) or Intel (x64) | x64 or arm64 | x64 or arm64 | | LatentWork | .dmg build | Linux build | NSIS installer (.exe) build | | Tools used | curl (or wget), tar | curl (or wget), tar | PowerShell | - The installer picks the right build for your machine. - If your server doesn't offer a build for your machine, the installer says so and skips that component. Ask your administrator. - The desktop app step needs `curl` on macOS and Linux; with only `wget` installed, the CLI still installs but LatentWork is skipped. ## Where files go | Path | Contents | | --- | --- | | ~/.latentcode/bin/latentcode | The CLI | | ~/.latentcode/plugins/skills/ | Built-in skills | | ~/.latentcode/vscode/latentcode.vsix | The downloaded editor extension | | /Applications/LatentWork.app | The desktop app. If `/Applications` isn't writable, `~/Applications/LatentWork.app`. | | ~/.config/latentcode/latentcode.jsonc | LatentCode settings, including the gateway URL and API key | ### PATH On macOS and Linux, the installer adds `~/.latentcode/bin` to `PATH` in the startup file of your current shell: `~/.zshrc`, `~/.bashrc`, `~/.config/fish/config.fish`, or `~/.profile` for other shells. The line ends with `# added by LatentStack installer`. On Windows, it adds the folder to your user `Path`. ## Connect to your gateway The installer sets LatentCode's gateway URL to `https://latentstack.dev/v1`. The only thing left is your API key, which you copy from Account settings → API Key in the console (see Quickstart). Either paste it when LatentCode first starts, or set it now: ``` latentcode config set api-key ls-your-key ``` ``` ✓ API key saved → /home/you/.config/latentcode/latentcode.jsonc ✓ Imported 6 model(s) (tier: ) ``` Setting the key also imports the models your tier allows. If the installer printed `Gateway URL was NOT pre-configured`, set the URL first: ``` latentcode config set base-url https://latentstack.dev/v1 ``` LatentWork asks for its own connection on first launch. See LatentWork. ## Verify the install - 01Check the CLI is on your PATH`latentcode --version`It prints a version number. If the command isn't found, open a new terminal. - 02Check the connection`latentcode config``LatentRouter connection config /home/you/.config/latentcode/latentcode.jsonc gateway url https://latentstack.dev/v1 api key ls-AbCdE…wXyZ default model latentrouter/… only provider latentrouter models 6 imported``gateway url` is your server, `api key` is set, and `models` shows a count. The key is always shown masked. LatentRouter is LatentCode's name for your LatentStack gateway. - 03List your models`latentcode config models --refresh`This re-imports your models from the gateway, which also proves the key works. An `Invalid API key` warning means the key is wrong or was regenerated. ## Installer options install.sh (macOS and Linux) `--cli-only`flagoptional Install only latentcode. Skips the desktop app and the editor extension. `--desktop-only`flagoptional Install only LatentWork. Skips latentcode and the editor extension. `--no-vscode`flagoptional Skip the editor extension. `--no-skills`flagoptional Skip the skills bundle. `--base URL`stringoptional Download from a different server, for example `--base https://ai.example.com`. The CLI's gateway URL is set to `URL/v1`. install.ps1 (Windows) `-CliOnly`switchoptional Install only latentcode. `-DesktopOnly`switchoptional Install only LatentWork. `-NoVscode`switchoptional Skip the editor extension. `-NoSkills`switchoptional Skip the skills bundle. `-Base URL`stringoptional Download from a different server. Both scripts also read the `LATENTSTACK_BASE` environment variable as the download server. An explicit `--base` or `-Base` wins over it. ### Passing options A piped script needs a little extra syntax to receive options. In bash, put them after `bash -s --`. In PowerShell, `iex` can't pass parameters, so create a script block instead: ``` curl -fsSL https://latentstack.dev/install.sh | bash -s -- --cli-only ``` ### Desktop app only, without the rest The desktop step is also served as its own script. It installs LatentWork and its menu entry and nothing else. On Windows, `-Silent` runs the app's installer without prompts. ``` curl -fsSL https://latentstack.dev/install-desktop.sh | bash ``` ## Upgrade To update LatentCode, run: ``` latentcode upgrade ``` It downloads the installer from the gateway you're connected to and runs it again, which installs the latest version your server has. The LatentCode TUI also checks for a new version when it starts: patch releases install automatically, and larger releases show a notice. To turn this off, set `"autoupdate": false` (or `"notify"` to be told without installing) in `latentcode.jsonc`, or set `LATENTCODE_DISABLE_AUTOUPDATE=1`. To update everything, including LatentWork and the editor extension, run the install command again. Re-running is safe: it replaces the binaries, reinstalls the extension over the old one and swaps in the new skills bundle. Close LatentCode and LatentWork first, or the skills step may report that it couldn't replace the folder. ## Uninstall ``` curl -fsSL https://latentstack.dev/uninstall.sh | bash ``` The uninstaller removes the CLI, the desktop app, the editor extension, and all LatentCode and LatentWork settings, sessions and caches, including your saved API key. Preview it first with a dry run: ``` curl -fsSL https://latentstack.dev/uninstall.sh | bash -s -- --dry-run ``` | bash | PowerShell | Effect | | --- | --- | --- | | --dry-run | `-DryRun` | Print what would be removed and change nothing. | | --keep-data | `-KeepData` | Remove the apps only. Keep settings, sessions and caches. | | --no-vscode | `-NoVscode` | Leave the editor extension installed. | ### What's removed | Item | macOS and Linux | Windows | | --- | --- | --- | | CLI and skills | `~/.latentcode` | `%USERPROFILE%\.latentcode`, and its `Path` entry | | LatentWork | `LatentWork.app` (macOS), or `~/.local/share/LatentWork` and its menu entry (Linux) | Runs the app's own uninstaller silently | | Editor extension | Uninstalled from every supported editor found | Same | | LatentCode data (not with --keep-data) | `latentcode` under `~/.config`, `~/.local/share`, `~/.cache` and `~/.local/state` | The same folders under %USERPROFILE% | | LatentWork data (not with --keep-data) | Its app data, cache and log folders | Its folders under %APPDATA% and %LOCALAPPDATA% | | Shell PATH lines | LatentStack lines in your shell startup files. A backup is kept as `.latentstack-bak`. | The user Path entry | The uninstaller doesn't remove the `~/.local/bin` line some shells have, because other tools use that folder. When it finishes, open a new terminal. ## Troubleshooting latentcode: command not found The installer added `~/.latentcode/bin` to your shell startup file, but open terminals don't see it yet. Open a new terminal, or run `source ~/.zshrc` (or your shell's file). You can always run the CLI by its full path, `~/.latentcode/bin/latentcode`. No latentcode binary available on … for this machine Your server doesn't have a build for your OS and CPU. The message lists the builds it tried. Ask your administrator to add the missing one. LatentWork desktop app couldn't be installed Your server has no desktop build for your platform, or the download failed. The CLI is unaffected. Ask your administrator whether your server offers LatentWork for your platform. Installed to ~/Applications (no permission for /Applications) A piped script can't ask for your password, so on macOS the app went into your personal Applications folder instead. It works the same way and still shows in Launchpad and Spotlight. Windows blocks latentcode.exe Windows SmartScreen shouldn't block it, but AppLocker or WDAC policies that block unsigned programs can: ask your IT team to allow `%USERPROFILE%\.latentcode\bin\latentcode.exe`. Could not replace latentcode.exe — is latentcode running? Close every LatentCode window and run the installer again. A restart releases the file if it's still locked. Native skills: could not replace … is latentcode or LatentWork running? Close LatentCode and LatentWork and run the installer again. Your existing skills are left as they were. No supported editor found The extension was downloaded to `~/.latentcode/vscode/latentcode.vsix` but no editor command was found. On macOS, run Shell Command: Install 'code' command in PATH from VS Code's Command Palette and run the installer again, or run Extensions: Install from VSIX... in your editor and pick that file. No download server configured The script was run from a saved copy rather than from the server. Run it through the install command, or pass `--base https://your-server`. For connection and API errors after installing, see Troubleshooting. Source: https://latentstack.dev/docs/install --- # Concepts The ideas every LatentStack product shares: organizations, roles, API keys, models, tiers, teams, guardrails and usage. ## The gateway Every model request from LatentCode, LatentWork, the Agents API and your own code goes to one place: the LatentStack gateway, running on your server. Clients never talk to a model provider directly. For each request, the gateway: - identifies you from your API key and works out which organization and team the request belongs to; - runs the organization's guardrails over the request; - checks that your tier allows the model, and applies rate limits, budgets and credits; - sends the request to the provider that serves the model, using credentials your administrator configured; - records the tokens and cost against you, your organization and your team. Because every request passes through the gateway, the policies below apply the same way to every product. ## Organizations An organization is a tenant: a company, department or group with its own members, tiers, teams, guardrails, model and provider settings, and usage. Nothing is shared between organizations. - One account, many organizations. Your account belongs to you, and you can be a member of several organizations, with a different role and tier in each. - The active organization. The console shows one organization at a time; switch with the organization switcher. A request is counted against the organization that's active for it. - Your default organization is used when a client doesn't say which one it means. It's set to the first organization you join. - Creating one. On the Organizations page, choose New organization. You become its owner, and it gets its own default tier. Your deployment may turn organization creation off. ### Joining an organization | Way in | How it works | | --- | --- | | Invitation | An owner or admin invites you by email from the Members page. Open the link and sign in (or create an account) with the invited email address to accept. Invitations expire after 14 days, and a new invitation to the same address replaces the old one. | | Public organization | Organizations can be Public — discoverable. Find them under Discover public organizations and request to join. Depending on the organization's setting, you join straight away or an admin approves the request. | | Added by an admin | An admin creates your account, or adds your existing account, from the Users page. You may get a welcome email with a temporary password and your API key. | | Automatic | Your organization may add new accounts automatically. | ## Roles Inside an organization, each member has one of three roles: | Role | Can do | | --- | --- | | member | Use the models their tier allows, see their own usage, join teams they are added to. | | admin | Everything a member can, plus: invite, approve, remove and change the role of members; manage users, tiers, teams, guardrails, prompts and organization settings; see the organization's usage. | | owner | Everything an admin can, plus delete the organization and transfer ownership. Each organization has one owner. | - Admins and owners see the Administration section of the console sidebar. Members see only Organization and My account. - You can only change members whose role is below yours, never the owner and never yourself. Invitations can grant admin or member; ownership moves only by transfer. - An owner can't leave an organization without first transferring ownership. ## API keys An API key identifies you to the gateway. Keys start with `ls-`. Send yours as a bearer token; the gateway also accepts it in an `x-api-key` header, which Anthropic clients use: ``` Authorization: Bearer ls-… ``` - One personal key per account. It's created with your account. Copy it from Account settings → API Key in the console (open it). - Rotating. Select Regenerate on the same card. The old key stops working immediately, so update LatentCode and LatentWork with the new one. Administrators can't regenerate another user's key. - Not tied to an organization. Your personal key works in every organization you belong to. Clients choose the organization with the `X-Org-Id` header; without it, the gateway uses your default organization. - Keys end with membership. If you're removed from an organization, requests to it fail even though the key is still valid. If your account is deleted, the key stops working. ## Models Each organization chooses which models it offers; admins manage them in the console. | Idea | What it means | | --- | --- | | Model id | How you name a model in a request, for example `anthropic/claude-haiku-4-5`: usually `/`. Use ids exactly as `GET /v1/models` returns them. LatentCode may show a longer id that includes the provider. | | Provider | The service that actually runs the model, such as Anthropic, OpenAI, Gemini, Amazon Bedrock, Azure or OpenRouter. | | Context window | The most tokens a request and its reply can use together. LatentCode uses it to decide when to compact a long conversation. | | Max output tokens | The longest reply the model can produce. | The model pickers in LatentCode and LatentWork list only the models your tier allows. ## Tiers A tier is a bundle of allowed models and limits. Admins create tiers on the Tiers page and assign them to users and teams. Every organization has a default tier that new members start on. | Setting | Effect | | --- | --- | | Allowed models | Which models members on the tier can use. A request for any other model is refused with model_not_allowed. | | Default model | The model clients preselect when they first connect, and fall back to on errors. It must be one of the allowed models. | | Rate limits | Requests per minute, hour, 6 hours and day, per model, with a default for models not listed. 0 means unlimited. Limits count requests, not tokens. | | Budget limits | US-dollar spend caps per minute, hour, 6 hours and day, plus optional per-model daily caps. 0 means unlimited. | | Background models | The models LatentCode uses behind the scenes, such as for subagents and session titles. | ### Which tier applies When you work in a team, the team's tier applies. Otherwise you get the tier an admin gave you in the organization, or the organization's default tier. If none applies, the request is refused with `no_tier_assigned`. Rate limits and budgets are counted separately for each organization, and for each team within it. ## Teams A team (a project in the API) is a group of members inside an organization with its own tier and, optionally, its own instructions that are added to every request made for the team. Admins manage teams on the Teams page; you see yours under My Teams. - You choose a team in LatentCode or LatentWork. API clients send the team's id in the `X-Project-Id` header. - Requests for a team use the team's tier and count against the team's limits, separately from your personal usage. - Admins can give individual members a different tier or rate limits within a team. ## Guardrails Guardrails screen every request before it reaches a model. Each organization sets its own on the Guardrails page: - AI policy check. A model you choose reviews each request against policies you write in plain language, and blocks requests that break them. - Sensitive data (PII). Detects data such as card numbers, email addresses, phone numbers and national ID numbers. Block refuses the request; Sanitize redacts or masks the data and sends the rest. A blocked request fails with a `400` error that says why. See Admin Console to configure guardrails and Troubleshooting for the errors. ## Usage and cost The gateway records every request: the model, input, output, cached and reasoning tokens, and the cost in US dollars. | Where | Who | What you see | | --- | --- | --- | | My Usage | Everyone | Your tier, allowed models, rate-limit and budget usage, credits, and spend by model and day, for you personally or for a team. | | Budget Alerts | Everyone | An email when your daily spend crosses a percentage of your budget. | | Overview | Admins | Spend over time, top models and top users. | | Usage Analytics | Admins | Detailed usage and cost across the organization. | ### Three kinds of spending limit | Limit | Set on | Behaviour | | --- | --- | --- | | Rate limits | Tier, team member | Requests per window. Requests may slow down near a limit and fail with 429 past it. | | Budgets | Tier | Dollar spend per window. Requests fail with 402 until the window resets. | | Credits | Organization, member | A balance that goes down with use and doesn't reset by itself. The organization has a pool, and each member can have a cap within it. When either runs out, requests fail with 402. Members can ask for more with Request Credits on My Usage; admins answer on Credit Requests. | ## Signing in to the console The console uses email and password. Anyone can create an account on the sign-up page; an account on its own belongs to no organization until you create or join one. If you forget your password, the sign-in page emails you a 6-digit code to reset it. The code is valid for 10 minutes. Source: https://latentstack.dev/docs/concepts --- # Troubleshooting Find the error you're seeing, what causes it and how to fix it, for LatentCode, LatentWork, the Agents API and the console. ## Reading a gateway error Every product sends its model requests through the gateway, so most problems show up as a gateway error. The error names the problem in its `type` and explains it in `message`. LatentCode and LatentWork show the message; the full error looks like this: JSON ``` { "error": { "message": "Model 'claude-opus-5' is not allowed for your tier 'Free'", "type": "model_not_allowed" } } ``` ## Error reference | Status | type | Meaning | | --- | --- | --- | | 401 | invalid_api_key | The key is missing, wrong, or regenerated. Details | | 403 | org_access_denied | You aren't a member of the organization the request is for. Details | | 403 | project_access_denied | You aren't in the team, or the team belongs to another organization. Details | | 403 | no_tier_assigned | No tier applies to you in this organization. Details | | 403 | model_not_allowed | Your tier doesn't include the model. Details | | 400 | guardrail_blocked, guardrail_blocked_llm, guardrail_blocked_pii | A guardrail blocked the request. Details | | 400 | invalid_request_error | The request itself is wrong. Details | | 402 | budget_exceeded | A tier spending budget is used up for the current window. Details | | 402 | credit_limit_exceeded | Your organization's or your own credits have run out. Details | | 429 | rate_limit_exceeded | Too many requests. Details | | 502 | varies | The model provider failed or rejected LatentStack's credentials. Details | ## Authentication and access ### 401: Invalid API key JSON ``` { "error": { "message": "Invalid API key", "type": "invalid_api_key" } } ``` Cause. The gateway doesn't recognise the key. Usually it was regenerated (the old key stops working at once), copied with a missing character, or the account was deleted. Fix. Copy the key again from Account settings → API Key (open it) and update every client that uses it. In LatentCode, run `latentcode config set api-key ls-…`. A related message with the same status and type: | message | Cause and fix | | --- | --- | | API key required. Send 'Authorization: Bearer '. | No key was sent. Add an `Authorization: Bearer ls-…` header, or `x-api-key: ls-…`. | ### 403: Not a member of this organization JSON ``` { "error": { "message": "You are not a member of this organization", "type": "org_access_denied" } } ``` Cause. The request's `X-Org-Id` header names an organization you don't belong to, often because you left or were removed and the client still has it selected. Fix. Pick an organization you belong to in the client, or drop the header to use your default organization. List yours with: ``` curl https://latentstack.dev/v1/orgs -H "Authorization: Bearer $LS_API_KEY" ``` ### 403: Team errors | message | Cause | Fix | | --- | --- | --- | | You are not a member of this project | The request names a team (`X-Project-Id`) you aren't in. | Choose one of your teams (see My Teams in the console), or ask an admin to add you. | | This team is not available in the selected organization | The team belongs to a different organization from the one the request is for. | Switch to the team's organization, or choose a team in the current one. | ### 403: No access tier JSON ``` { "error": { "message": "No access tier is assigned for this account in the selected organization. Ask an administrator to assign one.", "type": "no_tier_assigned" } } ``` Cause. No tier applies: not the team's, not yours in the organization, not the organization's default. See Which tier applies. Fix. Ask an organization admin to assign you a tier on the Users page, or to set a default tier on the Tiers page. ### 403: Model not allowed JSON ``` { "error": { "message": "Model 'claude-opus-5' is not allowed for your tier 'Free'", "type": "model_not_allowed" } } ``` Cause. Your tier's allowed models don't include the one you asked for. Tiers can differ between organizations and teams. Fix. Pick a model from your model list, which only shows the models you can use. In LatentCode, run `latentcode config models --refresh` to update the model list. To get the model added, ask an admin to add it to your tier. ## Request errors ### 400: Blocked by a guardrail JSON ``` { "error": { "message": "Your request was blocked because it contained sensitive data.", "type": "guardrail_blocked_pii", "entities": [{ "entity": "US_SSN", "count": 1 }] } } ``` | type | Default message | What happened | | --- | --- | --- | | guardrail_blocked_pii | Your request was blocked because it contained sensitive data. | The request contained data the organization's PII guardrail blocks. `entities` lists what was found and how often. | | guardrail_blocked_llm | Your request was blocked by an AI safety policy. | The AI policy check found the request breaks a policy. `policy` names it when known. | | guardrail_blocked | Your request was blocked by a content guardrail. | The request matched a blocking content rule. `guardrail` names the rule. | Admins can replace the default messages, so yours may differ. Remove the flagged content and try again. If you think the block is wrong, tell an organization admin: guardrails are set per organization on the Guardrails page. When the PII guardrail is set to sanitize, it removes the data and the request goes through. ### 400: Invalid request | message | Fix | | --- | --- | | 'messages' must be a non-empty array | Send at least one message in `messages`. | | 'max_tokens' must be a positive integer | Set `max_tokens` to 1 or more, or leave it out. | | Model does not support tools | Remove `tools`, or use a model that supports tool calling. | | does not support reasoning effort '' — supported: … | Use one of the listed levels. | | reasoning effort '' is not available for here — allowed: … | Your organization offers fewer levels than the model supports. Use one of the allowed ones. | | '' on '' has no price, so every call would bill at zero … | Your server has no price for this model on this provider. Tell your administrator. | | Provider '' has no id declared for model '', so it cannot serve it. … | This model isn't set up correctly on your server. Tell your administrator. | | HTTP 400: … | The provider rejected the request. A common case is a prompt longer than the model's context window: shorten it, or start a new conversation. | ## Limits and spending ### 429: Rate limit JSON ``` { "error": { "message": "Rate limit reached for this key: 60 requests per minute; retry in 12s", "type": "rate_limit_exceeded", "retry_after": 12 } } ``` Cause. Your tier limits how many requests you can make per model per minute, hour, 6 hours and day. Near a limit, requests slow down; past it, they fail with 429. Fix. Check Rate limit usage (per model) on My Usage to see which limit you hit, slow down, or ask an admin for a higher tier. Admins can reset a user's counters. ### 402: Budget exceeded JSON ``` { "error": { "message": "Budget exceeded for window 'day': spent $5.0132 of $5.0000", "type": "budget_exceeded", "window": "day", "model": null } } ``` Cause. Your tier caps spend per window (`min`, `hour`, `6h` or `day`), and you've reached it. When `model` is set, the cap is that model's daily budget. Fix. Wait for the window in `window` to reset, or switch to a cheaper model if only a per-model budget is used up. Budget usage (USD) on My Usage shows where you stand. To get warned before this happens, set up Budget Alerts. ### 402: Credit limit exceeded JSON ``` { "error": { "message": "Credit limit exceeded (member): $0.0000 of $20.0000 remaining", "type": "credit_limit_exceeded", "scope": "member", "remaining": 0, "limit": 20 } } ``` Cause. Credits don't reset on their own. `scope` says whose ran out: `member` is your own allowance within the organization, `org` is the whole organization's pool. Fix. For `member`, select Request Credits on My Usage; an admin approves it on Credit Requests. For `org`, an organization admin needs to top up the pool. ## 502: Provider errors A 502 means the model provider couldn't complete the request. The message starts with the provider's status, for example `HTTP 503: …`. | What you see | Cause | Fix | | --- | --- | --- | | HTTP 5xx: … | The provider had an outage or was overloaded. The gateway already retried. | Try again shortly, or use another model. | | HTTP 401: … or HTTP 403: … | The provider rejected the credentials LatentStack uses for it. Your key is fine. | Tell your administrator. Provider credentials are set in the console. | | provider '' has no … — set one on the Providers page | The provider serving this model isn't set up on your server. | Tell your administrator. | | Other messages | A timeout or network problem between the gateway and the provider. | Try again. If it keeps happening, tell your administrator. | ## LatentCode Invalid API key when setting the key or connecting Cause. The gateway rejected the key (HTTP 401 or 403). Fix. Copy the key again from Account settings and run `latentcode config set api-key ls-…`. Check the gateway URL with `latentcode config`. Could not reach gateway (… → HTTP 404) or Could not reach … Cause. The gateway URL is wrong or unreachable. It must be your server's address followed by `/v1`. `latentcode config set base-url` warns when the URL doesn't end in `/v1`. Fix. Run `latentcode config set base-url https://latentstack.dev/v1`, then `latentcode config models --refresh`. If it still fails, check that `https://latentstack.dev` opens in a browser on this machine. No models returned for this key (empty tier?) Cause. The key works, but no models are available to you: your tier allows none, or no tier applies. Fix. Ask an organization admin to assign you a tier with at least one model. The Connect LatentRouter dialog keeps coming back Cause. LatentCode won't start a session until the gateway accepts your key, so the first-run dialog reopens until a key validates. Fix. Enter a working key, or press `ctrl+c` to quit and set it with `latentcode config set api-key`. Press `esc` on the key step to go back and correct the gateway URL. A model I expect is missing from the model list Cause. LatentCode lists the models it imported the last time the key was checked. Tier changes don't show until it imports again. Fix. Run `latentcode config models --refresh`. If the model is still missing, it isn't in your tier for the selected organization or team. Collecting details for a bug report Run the failing command with logs printed to the terminal: ``` latentcode run "hello" --print-logs --log-level DEBUG ``` Include the output of `latentcode --version` and `latentcode config`. The config output masks your key, but check what you share. More in LatentCode. ## LatentWork The profile menu says Gateway unreachable Cause. Your API key is wrong or was regenerated. Fix. Copy your current key from Account settings, paste it into Settings → LatentRouter and save. Server unreachable. Check the URL and try again. Cause. LatentWork couldn't connect to the URL within the time limit. Fix. Check the URL is your server's address, for example `https://latentstack.dev`, and that this machine can open it in a browser. Server returned an error (…) Cause. The server answered, but not successfully. Fix. Check the URL points at your LatentStack server and not at another site on the same host. More in LatentWork. ## Console An account with this email already exists Sign in instead. If you don't know the password, choose the forgotten-password link on the sign-in page to get a reset code by email. Too many sign-up attempts from this network. Please try again later. Too many sign-ups came from your network. Wait a few minutes and try again. My invitation link doesn't work - Invite not found or already used: the link was used, revoked or replaced by a newer invitation. Ask for a new one. - This invite has expired: invitations last 14 days. Ask for a new one. - This invite was sent to …: you're signed in with a different email address. Sign out and sign in (or sign up) with the invited address. I can't see the Administration pages They're for organization owners and admins, in the organization that's active. Check the organization switcher, then ask an owner to make you an admin if you need access. My usage is in the wrong organization Usage is counted against the organization each request was for. Clients use your default organization unless you pick another one in the client. See Organizations. ## Installing Problems with the installer, `PATH`, missing builds or blocked executables are covered in Install → Troubleshooting. Source: https://latentstack.dev/docs/troubleshooting --- # LatentCode A coding agent that runs in your terminal. It reads your code, edits files and runs commands to get a task done, and asks before it does anything you haven't allowed. ``` $ cd my-project $ latentcode > The /orders endpoint returns 500 when the cart is empty. Find out why and fix it. ``` ## What you can do with it - Understand a codebase. Ask how something works; it searches and reads the code and answers with file references. - Make changes. Describe a feature, a fix or a refactor. It edits the files, runs your tests and shows you every diff. - Plan first. The read-only Plan agent investigates and proposes an approach without touching anything. - Keep going on its own. Give it a goal and it works turn after turn until the goal is met, or run a prompt on a schedule with `/loop`. - Script it. `latentcode run` sends one prompt and prints the result, for CI jobs and shell scripts. - Extend it. Add your own slash commands, agents, skills, MCP servers and plugins. ## How it connects LatentCode sends every model request through your organization's LatentStack gateway, using your personal API key. The models you can pick are the ones your tier allows, and usage shows up on your My Usage page. Your code stays on your machine: LatentCode reads and edits files locally and sends the model only what it needs for the task. ## Install The LatentStack installer sets up LatentCode and points it at this gateway: ``` curl -fsSL https://latentstack.dev/install.sh | bash ``` See Install for Windows and other options, then follow the Quickstart. ## Explore the docs ### Quickstart Connect, start a session and review your first change. ### Common workflows Explore code, fix bugs, write tests, review changes. ### The TUI Prompt input, file references, shell mode, sessions. ### Agents Build, Plan and subagents, and making your own. ### Permissions Control what runs without asking. ### Models Choose models and reasoning effort. ### Goals and loops Long-running and recurring work. ### Sessions and context Resume, fork, undo, compaction. ### Configuration Config files and every setting. ### MCP servers Connect external tools. ### Keybindings Every shortcut, and how to change them. ### CLI reference Every command and flag. Source: https://latentstack.dev/docs/latentcode --- # Quickstart Install LatentCode, connect it to your gateway, and have it make and verify a change in your project. ## Before you begin - A LatentStack account and an API key. Your key starts with `ls-`; copy it, or generate one, under API Key on your Account page. - macOS, Linux or Windows, and a terminal. - A project to work on. A git repository is best: undo and diffs use git. ## 1. Install ``` curl -fsSL https://latentstack.dev/install.sh | bash ``` The installer puts `latentcode` in `~/.latentcode/bin`, adds it to your `PATH`, and points it at this gateway. Open a new terminal and check it: ``` latentcode --version ``` See Install for other options. ## 2. Connect Save your API key. LatentCode checks it against the gateway and imports the models your tier allows: ``` latentcode config set api-key ls-your-key ``` ``` ✓ API key saved → ~/.config/latentcode/latentcode.jsonc ✓ Imported 24 model(s) (tier: standard) ``` If you skip this, the TUI asks for the gateway URL and key the first time you start it, in a Connect LatentRouter dialog. Check the connection at any time: ``` latentcode config ``` Note Installed some other way? Point LatentCode at this gateway first. The URL ends in `/v1`: ``` latentcode config set base-url https://latentstack.dev/v1 ``` ## 3. Start a session ``` cd ~/src/my-project && latentcode ``` The TUI opens with a prompt at the bottom. The line under it shows the agent (Build), the model, and how much context is left. Press `ctrl+x` `m` to pick a different model. Start by asking about the code. Nothing is changed while it answers questions: ``` > Give me an overview of this project: what it does, how it's laid out, and how to run the tests. ``` ## 4. Make a change - 01Plan itPress `tab` to switch to the Plan agent, which can read but not edit. Describe the change:`> Add input validation to the signup handler: reject empty emails and passwords under 8 characters, with a clear error message.`It investigates and replies with a plan. Ask follow-up questions until you're happy with it. - 02Build itPress `tab` to go back to Build and say `go ahead`. The agent edits the files and runs your tests. Each edit appears in the conversation as a diff, and the sidebar (`ctrl+x` `b`) lists every modified file. - 03Answer any approval requestsIf it needs to do something outside the defaults, such as install a package or touch a `.env` file, it stops and asks. Choose Yes, allow once, allow it for the rest of the session, or No and tell it what to do instead. See Permissions. - 04Review the resultType `/diff` to open the diff viewer on your working tree: `n`/`p` move between files, `]`/`[` between changes, `q` closes it. For a second opinion, run `/review`: reviewers check your uncommitted changes and report problems. - 05Keep it, or undo itCommit as usual, or ask the agent to. If you don't like the change, `/undo` (`ctrl+x` `u`) removes your last message and restores the files it changed. `/redo` brings it back. ## 5. Teach it your project Run `/init`. LatentCode studies the repository and writes an `AGENTS.md` at its root with your build commands, conventions and structure. Every session reads it, so commit it for your team. See Rules. ## Next steps - Common workflows: fixing bugs, writing tests, reviewing pull requests. - The TUI: file references, shell commands, images and sessions. - Goals and loops: let it keep working until a condition is met. - latentcode run: use it from scripts and CI. Source: https://latentstack.dev/docs/latentcode/quickstart --- # Common workflows Prompts and commands for everyday tasks: understanding code, fixing bugs, testing, reviewing and working with git. ## Understand a codebase Switch to Plan (`tab`) so nothing changes while you explore, then start broad and narrow down: ``` > Give me a tour of this repository: the main components, how a request flows through them, and where the tests live. > How does authentication work? Point me to the files involved. > @src/billing/invoice.ts why does finalize() lock the account row? ``` - Reference files with `@` so the agent starts from the right place. `@file#10-40` narrows it to lines. - For wide searches, the agent hands work to the `explore` subagent. Ask for it directly with `@explore`. - Once you understand the project, `/init` writes what you learned into `AGENTS.md`. ## Fix a bug ``` /bug-fix Uploading a CSV with a BOM fails with "unknown column id" ``` `/bug-fix` sets a goal: find the root cause, make the smallest fix, add a regression test and run the tests. The agent keeps going until that's done or it needs you. Give it everything you have: the error, the stack trace, steps to reproduce. Paste a screenshot with `ctrl+v`, or run the failing command yourself with `!` so the output is in the conversation: ``` ! pnpm vitest run src/import/csv.test.ts ``` ## Write tests ``` > Write tests for @src/pricing/discounts.ts. Follow the style of the existing tests in src/pricing/. Cover the edge cases: zero quantity, stacked discounts, expired codes. Run them and make sure they pass. ``` Say which framework and which existing tests to imitate, and ask it to run them. If your test command isn't obvious, put it in AGENTS.md. ## Refactor safely - Plan first in Plan, and agree on the approach before switching to Build. - Ask for small steps and a test run after each. Check them with `/diff`, and use `/undo` to back out one that went wrong. - For large changes, `/fork` the session to try an alternative without losing the first attempt. ## Review changes ``` /review # uncommitted changes, including untracked files /review branch main # this branch compared with main /review commit 4f2a9c1 # one commit /review pr 212 tests errors # a GitHub pull request, only the tests and error-handling aspects ``` `/review` runs specialist reviewers in parallel, each on one aspect (`code`, `errors`, `tests`, `types`, `comments`, `simplify`), and reports what they find. It doesn't change anything; ask for fixes afterwards. Pull requests are fetched from your git remote, so this needs a GitHub repository. `/diff` shows the same changes for your own review. See The diff viewer. ## Work with git and pull requests ### Commits and branches Ask in plain language: `commit this with a descriptive message`, `create a branch for this fix`. Git commands that change the repository ask for approval by default, and pushes, rebases and hard resets are treated as dangerous and ask even in the Auto agent. See Permissions. ### Pick up a pull request ``` latentcode pr 212 ``` Checks out pull request 212 into a branch named `pr/212` and opens LatentCode on it, ready for questions or fixes. It uses the GitHub CLI, which must be installed and logged in. ## Run it in scripts and CI `latentcode run` sends one prompt and prints the answer, then exits. In CI, connect with an API key stored as a secret, and allow only what the job needs: ci-review.sh ``` latentcode config set base-url https://latentstack.dev/v1 latentcode config set api-key "$LS_API_KEY" export LATENTCODE_PERMISSION='{"edit":"deny","bash":{"*":"deny","git diff*":"allow","git log*":"allow"}}' git diff origin/main...HEAD | latentcode run --agent plan --format json \ "Review this diff for bugs and security problems. Reply with a markdown list." > review.jsonl ``` Warning Approvals in scripts Anything that would ask for approval is rejected in `run`. Either allow it in config, as above, or pass `--auto` inside a disposable environment such as a CI container. See the run reference for every flag and the JSON event format. Source: https://latentstack.dev/docs/latentcode/workflows --- # The TUI Run latentcode with no arguments to open the full-screen terminal UI. This page covers the screen, the prompt and everything you can put in it. ## The screen A new session opens with a welcome panel: your account and organization, the model, the working directory, a tip and what's new in this version. The prompt sits at the bottom. ### The line under the prompt While the agent is idle it shows, from left to right: - The agent, for example Build, with `(tab to cycle)`. - The model and the gateway host serving it, and the reasoning effort if you've picked one. - The working directory. - On the right: a `TODOS` chip while the agent has a task list, a `GOAL` chip while a goal is active, and context usage as `used / limit (N% left)`. While the agent works, the line shows a spinner, the elapsed time and any retries. Press `esc` twice to interrupt it. ### The sidebar `ctrl+x` `b` shows or hides the sidebar (clicking the `TODOS` or `GOAL` chip does too). On terminals up to 120 columns wide it opens over the conversation. It shows: | Section | Shows | | --- | --- | | Cost | What the session has cost so far. | | Context | Tokens used out of the model's limit, and how much is left before compaction. | | MCP | Each MCP server and whether it's connected, failed, disabled or needs authentication. | | Todo | The agent's task list, until everything on it is done. | | Goal | The active goal, whether it's working or waiting for you, and the turn count. | | Loop | A running /loop: its prompt, interval, iteration and next run. | | Modified Files | Files changed in this session, with lines added and removed. | ### The command palette `ctrl+p` lists every action with its shortcut: switching sessions, models and themes, toggling display options, stashing a prompt, and more. Start typing to filter. Some actions exist only here, such as Show sidebar, Stash prompt and Copy last assistant message. ## Writing prompts | To | Press | | --- | --- | | Send | `return` | | Insert a newline | `shift+return`, `ctrl+return`, `alt+return` or `ctrl+j` | | Recall earlier prompts | `up` / `down` with the cursor at the start or end of the prompt | | Clear the prompt | `ctrl+c` | | Write in your editor | `ctrl+x` `e` or `/editor`. Uses `$VISUAL` or `$EDITOR`. | | Send while the agent is working | Just send it. The agent picks it up at its next step. | Pasting three or more lines, or more than 150 characters, inserts a `[Pasted ~N lines]` placeholder to keep the prompt readable; the full text is still sent. `ctrl+o` previews or edits it. If you clear a prompt you've typed a lot into, it's saved in the history so `up` brings it back. To put a prompt aside and come back to it, use Stash prompt and Stash pop in the command palette. ## Referencing files and agents with @ Type `@` to open a fuzzy search. Pick an entry with `tab` or `return`. | Type | Adds | | --- | --- | | @src/app.ts | The file, attached to your message. | | @src/app.ts#10-40 | Only lines 10 to 40. | | @src/components | A directory. | | @explore | Hands the request to that subagent. | | @sync: | Opens a session picker, then brings in a summary of that session's history, including sessions shared to your organization. | MCP servers that offer resources also appear in the list. ## Running shell commands with ! Type `!` at the very start of the prompt to switch to shell mode, then type a command and press `return`. It runs in your project directory, and the command and its output become part of the conversation, so you can ask about them next. ``` ! npm test -- --grep checkout ``` Press `esc`, or `backspace` at the start of the prompt, to leave shell mode. ## Images and PDFs - Paste an image from the clipboard with `ctrl+v`. - Drag a file into the terminal, or paste its path. PNG, JPEG, GIF, WebP, AVIF and PDF files are attached; SVG files are added as text. - Attachments appear in the prompt as `[Image 1]` or `[PDF 1]`. Whether a model can read images or PDFs is set by your administrator for each model. Large images are resized before sending; see `attachment.image` in Configuration. ## Slash commands Type `/` to list commands: built-in ones, your custom commands and prompts from MCP servers (marked `:mcp`). `/skills` lists skills. The Slash commands page lists every built-in. ## Reading the conversation | To | Use | | --- | --- | | Expand or collapse reasoning, summaries and tool activity | `ctrl+l` | | Show or hide thinking | `/thinking` | | Show timestamps | `/timestamps` | | Hide code blocks | `ctrl+x` `h` | | Scroll | `pageup` / `pagedown`, the mouse wheel, or `ctrl+alt+u` / `ctrl+alt+d` for half a page | | Jump to the start or end | `ctrl+g` / `ctrl+alt+g` | | Jump to a message | `/timeline` or `ctrl+x` `g` | | Copy the last answer | `ctrl+x` `y` | | Copy the whole conversation | `/copy` | When the agent starts subagents, each gets its own child session. Open the first with `ctrl+x` `down`, move between them with `left` and `right`, and go back with `up`. ## The diff viewer `/diff` opens a full-screen view of changes, with a file tree on the left. `d` switches between three sources: | Source | Shows | | --- | --- | | Working tree | Everything uncommitted in your repository. | | Main branch | Your branch compared with the default branch (only when you're on another branch). | | Last turn | What the agent changed in its last turn. | | Key | Action | | --- | --- | | `n` / `p` | Next / previous file | | `]` / `[` | Next / previous change | | `j` / `k` | Move down / up | | `v` | Side by side or unified | | `b` | Show or hide the file tree | | `tab` | Move focus between the tree and the diff | | `m` | Mark the file reviewed | | `?` | All shortcuts | | `q` / `esc` | Close | Side-by-side needs a wide terminal; narrower ones show a single column. Set `"diff_style": "stacked"` in `tui.json` to always use one column. ## Themes `/themes` or `ctrl+x` `t` previews and switches themes. The default is `latentcode`; `system` uses your terminal's own colors. Built in: aura, ayu, carbonfox, catppuccin, catppuccin-frappe, catppuccin-macchiato, cobalt, console, cursor, flexoki, github, gruvbox, latentcode, mercury, moss, nightowl, nord, plum, vercel and zenburn. To add your own, put a JSON theme file in `themes/` inside `~/.config/latentcode` or a project's `.latentcode` folder; its file name is the theme name. Set the default with `"theme"` in `tui.json`. ## Notifications To get a desktop notification and a sound when LatentCode finishes, asks a question or needs approval, turn on `attention` in `tui.json`: JSONC ``` { "attention": { "enabled": true, "sound": true, "volume": 0.4 } } ``` ## Other ways to run it - `latentcode --mini`: a lighter interface that prints into your normal terminal scrollback, with the prompt in a footer. Also `latentcode run --interactive`. - `latentcode run "…"`: one prompt, no interface. See the CLI reference. Note Suspend and quit `ctrl+z` suspends LatentCode to your shell (`fg` brings it back). `ctrl+c` or `ctrl+d` on an empty prompt, `ctrl+x` `q`, or `/exit` quits. Your session is saved; `latentcode -c` reopens it. Source: https://latentstack.dev/docs/latentcode/tui --- # Agents An agent is a role: a system prompt, a set of permissions and optionally its own model. Primary agents are the ones you talk to; subagents are helpers they hand work to. ## Primary agents Press `tab` to move to the next primary agent and `shift+tab` to go back, or pick one from the list with `ctrl+x` `a` or `/agents`. The current agent is shown under the prompt. | Agent | Use it to | | --- | --- | | build | Do the work. The default. It edits files and runs shell commands, and asks before network access, destructive commands, git changes and sensitive files. | | auto | Work with fewer interruptions. Like Build, but network commands, web access, git changes and files outside the project are allowed too. Destructive commands and secrets still ask. | | plan | Think before changing anything. Read-only: it explores the code and writes a plan. When the plan is ready it can offer to switch to Build. | | ultraplan | Plan, then have a second model check the plan against the code before you approve it. Appears only when your organization has it turned on. | The exact rules for each are on the Permissions page. Start in a different agent with `latentcode --agent plan`, or make it the default with `"default_agent"` in your config. ## Subagents A primary agent can start subagents to work on part of a task in their own context, which keeps its own context small, and can run several at once. Each runs in a child session you can open (see The TUI). | Subagent | Does | | --- | --- | | general | Multi-step work that may end in changes: reproducing a bug, making a contained change, running an investigation to a conclusion. | | explore | Fast, read-only searching and answering questions about the code. It can read and search files and run commands, but not edit. | The agent decides when to use them, or you can ask directly by mentioning one: `@explore where do we validate webhook signatures?`. Subagents can't start further subagents unless you raise `subagent_depth`. ## Create an agent ### With the wizard ``` latentcode agent create ``` - Choose where to save it: the current project or global (asked only inside a git repository). - Describe what the agent should do. A model writes its name, description and system prompt. - Choose which permissions to allow. Everything you leave unticked is denied. - Choose the mode: All, Primary or Subagent. The agent is saved to `.latentcode/agents/.md` or `~/.config/latentcode/agents/.md`. Edit the file to refine it. For scripts, pass `--path`, `--description`, `--mode` and `--permissions` to skip the questions (see the CLI reference). ### As a Markdown file Put a Markdown file in `.latentcode/agents/` in your project, or `~/.config/latentcode/agents/` to use it everywhere. The file name is the agent's name, the front matter configures it and the body is its system prompt. .latentcode/agents/migrations.md ``` --- description: Writes and reviews database migrations. Use for any schema change. mode: subagent model: latentrouter/bedrock-anthropic/anthropic/claude-sonnet-5 permission: bash: "*": ask "npm run db:migrate:dry*": allow --- You write PostgreSQL migrations for this project. - Every migration must be reversible; write the down step. - Never drop a column in the same release that stops using it. - Run the dry-run command and include its output in your answer. ``` Files in subfolders are named by their path: `agents/db/migrations.md` is `db/migrations`. You can use `{file:…}` and `{env:…}` in values, as in config. ### In latentcode.json JSONC ``` { "agent": { "docs": { "description": "Writes and updates user documentation.", "mode": "subagent", "prompt": "{file:./prompts/docs-writer.md}", "permission": { "bash": "deny" } }, "build": { "model": "latentrouter/bedrock-anthropic/anthropic/claude-opus-5" }, "auto": { "disable": true } } } ``` The same keys change built-in agents: here Build gets a different model and Auto is removed. ## Agent options `description`stringoptional When to use the agent. Primary agents show it in the agent list; for subagents it's how other agents decide to call them, so be specific. `mode`"primary" | "subagent" | "all"optionaldefault `all` Primary agents appear in the `tab` cycle; subagents can be mentioned with `@` and started by other agents; `all` is both. `prompt`stringoptional The system prompt. In a Markdown file, the body. `model`stringoptional Model to use, as `provider/model`. Without it, primary agents use the session's model and subagents use the model of the agent that started them, unless your organization assigns one. `variant`stringoptional Default reasoning effort, such as `high`. Only applies while the agent uses its own `model`. `permission`objectoptional Rules for this agent, applied after the top-level ones. See Permissions. `steps`integeroptional Maximum tool-using steps per request. When reached, the agent must answer in text. `temperature`numberoptional Sampling temperature, where the model supports it. Lower is more focused. `top_p`numberoptional Nucleus sampling, where the model supports it. `color`stringoptional A hex color such as `#FF5733`, or a theme color: `primary`, `secondary`, `accent`, `success`, `warning`, `error`, `info`. `hidden`booleanoptionaldefault `false` Keep the agent out of the `@` menu and the `tab` cycle. `disable`booleanoptionaldefault `false` Remove the agent, including a built-in one. `memory`"user" | "project" | "local"optional Give the agent its own memory. `user` follows you across projects; `project` is stored in `.latentcode/agent-memory` and committed; `local` in `.latentcode/agent-memory-local`, not committed. ## Check your agents ``` latentcode agent list ``` Prints every agent with its mode and permission rules. `latentcode debug agent ` shows one agent's full configuration. Source: https://latentstack.dev/docs/latentcode/agents --- # Permissions Decide what the agent may do on its own, what it has to ask about, and what it may never do. ## How it works Before each action (reading a file, editing one, running a command, fetching a URL) LatentCode checks your permission rules. Each rule gives one of three answers: | Action | Result | | --- | --- | | allow | Runs without asking. | | ask | Stops and asks you first. | | deny | Blocked. The agent is told it isn't allowed. | ## Approving a request When the agent needs approval, the prompt is replaced by a request like this: ``` Bash command git push origin feature/orders Do you want to proceed? 1. Yes, allow once 2. Yes, don't ask again this session for commands starting the same way 3. No, tell latentcode what to do (esc) ``` | Choice | Effect | | --- | --- | | Yes, allow once | Runs this one action. | | Yes, don't ask again this session | Also approves matching requests for the rest of this session, including its subagents. The approval is kept in memory only and never written to your config. A rule set to `deny` still wins. | | No, tell latentcode what to do | Rejects the action and stops the turn so you can type what to do instead. Other requests waiting in the same session are rejected too. | Press `1`–`3` to choose, or move with the arrow keys and press `enter`. `esc` rejects. `ctrl+f` shows the request full screen, which helps with long commands and diffs. What "matching" covers depends on the request: the same file, the same pattern, commands starting the same way (for example every `git push …`), or the same URL origin. ## Defaults Out of the box, the agent can read and change your project freely but asks about anything that reaches outside it, touches secrets or is hard to undo: | Permission | Default | | --- | --- | | read | Allowed, except `.env` files (`.env.example` is allowed) and credentials such as `~/.ssh`, `~/.aws`, `*.pem`, `*.key`, `.npmrc`, `.netrc`: ask. | | edit | Allowed, except: ask for `.env` files, `.latentcode/`, `.github/workflows/`, `package.json` and lock files, `Dockerfile`, `docker-compose*.yml`, `*.tf`, `*.tfvars` and credential files. | | bash | Depends on the agent (below). Always allowed: `pwd`, `ls`, `git status`, `git diff`, `git log`, `git show`, `rg`, `grep`, `which`, `file`, `stat`, `wc`. | | network | Ask. Commands that use the network: `curl`, `wget`, `ssh`, `gh`, `aws`, `kubectl`, `git clone/fetch/pull/push`, package installs, and so on. | | dangerous_command | Ask. `sudo`, `rm -r`, `git reset --hard`, `git push`, `git rebase`, `git commit --amend`, deleting branches, `kubectl delete`, `terraform destroy`, `docker … prune`. | | repository_metadata | Ask. Git commands that change the repository: `git add`, `commit`, `checkout`, `merge`, `stash`, `tag`, and similar. | | external_directory | Ask, for any file or command outside the project directory. | | webfetch, websearch | Ask. | | doom_loop | Ask, when the agent calls the same tool with the same input three times in a row. | | everything else | Allowed: `glob`, `grep`, `task`, `todowrite`, `skill`, MCP tools. | ### Per agent | Agent | Differences from the defaults | | --- | --- | | build | All shell commands are allowed. Network, dangerous and repository-changing commands still ask. | | auto | Also allows network commands, web fetch and search, repository-changing git commands and files outside the project. Dangerous commands and sensitive files still ask. | | plan | Read-only. File edits, network, dangerous and repository-changing commands are denied; only the always-allowed shell commands run. You can't loosen this with config. | Switch agents with `tab`. See Agents. ## Configure permissions Add a `permission` block to `latentcode.json`, globally or in a project: latentcode.json ``` { "permission": { "edit": "ask", "webfetch": "allow", "bash": { "*": "ask", "npm test*": "allow", "git push*": "ask", "rm *": "deny" }, "read": { "*": "allow", "secrets/*": "deny" } } } ``` - A permission takes one action (`"edit": "ask"`) or an object of patterns. - Patterns are matched against the command for `bash`, and against the path for `read`, `edit` and `external_directory`. `*` matches anything, `?` one character. A pattern ending in `" *"` also matches the command with no arguments, so `"git status *"` matches `git status`. - The last matching rule wins. Put `"*"` first and the exceptions after it. A request that matches nothing asks. - `~` and `$HOME` at the start of a pattern expand to your home directory. - `"permission": "ask"` as a single string applies to everything. ### Permission keys | Key | Covers | | --- | --- | | read | Reading files and listing directories. | | edit | Every tool that changes files: edit, write and patch. | | bash | Shell commands, matched against the command text. | | network | Shell commands that reach the network. | | dangerous_command | Destructive or privileged shell commands. | | repository_metadata | Git commands that change the repository. | | external_directory | Anything outside the project directory. | | glob, grep | File and content search. | | task | Starting subagents, matched against the subagent's name. | | skill | Loading a skill, matched against its name. | | webfetch, websearch | Fetching URLs and searching the web. | | todowrite | The agent's task list. | | question | The agent asking you multiple-choice questions. | | doom_loop | Repeating the same tool call. | | _ | An MCP tool, for example `github_create_issue`. Wildcards work: `"github_*": "ask"`. | ### Per-agent rules Rules under an agent apply only to it and override the top-level ones: JSONC ``` { "agent": { "build": { "permission": { "bash": { "*": "ask", "npm run *": "allow" } } } } } ``` ## Command sandbox On macOS and Linux, shell commands also run inside an operating-system sandbox. A command can read anywhere but can only write inside the project (plus any directories you approved for it), and can only use the network if it was recognized as a network command. This holds even for commands you allowed. Linux needs `bwrap` (bubblewrap) installed. Set `LATENTCODE_OS_SANDBOX=false` to turn the sandbox off. ## Without the TUI `latentcode run` has nobody to ask, so it rejects every request that would ask, and denies questions and plan mode. Allow what an automated job needs in config, or pass `--auto` (same as `--dangerously-skip-permissions`) to approve every request that isn't denied. Only use it in an environment you'd be happy for the agent to change. `--auto` has no effect in the TUI. You can also set rules for one process with the `LATENTCODE_PERMISSION` environment variable, as JSON: Bash ``` LATENTCODE_PERMISSION='{"bash":{"*":"allow"},"webfetch":"deny"}' latentcode run "run the tests and fix failures" ``` ## FAQ Why does it ask before editing package.json? Dependency and CI files are on the default ask list because changes to them run code on other machines. Allow them with `"edit": { "*package.json": "allow" }`. Why does a file like app.environment.ts ask to be read? The default `*.env*` pattern matches any path containing `.env`. Add a more specific rule after it, such as `"read": { "*.environment.ts": "allow" }`. Can I make "don't ask again" permanent? Not from the prompt: session approvals end with the session. Add the rule to your config instead. The agent says a command was denied, but I allowed it. Check for a later, more specific rule and for agent-level rules: the last match wins, and agent rules come after the top-level ones. In Plan, edits and non-read-only commands are always denied. `latentcode agent list` prints the resolved rules for every agent. Source: https://latentstack.dev/docs/latentcode/permissions --- # Models Choose which model LatentCode uses, how hard it thinks, and which organization pays for it. ## Which models you can use LatentCode gets its models from your LatentStack gateway. The list depends on your organization's tier, is imported when you save your API key, and is refreshed in the background. Print it with: ``` latentcode models ``` ``` tier: standard latentrouter/bedrock-anthropic/anthropic/claude-haiku-4-5 latentrouter/bedrock-anthropic/anthropic/claude-sonnet-5 latentrouter/gemini/gemini-3.1-pro-preview … ``` A model ID has three parts: the provider `latentrouter` (your gateway), the host that serves the model (for example `bedrock-anthropic`), and the model. Use the full ID wherever a setting or flag asks for `provider/model`. The IDs on your gateway may differ from these examples. If a model you expect is missing, ask your administrator to add it to your tier, then run `latentcode config models --refresh`. ## Switch models `/models` or `ctrl+x` `m` opens the model picker. It lists your Favorites, your Recent models and then every model grouped by host, with your tier's default marked `(tier default)`. Type to filter. | Key | Action | | --- | --- | | `ctrl+f` | In the picker: add or remove a favorite. | | `f2` / `shift+f2` | Switch to the next / previous recently used model without opening the picker. | The choice applies from your next message and is remembered for the agent you're using. To choose at startup, pass `-m`: ``` latentcode -m latentrouter/bedrock-anthropic/anthropic/claude-sonnet-5 ``` ## Default model New sessions use, in order: the model from `-m`, the `model` setting, your most recent model, then your tier's default. ``` latentcode config set default-model bedrock-anthropic/anthropic/claude-sonnet-5 ``` This writes `"model"` to your global config, adding the `latentrouter/` prefix. A project can set its own `"model"` in its `latentcode.json`, and each agent can have its own (see Agents). When you save an API key or refresh models and your default isn't on your tier, LatentCode picks one that is. ### small_model Background jobs, such as naming sessions, use a smaller, cheaper model. Set it with `"small_model"`; otherwise LatentCode picks a small model from the same provider. Your organization can also assign models to these jobs, which takes precedence. Note If a model fails If a request fails with an error the model can't recover from, the session switches once to your tier's default model and carries on. You'll see a notice when that happens. ## Reasoning effort Models that can reason offer effort levels, such as `low`, `medium` and `high`, or just `on` and `off`. The levels come from how your administrator set up each model. - `ctrl+t` steps through the levels and back to the default. - `/effort` opens a picker. If the model has no levels, you're told why. - The chosen level is shown under the prompt and remembered per model. - For scripts: `latentcode run --effort high "…"`. Per agent: `"variant": "high"`. Higher effort usually gives better answers on hard problems, and takes longer and costs more. ## Organizations and teams If you belong to more than one LatentStack organization, `/org` switches which one your requests are billed to and whose tier applies. `/projects` picks a team within it. The choice is saved on your machine for the API key you're using, and changing organization clears the team. Choose Default to let the gateway decide. For a single command, pass `--org` and `--team` (names or IDs) to `run`, `models` or `stats`. Nothing is saved. ``` latentcode run --org acme --team payments "summarize open TODOs" ``` ## Fusion The main model hands routine work, such as broad searches, to a cheaper sidekick model. - Turn it on for everything with `/fusion`, or for one run with `latentcode --fusion`. `--sidekick-model ` picks the sidekick and also turns Fusion on. - Change the main and sidekick models, or turn Fusion off, with Change fusion config in the command palette (`ctrl+p`). These settings are saved to your global config. - A `FUSION` badge appears under the prompt. The sidebar and `/stats` split cost into Main agent and Sidekick. Warning `--fusion` (and the `LATENTCODE_FUSION` variable) keep Fusion on for that process even if it's off in your config. ## Debate `/debate` puts one question to several models, which answer, read each other's answers and respond over a number of rounds. Use it for design decisions where a second opinion helps. ``` /debate --rounds 3 Should the job queue use Postgres SKIP LOCKED or Redis streams? ``` - Rounds: 2 to 10, default 3. - Participants: 2 to 5, each on a different model. By default there are two: your current model and one other. Add more, and choose their models, with Configure debate in the command palette. - Participants can read and search your code but can't change it or use the network. - Each participant has 10 minutes by default. Change it with `debate.participantTimeoutMs`; `0` removes the limit. Source: https://latentstack.dev/docs/latentcode/models --- # Goals and loops Let the agent keep working without you: a goal runs turn after turn until a condition is true; a loop runs a prompt again and again on a schedule. ## Goals ``` /goal all tests in packages/api pass and npm run lint reports no errors ``` Normally the agent stops when it thinks it's done. With a goal, each time it stops, a separate model checks the recent conversation against your condition. If the condition isn't met, the agent is told what's missing and carries on. This repeats until: - The condition is met. The conversation shows `✓ Goal achieved`. - It can't be met. If the checker decides the goal is impossible, the goal is cleared with `✗ Goal failed` and the reason. - The agent is stuck. After three checks in a row with no progress, the goal waits for you (`waiting for you` in the sidebar). Send a message to help, or `/goal resume`. - A limit is reached (below). The agent is asked to wrap up, then the goal pauses. While a goal is active, a `GOAL` chip appears under the prompt and the sidebar shows the condition and the turn count. Write conditions you could check yourself: name the command that must pass, the file that must exist, or the behavior that must be fixed. ### Manage a goal | Command | Effect | | --- | --- | | /goal | Set a goal and start working on it. Replaces any current goal. | | /goal | Show the goal, its status, elapsed time, turns and tokens used. Same as `/goal status`. | | /goal pause | Stop continuing automatically. The goal is kept. | | /goal resume | Continue with fresh limits. | | /goal edit | Replace the condition without starting a run. | | /goal append | Add to the condition and pass it to the agent straight away. `/goal +` does the same. | | /goal clear | Remove the goal. `stop`, `off` and `cancel` work too. | Pressing `esc` twice interrupts the current turn; the goal then waits for you. The goal is stored with the session, so it survives quitting, resuming and compaction, and a forked session copies it. ### Limits Each run toward a goal stops at whichever limit comes first: | Setting | Default | Limit | | --- | --- | --- | | goal.maxTurns | 75 | Turns. | | goal.maxDurationMinutes | 45 | Minutes. Checked between turns, so a running step isn't cut off. | | goal.maxTokens | 500000 | Growth of the conversation's context during the run. Compaction brings it back down. | latentcode.json ``` { "goal": { "maxTurns": 120, "maxDurationMinutes": 90 } } ``` The counts start again each time you send a message or run `/goal resume`. Changes to the settings apply from the next `/goal` or `/goal resume`. The agent is warned as it gets close to a limit. ### /bug-fix ``` /bug-fix checkout returns 500 when the cart contains a gift card ``` Sets a goal with a ready-made condition: find the root cause, make the smallest fix, add a regression test, and run the tests to prove it. Manage it with the `/goal` commands. Note Which model checks the goal Goal checks use a model your organization assigns for background work, or the session's model if none is assigned. Each check costs a small request. ## Loops ``` /loop 10m check the CI status of this branch and fix anything that failed /loop keep the dependency updates PR green /loop ``` A loop sends the same prompt to the session repeatedly. There are three kinds: | You type | Kind | Runs | | --- | --- | --- | | /loop 10m | Fixed interval | Every 10 minutes, starting 10 minutes from now. Use `s`, `m` or `h`. You can also write the interval in the prompt: `/loop check the deploy every 5 minutes`. | | /loop | Self-paced | Now, then after each run a model picks the next delay, between 1 and 60 minutes. | | /loop | Maintenance | Now, using the instructions in the nearest `loop.md` in your project, or built-in maintenance instructions if there isn't one. | Before each run the conversation shows `⟳ Loop fired · iteration N`. A loop never interrupts a turn that's in progress; it waits for it to finish. The sidebar shows the prompt, the iteration and when the next run is due. ### Manage a loop | Command | Effect | | --- | --- | | /loop status | Show the loop. A bare `/loop` does the same while one is running. | | /loop pause | Stop running it. It's kept. | | /loop resume | Start again. The next run is one interval away (5 minutes for self-paced loops). | | /loop stop | Remove the loop. `off`, `cancel` and `clear` work too. `esc` also stops it while it's waiting for the next run. | Loops have no run limit and never expire; stop them when you're done. They're saved with the session and start again when you reopen LatentCode. A run that came due while LatentCode was closed runs once when you reopen it; missed runs don't pile up. Warning Loops cost money Every run is a full agent turn on your usage. Pick an interval that matches how often things actually change. ## FAQ Can I use a goal with latentcode run? Yes: `latentcode run --command goal "all tests pass"`. Remember that `run` rejects anything that needs approval, so allow what the goal needs in your permissions. The goal says it was achieved, but it isn't. The checker only sees the recent conversation. Make the condition verifiable there: ask for a command whose output proves it, for example "npm test exits with 0 and prints the summary". Source: https://latentstack.dev/docs/latentcode/goals --- # Sessions and context Every conversation is a session, saved on your machine. Resume, branch, undo, and keep long sessions within the model's context window. ## Start, resume and switch | To | In the TUI | From the shell | | --- | --- | --- | | Start a new session | `/new` (or `/clear`), `ctrl+x` `n` | `latentcode` | | Continue the last one | | `latentcode -c` | | Open a specific one | `/sessions` (or `/resume`), `ctrl+x` `l` | `latentcode -s ` | | List them | `/sessions` | `latentcode session list` | In the session list: - `ctrl+r` renames the selected session (or use `/rename` in a session). - `ctrl+d` deletes it; press it again to confirm. - `ctrl+f` pins it to the top. Pinned sessions get quick slots: `ctrl+x` `1` to `ctrl+x` `9` jump straight to them. New sessions are titled automatically from your first message. ## Fork a session `/fork` asks which message to branch from, then copies the conversation up to that point into a new session titled `… (fork #1)`. The original is left as it was. Use it to try a different approach without losing the first one. From the shell, `--fork` with `-c` or `-s` continues in a copy. ``` latentcode -s ses_abc123 --fork ``` A fork also copies the session's goal and loop, if it has them. ## Undo and redo `/undo` (`ctrl+x` `u`) removes your last message and everything after it, restores the files the agent changed since then, and puts your message back in the prompt so you can reword it. Run it again to go further back. `/redo` (`ctrl+x` `r`) reverses it. If the agent is working, undo stops it first. Undo works in git repositories and never commits to your repository. Untracked files over 2 MB aren't restored. Turn it off with `"snapshot": false`. Warning Undo restores files, not the outside world. Commands the agent ran, such as database migrations, pushes or package installs, aren't reversed. ## Context and compaction Each model has a context window: the most text it can consider at once. The line under the prompt shows how much of it the session uses, and the sidebar shows how much is left before compaction. ### Automatic Old tool output and older turns are condensed automatically, so long sessions keep going. Nothing is deleted: the full history stays in the session, and you can still scroll through it. ### Manual Run `/compact` (or `/summarize`, `ctrl+x` `c`) to compact now, for example before switching to a new part of a task. ### Settings latentcode.json ``` { "compaction": { "auto": true, // summarize automatically "prune": true, // drop old tool output "tail_turns": 2 // recent turns kept word for word } } ``` `LATENTCODE_DISABLE_AUTOCOMPACT` turns automatic compaction off for one process. Automatic compaction needs the model's context window, which your gateway reports. If the sidebar shows no context limit for a model, ask your administrator to set its context window. ## Work in more than one directory A session works in the directory you started it in. Anything outside it asks for permission. To let the session use another directory freely, add it: ``` /add-dir ../shared-lib ``` This applies to the current session only and isn't written to config. `/add-dir status` lists the extra directories. To start in another directory, pass it as an argument: `latentcode ../other-repo`. ## Bring in another session Type `@sync:` in the prompt and pick a session. A summary of that session's history is added to your message, so you can continue work started elsewhere without copying it. `/push-to-registry` summarizes the current session and shares it with your organization. Teammates can then pick it from their own `@sync:` list. ## Save and share a transcript | Command | Result | | --- | --- | | /export | Asks which details to include (thinking, tool details, model info), then writes a Markdown file named `session-.md` in the current directory and opens it in `$EDITOR`. Also `ctrl+x` `x`. | | /copy | Copies the transcript to the clipboard. | | latentcode export | Prints the session and every message as JSON. Add `--sanitize` to redact the content. | ## Usage and cost `/stats` shows what the current session has cost, including its subagents: cost, number of calls, input, output and cached tokens, and the models used. The figures come from your gateway. For all sessions, run: ``` latentcode stats --days 7 --models ``` See also My Usage in the console. ## Where sessions are stored Sessions live in a local database (`latentcode db path` prints where). Deleting a session with `ctrl+d` or `latentcode session delete` removes it for good. Source: https://latentstack.dev/docs/latentcode/sessions --- # Configuration Where LatentCode reads its settings from, how files combine, and every setting you can use. ## Two files | File | Holds | | --- | --- | | latentcode.json | How the agent behaves: models, agents, permissions, commands, MCP servers, plugins, instructions, compaction. | | tui.json | How the terminal UI looks and responds: theme, keybindings, scrolling, notifications. | Both accept JSON with comments and trailing commas, so you can also name them `.jsonc`. Add the schema line to get completion and validation in your editor: ~/.config/latentcode/latentcode.jsonc ``` { "$schema": "https://latentstack.dev/config.json", "model": "latentrouter/bedrock-anthropic/anthropic/claude-sonnet-5", "small_model": "latentrouter/bedrock-anthropic/anthropic/claude-haiku-4-5", "permission": { "bash": { "git push*": "ask" } }, "instructions": ["docs/CONVENTIONS.md"] } ``` ~/.config/latentcode/tui.json ``` { "$schema": "https://latentstack.dev/tui.json", "theme": "system", "keybinds": { "session_new": "ctrl+x n,ctrl+n" } } ``` Note Your gateway connection lives here too `latentcode config set …` writes your gateway URL, API key and imported models into the global `latentcode.jsonc`. Use the command rather than editing those values by hand. See latentcode config. ## Where config is read from LatentCode merges every file it finds. Later sources override earlier ones, key by key: | Order | Source | | --- | --- | | 1 | Global: `~/.config/latentcode/latentcode.json` and `latentcode.jsonc` (`$XDG_CONFIG_HOME/latentcode` if you set it). | | 2 | An extra file named by the `LATENTCODE_CONFIG` environment variable, if set. | | 3 | Project: `latentcode.json` or `latentcode.jsonc` in the current directory and every parent up to the git root, and in project `.latentcode` folders. The file closest to where you started wins. | | 4 | Settings your administrator enforces always win. | Objects merge deeply, so a project file only needs the keys it changes. Arrays replace each other, except `instructions`, which are combined. Run this to see the result: ``` latentcode debug config ``` `tui.json` is found the same way: global first, then `tui.json` in the project and its parents, then `.latentcode` folders. ### The .latentcode folder Besides config, a `.latentcode` folder in your project (or `~/.config/latentcode` for everything you do) can hold: | Folder | Contents | See | | --- | --- | --- | | agents/ | Agent definitions, one Markdown file each | Agents | | commands/ | Slash commands, one Markdown file each | Custom commands | | skills/ | Skills, one folder with a `SKILL.md` each | Skills | | plugins/ | Plugins, `.ts` or `.js` files | Plugins | | tools/ | Custom tools | Custom tools | | themes/ | Custom TUI themes as JSON | Themes | The singular names (`agent/`, `command/`, `skill/`, `plugin/`, `tool/`) work too. Commit the folder so your team shares it. ## Variables Any string value can pull in an environment variable or a file: JSONC ``` { "mcp": { "tracker": { "type": "remote", "url": "https://tracker.example.com/mcp", "headers": { "Authorization": "Bearer {env:TRACKER_TOKEN}" } } }, "agent": { "reviewer": { "prompt": "{file:./prompts/reviewer.md}" } } } ``` - `{env:NAME}` becomes the variable's value, or an empty string if it isn't set. - `{file:path}` becomes the file's contents. Paths are relative to the config file; `~/` is your home directory. A missing file is an error. ## latentcode.json reference Every key is optional. Unknown keys are ignored. Invalid JSON, or a value of the wrong type, stops LatentCode with an error that names the file. ### Models and agents | Key | Type | Description | | --- | --- | --- | | model | string | Default model, as `provider/model`. See Models. | | small_model | string | Model for background jobs such as session titles and goal checks. | | default_agent | string | Primary agent new sessions start with. Default `build`. | | agent | object | Configure built-in agents or add your own. See Agents. | | subagent_depth | integer | How many levels deep subagents may start their own subagents. Default `1`. | ### Permissions and tools | Key | Type | Description | | --- | --- | --- | | permission | object \| string | What needs approval. See Permissions. | | tools | object | Legacy. `{"bash": false}` is turned into a `deny` permission. Prefer `permission`. | | shell | string | Shell used for commands the agent runs and for `!` commands. Default: `$SHELL`. | | tool_output.max_lines | integer | Longer tool output is truncated and saved to a file the agent can read. Default `2000`. | | tool_output.max_bytes | integer | Same, in bytes. Default `51200`. | | attachment.image | object | Resizing for attached images: `auto_resize` (default true), `max_width` and `max_height` (default 2000). | ### Context and instructions | Key | Type | Description | | --- | --- | --- | | instructions | string[] | Extra rule files, globs or URLs added to every session. See Rules. | | compaction.auto | boolean | Summarize the conversation automatically when context runs low. Default `true`. | | compaction.prune | boolean | Free context by dropping old tool output. Default `true`. | | compaction.tail_turns | integer | Recent turns kept word for word when compacting. Default `2`. | | goal | object | `maxTurns`, `maxDurationMinutes`, `maxTokens`: limits for one goal run. See Goals. | | snapshot | boolean | Record file snapshots so `/undo` can restore files. Default `true`. | ### Extensions | Key | Type | Description | | --- | --- | --- | | command | object | Custom slash commands. See Custom commands. | | skills | object | `paths` and `urls` to load extra skills from. A `urls` entry is a URL, or `{ url, headerEnv }` for a server that needs a key. See Skills. | | mcp | object | MCP servers. See MCP servers. | | plugin | array | Plugins: npm package names or file paths. See Plugins. | | formatter | boolean \| object | Format files after the agent edits them. Off unless set: `true` turns on the built-in formatters; an object also adds or overrides formatters. | | lsp | boolean \| object | Language servers that give the agent diagnostics after edits. Off unless set: `true` turns on the built-in servers; an object configures them. | ### Everything else | Key | Type | Description | | --- | --- | --- | | username | string | Name shown for your messages. Default: your OS user name. | | autoupdate | boolean \| "notify" | Global config only. `false` turns update checks off; `"notify"` tells you about updates without installing them. | | debate.participantTimeoutMs | integer | Time limit for each `/debate` participant. Default 600000; `0` means no limit. | Warning theme and keybinds belong in tui.json Put `theme` and `keybinds` in `tui.json`, not `latentcode.json`. ## tui.json reference | Key | Type | Description | | --- | --- | --- | | theme | string | Color theme. Default `latentcode`; `system` follows your terminal's colors. See Themes. | | keybinds | object | Change shortcuts. See Keybindings. | | leader_timeout | integer | Milliseconds to wait for the next key after the leader key. Default `2000`. | | scroll_speed | number | Lines per scroll step. Default `3`. | | scroll_acceleration.enabled | boolean | Scroll faster the faster you scroll, like macOS. | | diff_style | string | `auto` shows side-by-side diffs when the terminal is wide enough; `stacked` always shows one column. | | mouse | boolean | Capture the mouse for clicking and scrolling. Default `true`. | | cursor | object | `style` (`block`, `underline`, `line` or `default`; default `block`) and `blinking` (default `true`). | | prompt.max_height | integer | Maximum height of the prompt box in lines. Default: a third of the terminal, at least 6. | | attention | object | Desktop notifications and sounds when LatentCode needs you. Off by default; set `enabled: true`. Also `notifications`, `sound`, `volume` (0–1, default 0.4) and `sounds` for custom sound files per event: `default`, `question`, `permission`, `error`, `done`, `subagent_done`. | ## Files LatentCode keeps | What | Where (macOS and Linux) | | --- | --- | | Config | ~/.config/latentcode | | Sessions database | A local database (`latentcode db path` prints where) | | Logs | ~/.local/share/latentcode/log | | Cache | ~/.cache/latentcode | | State | ~/.local/state/latentcode | The `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME` and `XDG_STATE_HOME` variables move these. `latentcode debug paths` prints the exact paths on your machine, including Windows. Source: https://latentstack.dev/docs/latentcode/configuration --- # Rules and memory Tell LatentCode how your project works once, in files it reads at the start of every session, and let it remember what it learns. ## AGENTS.md An `AGENTS.md` file holds the instructions you'd give a new teammate: how to build and test, conventions, what not to touch. LatentCode adds it to every session in the project. Commit it so your whole team, and any other coding agent that reads `AGENTS.md`, gets the same guidance. AGENTS.md ``` # Orders service ## Commands - Install: `pnpm install` - Test one file: `pnpm vitest run path/to/file.test.ts` - Lint and typecheck before finishing: `pnpm lint && pnpm typecheck` ## Conventions - Money is stored as integer cents. Never use floats for amounts. - New endpoints need an OpenAPI entry in `openapi/orders.yaml`. - Don't edit files under `src/generated/`; run `pnpm codegen` instead. ``` ### Generate one with /init Run `/init` in a session. The agent reads your build files, CI config and any existing rule files (including other tools' rules), may ask you a few questions, and writes `AGENTS.md` at the repository root. If one already exists, it improves it instead. Add a focus if you like: `/init focus on the test setup`. Coming from GitHub Copilot? `/adopt copilot` turns your Copilot instructions into an `AGENTS.md`. ## Which files are read | File | Applies to | | --- | --- | | ~/.config/latentcode/AGENTS.md | Every project: your personal preferences. If it doesn't exist, `~/.claude/CLAUDE.md` is used instead. | | AGENTS.md in the project | This project. Every `AGENTS.md` from your working directory up to the repository root is included, so a monorepo can have one at the root and more in packages. | | CLAUDE.md | Used instead of `AGENTS.md` in projects that only have `CLAUDE.md`. | | files in `instructions` | Anything else you list in config (below). | When the agent reads a file deeper in the project, `AGENTS.md` files in that file's folders are picked up too, so package-specific rules arrive when they matter. Note Turn off CLAUDE.md Set `LATENTCODE_DISABLE_CLAUDE_CODE_PROMPT=1` to ignore `CLAUDE.md` files, or `LATENTCODE_DISABLE_CLAUDE_CODE=1` to also ignore `.claude/skills`. ## More instruction files Point `instructions` at other files, glob patterns or URLs: latentcode.json ``` { "instructions": [ "CONTRIBUTING.md", "docs/guidelines/*.md", "~/notes/coding-style.md", "https://example.com/engineering/standards.md" ] } ``` - Relative paths and globs are searched for from your working directory up to the repository root. - Lists from different config files are combined, not replaced. Keep rule files short and specific. Everything in them is sent with every request. ## Memory LatentCode keeps a memory for each project. The agent saves things worth knowing next time, such as a decision you made, a command that works or a mistake to avoid, and relevant memories are brought into later sessions automatically. | Command | Does | | --- | --- | | /remember | Save a note yourself, for example `/remember staging deploys need the VPN`. Prefix a type to file it: `user:`, `feedback:`, `project:` or `reference:`. | | /memory | Show where the memory is stored, its index and your saved notes. | | /memory path | Show only the location. | - Memory lives on your machine, in `~/.local/share/latentcode/memory/`, one folder per project. It's plain Markdown: edit or delete the files to change what's remembered. - Relevant memories are added automatically; older ones are double-checked. - To ignore memory for a task, say so in your message. - Agents can also have their own memory; see `memory` on the Agents page. Warning Don't save secrets as memories. Memory files are plain text. Source: https://latentstack.dev/docs/latentcode/rules --- # Custom commands Turn a prompt you type often into a slash command, with arguments, file contents and live shell output filled in. ## Create a command Add a Markdown file to `.latentcode/commands/` in your project, or to `~/.config/latentcode/commands/` for every project. The file name is the command name. .latentcode/commands/test-fix.md ``` --- description: Run the tests for a package and fix what fails agent: build --- Run the test suite for the $1 package. Recent changes on this branch: !`git log --oneline main..HEAD` Fix every failing test. Don't change a test's assertions unless the test is wrong, and explain why if you do. Focus on: $2 ``` Type `/test-fix` and it appears in the command list with its description. Run it with arguments: ``` /test-fix billing the proration edge cases ``` Commands in subfolders get the path as their name: `commands/db/reset.md` is `/db/reset`. From the shell, run one with `latentcode run --command test-fix billing`. ## What you can put in a template | Write | Becomes | | --- | --- | | $ARGUMENTS | Everything typed after the command name, as typed. | | $1, $2, … | Individual arguments, split on spaces. Quote an argument to keep spaces in it: `/cmd "two words" next`. The highest-numbered placeholder takes all the remaining arguments. | | !`command` | The output of the shell command, run in your project directory when you use the slash command. | | @path/to/file | The file, attached to the message, as if you'd typed it in the prompt. | If the template has no placeholders and you type arguments anyway, they're added at the end. Warning Shell commands in a template run as soon as you use the command, without a permission prompt. Only use commands you trust, and review command files you get from others. ## Options `description`stringoptional Shown next to the command in the list. `agent`stringoptional Agent that runs the command. If it's a subagent, the command runs as a subtask in its own child session. `model`stringoptional Model for this command, as `provider/model`. `subtask`booleanoptional `true` always runs the command in a child session, keeping your main conversation's context clean. `false` never does. ## Define commands in config You can also define commands under `command` in `latentcode.json`. The `template` is required; use `{file:…}` to keep long templates in their own file. JSONC ``` { "command": { "changelog": { "description": "Draft a changelog entry for the current branch", "template": "Write a changelog entry for these changes:\n!`git diff main...HEAD --stat`", "model": "latentrouter/bedrock-anthropic/anthropic/claude-haiku-4-5" } } } ``` ### Name clashes A command you define with the same name as a built-in one replaces it. See Slash commands for the names already taken. ## Other things in the command list - Prompts offered by MCP servers, shown as `/server:prompt` with `:mcp` after them. - Skills can be run by name too; `/skills` lists them. Source: https://latentstack.dev/docs/latentcode/custom-commands --- # Skills A skill is a folder of instructions, and optionally scripts and reference files, that the agent loads only when a task needs it. ## How skills work The agent sees each skill's name and description, and loads a matching skill's full instructions before it starts the work. Skills cost almost no context until they're used, so you can install many. You can also run a skill yourself: `/skills` lists them, and `/` runs one. LatentCode also checks each message you send against your skills' names and descriptions. When a skill matches, the agent's first attempt to edit a file or run a shell command in that turn is held back with a Load first notice, so it reads the skill before acting. If the skill doesn't apply, the agent says so and carries on. This happens at most once per message. ## Write a skill Create a folder containing a `SKILL.md`. The front matter needs a `name`, and should have a `description` that says when to use it. .latentcode/skills/release-notes/SKILL.md ``` --- name: release-notes description: Write release notes from merged pull requests. Use when asked for release notes, a changelog or a summary of what shipped. --- # Release notes 1. Find the previous tag with `git describe --tags --abbrev=0`. 2. List merged pull requests since then with `gh pr list --state merged --search "merged:>="`. 3. Group them under Features, Fixes and Internal. Skip dependency bumps. 4. Follow the format in `template.md` in this folder. ``` Other files in the folder, such as templates, examples or scripts, are available to the agent: when it loads the skill, it's told the folder's location. Write the description with the words people use when they ask for the task: matching relies on them. A skill without a `description` is never matched or shown to the agent. ## Where skills are found | Location | Scope | | --- | --- | | .latentcode/skills//SKILL.md | This project. Commit it to share with your team. | | ~/.config/latentcode/skills//SKILL.md | All your projects. | | Bundled | Skills bundled with LatentStack. Turn them off with `"skills": { "native": { "enabled": false } }`. | | .claude/skills and .agents/skills | Skills written for other agents, in your home directory and in the project and its parents. | | paths in `skills.paths` | Any other folders you list, searched for SKILL.md files. | | URLs in `skills.urls` | Skills downloaded from a web server. Each URL is a folder with an `index.json` listing its skills. | If two skills have the same `name`, the one found first in this order wins. `skill/` works as the folder name as well as `skills/`. List everything LatentCode found with: ``` latentcode debug skill ``` latentcode.json ``` { "skills": { "paths": ["~/team-skills", "tools/skills"], "urls": [ "https://example.com/.well-known/skills/", { "url": "https://skills.example.com/team/", "headerEnv": { "X-API-Key": "TEAM_SKILLS_KEY" } } ] } } ``` Skills you add while LatentCode is running show up within a few seconds, with no restart. Skills from URLs are checked for updates every 15 minutes; give a skill a `version` in `index.json` and LatentCode downloads it again when the version changes. ### Skill servers that need a key Use the object form, as in the second `urls` entry above. `headerEnv` maps each request header to the name of an environment variable, so the key never goes in your config file. Export the variable before starting LatentCode (or later: it's read on every request). If it isn't set, the header is left out. The header is only sent to that server, never to another site it redirects to. Note Skipping other agents' skills Set `LATENTCODE_DISABLE_EXTERNAL_SKILLS=1` to ignore `.claude/skills` and `.agents/skills`, or `LATENTCODE_DISABLE_CLAUDE_CODE_SKILLS=1` to ignore only `.claude/skills`. ## Control which skills are used Loading a skill is a permission, matched against the skill's name: JSONC ``` { "permission": { "skill": { "*": "allow", "deploy-*": "ask" } } } ``` Denying the `skill` permission entirely also turns off skill matching. - Two skills come with LatentCode: `customize-latentcode`, which helps the agent change LatentCode's own configuration, and `l-spec`, for spec-driven changes. - See Permissions for how rules combine. Source: https://latentstack.dev/docs/latentcode/skills --- # MCP servers Connect LatentCode to other tools and data, such as issue trackers, databases and internal APIs, through the Model Context Protocol. ## Add a server ``` latentcode mcp add ``` The wizard asks for a name, whether the server is Local (a command LatentCode starts) or Remote (a URL), and whether it uses OAuth. Inside a git repository it also asks whether to save it to the current project or globally. To add one in a single command (saved globally): Bash ``` # local: everything after -- is the command to run latentcode mcp add files -- npx -y @modelcontextprotocol/server-filesystem ~/Documents # remote, with a header latentcode mcp add tracker --url https://tracker.example.com/mcp --header "Authorization=Bearer $TRACKER_TOKEN" ``` Check that it connects: ``` latentcode mcp list ``` ``` ✓ files connected npx -y @modelcontextprotocol/server-filesystem /Users/you/Documents ⚠ tracker needs authentication https://tracker.example.com/mcp ``` ## Configure servers in latentcode.json Servers live under `mcp`, keyed by name: latentcode.json ``` { "mcp": { "postgres": { "type": "local", "command": ["npx", "-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/app_dev"], "environment": { "PGPASSWORD": "{env:PGPASSWORD}" } }, "tracker": { "type": "remote", "url": "https://tracker.example.com/mcp", "headers": { "Authorization": "Bearer {env:TRACKER_TOKEN}" } }, "wiki": { "type": "remote", "url": "https://wiki.example.com/mcp", "oauth": {} } } } ``` ### Local servers `type`"local"required `command`string[]required The command and its arguments. `environment`objectoptional Environment variables for the command. `cwd`stringoptional Working directory, relative to the project. `enabled`booleanoptionaldefault `true` Set to false to keep the entry but not start it. `timeout`integeroptional Milliseconds to wait for requests to the server. ### Remote servers `type`"remote"required `url`stringrequired The server's URL. `headers`objectoptional HTTP headers to send, for example an API token. `oauth`object | falseoptional OAuth settings (below). `false` turns OAuth off even if the server asks for it. `enabled`booleanoptionaldefault `true` `timeout`integeroptional Milliseconds to wait for requests to the server. To turn off a server defined in another config file, for example in one project, set `"mcp": { "tracker": { "enabled": false } }`. `/mcps` in the TUI turns servers on and off with `space`. ## Log in with OAuth - 01Add the server with an oauth block`"oauth": {}` is enough for servers that support automatic client registration. Otherwise add the `clientId` (and `clientSecret`) you registered with the provider. - 02Authenticate`latentcode mcp auth tracker`Your browser opens the provider's login page. After you approve, it redirects to LatentCode on `http://127.0.0.1:19876/mcp/oauth/callback`. - 03Check`latentcode mcp auth list` shows each OAuth server and whether you're logged in. | oauth field | Meaning | | --- | --- | | clientId | Client ID registered with the provider. Omit it to register automatically. | | clientSecret | Client secret, if the provider issued one. | | scope | Scopes to request. | | callbackPort | Port for the redirect. Default `19876`. | | redirectUri | Full redirect URI, if the provider needs a specific one. | Credentials are stored locally, readable only by you. Log out with `latentcode mcp logout tracker`. If a login fails, `latentcode mcp debug tracker` walks through the OAuth steps and shows where it stops. ## Using MCP tools - The agent sees each tool as `_`, for example `tracker_create_issue`. - Tools are allowed by default. Control them with permissions: `"permission": { "tracker_*": "ask" }`. - Prompts the server offers appear as slash commands; resources appear in the `@` menu. - The sidebar and `/status` show each server's status. Warning Every tool costs context Each connected server's tool descriptions are sent with every request. Turn off servers you aren't using. ## Troubleshooting mcp list shows "failed" The error follows the status. For local servers, run the command yourself to see its output; check that it's on your `PATH`. Start LatentCode with `--print-logs` for details. "needs authentication" Run `latentcode mcp auth `. "needs client registration" The server doesn't support automatic registration. Register a client with the provider and add `clientId` to the server's `oauth` block. The browser login never returns Something else may be using port 19876. Set a different `callbackPort`. Source: https://latentstack.dev/docs/latentcode/mcp --- # Plugins and custom tools Extend LatentCode with JavaScript or TypeScript: react to events, check or change what the agent does, and give it new tools. ## Install a plugin Plugins published to npm install with one command: ``` latentcode plugin some-latentcode-plugin ``` This installs the package and adds it to the project's config. Add `-g` to install it for all projects and `-f` to replace a version that's already installed. You can also list plugins in `latentcode.json`, with options: JSONC ``` { "plugin": [ "some-latentcode-plugin", ["another-plugin", { "channel": "#builds" }], "./scripts/my-plugin.ts" ] } ``` Relative paths are resolved from the config file. Start LatentCode with `--pure` to run without any external plugins, for example to rule one out when something goes wrong. `latentcode debug info` lists the plugins that are loaded. Warning Plugins run with your permissions and aren't sandboxed. Only install ones you trust. ## Write a plugin Put a `.ts` or `.js` file in `.latentcode/plugins/` (project) or `~/.config/latentcode/plugins/` (everywhere). Every export must be a plugin: an async function that receives context and returns the hooks it implements. .latentcode/plugins/guard.ts ``` export const Guard = async ({ directory, $ }) => { return { // Refuse to read secrets, whatever the permission rules say. "tool.execute.before": async (input, output) => { if (input.tool === "read" && String(output.args.filePath).includes("secrets/")) { throw new Error("Reading files in secrets/ is not allowed") } }, // Desktop notification when the agent finishes (macOS). event: async ({ event }) => { if (event.type === "session.idle") { await $`osascript -e 'display notification "LatentCode finished" with title "${directory}"'` } }, } } ``` The plugin package, with types for plugins and tools, is installed into each `.latentcode` folder automatically. The context includes `directory` and `worktree` (the project), `project`, and `$` for running shell commands. ## Hooks | Hook | Called | You can | | --- | --- | --- | | event | For every event: sessions starting and going idle, messages, permission requests, and more. | React, for example notify or log. | | tool.execute.before | Before a tool runs, with its arguments. | Change the arguments, or throw to block the call. | | tool.execute.after | After a tool runs. | Change the title, output or metadata the agent sees. | | permission.ask | When a permission rule would ask. | Set `status` to `allow`, `deny` or `ask`. | | shell.env | Before a shell command runs. | Add environment variables. | | chat.message | When you send a message. | Change the message and its parts. | | chat.params | Before each model request. | Change temperature and provider options. | | chat.headers | Before each model request. | Add HTTP headers. | | command.execute.before | Before a slash command runs. | Change the parts it sends. | | config | At startup, with the merged config. | Read the configuration. | | tool | At startup. | Add tools (below). | ## Custom tools To give the agent a new tool without writing a full plugin, put a file in `.latentcode/tools/` or `~/.config/latentcode/tools/`: .latentcode/tools/ticket.ts ``` import { tool } from "@opencode-ai/plugin" export default tool({ description: "Look up a ticket in the tracker by its key, e.g. PAY-123", args: { key: tool.schema.string().describe("Ticket key"), }, async execute(args, context) { const res = await fetch(`https://tracker.example.com/api/tickets/${args.key}`, { headers: { Authorization: `Bearer ${process.env.TRACKER_TOKEN}` }, }) return await res.text() }, }) ``` - A default export is named after the file (`ticket`). Named exports are called `_`, so one file can hold several tools. - `tool.schema` is Zod; describe each argument so the model knows what to pass. - Return a string, or `{ output, title, metadata }`. Long output is truncated like any other tool's. - `context` has the `sessionID`, `agent`, `directory`, `worktree`, an `abort` signal, and `ask()` to request permission. - The tool can call anything: shell out to a Python or Go script, or call an API as above. - Plugins can add tools the same way, under a `tool` key in the hooks they return. ### Permissions for custom tools A custom tool runs without asking unless it calls `context.ask()` itself. To keep an agent from using it, deny it by name: `"permission": { "ticket": "deny" }`, globally or under an agent. Source: https://latentstack.dev/docs/latentcode/plugins --- # Keybindings Every TUI shortcut, its default keys, and how to change them. ## The leader key Most shortcuts start with the leader key, `ctrl+x`. Press it, let go, then press the next key within two seconds: `ctrl+x` `n` starts a new session. In the tables below, those are shown as `ctrl+x` followed by the key. `ctrl+p` opens the command palette, which lists every action with its current shortcut. It's the quickest way to find something. ## Change a shortcut Set keybindings in `tui.json` (not `latentcode.json`), globally in `~/.config/latentcode/tui.json` or per project. Use the names from the tables below. ~/.config/latentcode/tui.json ``` { "$schema": "https://latentstack.dev/tui.json", "keybinds": { "leader": "ctrl+a", "session_new": "n,ctrl+n", "input_newline": "shift+return,ctrl+j", "messages_toggle_conceal": "none" }, "leader_timeout": 3000 } ``` - Separate alternatives with commas. Each one works. - Write `` to use the leader key, whatever you've set it to. - Set a binding to `"none"` (or `false`) to turn it off. - Write keys the way the defaults below do, for example `ctrl+shift+a`, `alt+return` or `pagedown`. `enter`, `esc`, `pgup` and `pgdown` are accepted as other names for `return`, `escape`, `pageup` and `pagedown`. - `leader_timeout` is how long, in milliseconds, LatentCode waits for the key after the leader. Default 2000. - Unknown names are ignored with a warning in the log. Note Terminals don't send every key Many terminals can't tell `shift+return` from `return`, and on macOS the Option key often doesn't act as `alt` unless you turn that on in the terminal's settings. If a shortcut does nothing, try one of its alternatives (`ctrl+j` always inserts a newline) or bind a different key. ## Defaults Some keys mean different things in different places. `ctrl+d`, for example, quits from an empty prompt, deletes a character while you type, and deletes the selected session in the session list. ### General | Name | Default | Action | | --- | --- | --- | | app_exit | `ctrl+c``ctrl+d``ctrl+x``q` | Exit the application | | app_toggle_animations | none | Toggle animations | | app_toggle_file_context | none | Toggle file context | | app_toggle_diffwrap | none | Toggle diff wrapping | | app_toggle_paste_summary | none | Toggle paste summary | | app_toggle_session_directory_filter | none | Toggle session directory filtering | | command_list | `ctrl+p` | List available commands | | help_show | none | Open help dialog | | docs_open | none | Open documentation | | editor_open | `ctrl+x``e` | Open external editor | | theme_list | `ctrl+x``t` | List available themes | | theme_switch_mode | none | Switch between light and dark theme mode | | theme_mode_lock | none | Lock or unlock theme mode | | sidebar_toggle | `ctrl+x``b` | Toggle sidebar | | scrollbar_toggle | none | Toggle session scrollbar | | status_view | `ctrl+x``s` | View status | | terminal_suspend | `ctrl+z` | Suspend terminal | | terminal_title_toggle | none | Toggle terminal title | | plugin_manager | none | Open plugin manager dialog | | plugin_install | none | Install plugin | ### Sessions `escape` interrupts the agent only when pressed twice: the prompt shows `esc again to interrupt` after the first press. `session_rename`, `session_delete` and `session_pin_toggle` act in the session list. | Name | Default | Action | | --- | --- | --- | | session_export | `ctrl+x``x` | Export session to editor | | session_copy | none | Copy session transcript | | session_new | `ctrl+x``n` | Create a new session | | session_list | `ctrl+x``l` | List all sessions | | session_timeline | `ctrl+x``g` | Show session timeline | | session_fork | none | Fork session from message | | session_rename | `ctrl+r` | Rename session | | session_delete | `ctrl+d` | Delete session | | session_interrupt | `escape` | Interrupt current session | | loop_stop | `escape` | Stop the active loop while waiting | | session_background | `ctrl+b` | Background synchronous subagents | | session_compact | `ctrl+x``c` | Compact the session | | session_toggle_timestamps | none | Toggle message timestamps | | session_toggle_generic_tool_output | none | Toggle generic tool output | | session_child_first | `ctrl+x``down` | Go to first child session | | session_child_cycle | `right` | Go to next child session | | session_child_cycle_reverse | `left` | Go to previous child session | | session_parent | `up` | Go to parent session | | session_pin_toggle | `ctrl+f` | Pin or unpin session in the session list | | session_quick_switch_1 | `ctrl+x``1` | Switch to session in quick slot 1 | | session_quick_switch_2 | `ctrl+x``2` | Switch to session in quick slot 2 | | session_quick_switch_3 | `ctrl+x``3` | Switch to session in quick slot 3 | | session_quick_switch_4 | `ctrl+x``4` | Switch to session in quick slot 4 | | session_quick_switch_5 | `ctrl+x``5` | Switch to session in quick slot 5 | | session_quick_switch_6 | `ctrl+x``6` | Switch to session in quick slot 6 | | session_quick_switch_7 | `ctrl+x``7` | Switch to session in quick slot 7 | | session_quick_switch_8 | `ctrl+x``8` | Switch to session in quick slot 8 | | session_quick_switch_9 | `ctrl+x``9` | Switch to session in quick slot 9 | ### Models and agents | Name | Default | Action | | --- | --- | --- | | model_favorite_toggle | `ctrl+f` | Toggle model favorite status | | model_list | `ctrl+x``m` | List available models | | model_cycle_recent | `f2` | Next recently used model | | model_cycle_recent_reverse | `shift+f2` | Previous recently used model | | model_cycle_favorite | none | Next favorite model | | model_cycle_favorite_reverse | none | Previous favorite model | | mcp_list | none | List MCP servers | | provider_connect | none | Connect provider | | agent_list | `ctrl+x``a` | List agents | | agent_cycle | `tab` | Next agent | | agent_cycle_reverse | `shift+tab` | Previous agent | | variant_cycle | `ctrl+t` | Cycle reasoning effort | | variant_list | none | List reasoning effort levels | ### Conversation | Name | Default | Action | | --- | --- | --- | | messages_page_up | `pageup``ctrl+alt+b` | Scroll messages up by one page | | messages_page_down | `pagedown``ctrl+alt+f` | Scroll messages down by one page | | messages_line_up | `ctrl+alt+y` | Scroll messages up by one line | | messages_line_down | `ctrl+alt+e` | Scroll messages down by one line | | messages_half_page_up | `ctrl+alt+u` | Scroll messages up by half page | | messages_half_page_down | `ctrl+alt+d` | Scroll messages down by half page | | messages_first | `ctrl+g``home` | Navigate to first message | | messages_last | `ctrl+alt+g``end` | Navigate to last message | | messages_next | none | Navigate to next message | | messages_previous | none | Navigate to previous message | | messages_last_user | none | Navigate to last user message | | messages_copy | `ctrl+x``y` | Copy message | | messages_undo | `ctrl+x``u` | Undo message | | messages_redo | `ctrl+x``r` | Redo message | | messages_toggle_conceal | `ctrl+x``h` | Toggle code block concealment in messages | | tool_details | none | Toggle tool details visibility | | display_thinking | none | Toggle thinking blocks visibility | | display_detail | `ctrl+l` | Expand or collapse reasoning, summaries and tool activity | ### Prompt and text editing | Name | Default | Action | | --- | --- | --- | | stash_delete | `ctrl+d` | Delete stash entry | | prompt_submit | none | Submit prompt | | prompt_editor_context_clear | none | Clear editor context | | prompt_skills | none | Open skill selector | | prompt_stash | none | Stash prompt | | prompt_stash_pop | none | Pop stashed prompt | | prompt_stash_list | none | List stashed prompts | | prompt_paste_preview | `ctrl+o` | Preview pasted content | | input_clear | `ctrl+c` | Clear input field | | input_paste | `ctrl+v` | Paste from clipboard | | input_submit | `return` | Submit input | | input_newline | `shift+return``ctrl+return``alt+return``ctrl+j` | Insert newline in input | | input_move_left | `left``ctrl+b` | Move cursor left in input | | input_move_right | `right``ctrl+f` | Move cursor right in input | | input_move_up | `up` | Move cursor up in input | | input_move_down | `down` | Move cursor down in input | | input_select_left | `shift+left` | Select left in input | | input_select_right | `shift+right` | Select right in input | | input_select_up | `shift+up` | Select up in input | | input_select_down | `shift+down` | Select down in input | | input_line_home | `ctrl+a` | Move to start of line in input | | input_line_end | `ctrl+e` | Move to end of line in input | | input_select_line_home | `ctrl+shift+a` | Select to start of line in input | | input_select_line_end | `ctrl+shift+e` | Select to end of line in input | | input_visual_line_home | `alt+a` | Move to start of visual line in input | | input_visual_line_end | `alt+e` | Move to end of visual line in input | | input_select_visual_line_home | `alt+shift+a` | Select to start of visual line in input | | input_select_visual_line_end | `alt+shift+e` | Select to end of visual line in input | | input_buffer_home | `home` | Move to start of buffer in input | | input_buffer_end | `end` | Move to end of buffer in input | | input_select_buffer_home | `shift+home` | Select to start of buffer in input | | input_select_buffer_end | `shift+end` | Select to end of buffer in input | | input_delete_line | `ctrl+shift+d` | Delete line in input | | input_delete_to_line_end | `ctrl+k` | Delete to end of line in input | | input_delete_to_line_start | `ctrl+u` | Delete to start of line in input | | input_backspace | `backspace``shift+backspace` | Backspace in input | | input_delete | `ctrl+d``delete``shift+delete` | Delete character in input | | input_undo | `ctrl+-``super+z` | Undo in input | | input_redo | `ctrl+.``super+shift+z` | Redo in input | | input_word_forward | `alt+f``alt+right``ctrl+right` | Move word forward in input | | input_word_backward | `alt+b``alt+left``ctrl+left` | Move word backward in input | | input_select_word_forward | `alt+shift+f``alt+shift+right` | Select word forward in input | | input_select_word_backward | `alt+shift+b``alt+shift+left` | Select word backward in input | | input_delete_word_forward | `alt+d``alt+delete``ctrl+delete` | Delete word forward in input | | input_delete_word_backward | `ctrl+w``ctrl+backspace``alt+backspace` | Delete word backward in input | | input_select_all | `super+a` | Select all in input | | history_previous | `up` | Previous history item | | history_next | `down` | Next history item | ### Lists, autocomplete and dialogs | Name | Default | Action | | --- | --- | --- | | dialog.select.prev | `up``ctrl+p` | Move to previous dialog item | | dialog.select.next | `down``ctrl+n` | Move to next dialog item | | dialog.select.page_up | `pageup` | Move up one page in dialog | | dialog.select.page_down | `pagedown` | Move down one page in dialog | | dialog.select.home | `home` | Move to first dialog item | | dialog.select.end | `end` | Move to last dialog item | | dialog.select.submit | `return` | Submit selected dialog item | | dialog.prompt.submit | `return` | Submit dialog prompt | | dialog.mcp.toggle | `space` | Toggle MCP in MCP dialog | | prompt.autocomplete.prev | `up``ctrl+p` | Move to previous autocomplete item | | prompt.autocomplete.next | `down``ctrl+n` | Move to next autocomplete item | | prompt.autocomplete.hide | `escape` | Hide autocomplete | | prompt.autocomplete.select | `return` | Select autocomplete item | | prompt.autocomplete.complete | `tab` | Complete autocomplete item | | permission.prompt.fullscreen | `ctrl+f` | Toggle permission prompt fullscreen | | plugins.toggle | `space` | Toggle plugin | | dialog.plugins.install | `shift+i` | Install plugin from plugin dialog | ### Diff viewer These apply inside the diff viewer (`/diff`). It also uses fixed keys you can't change: `j`/`down` and `k`/`up` to move, `pagedown`/`ctrl+f` and `pageup`/`ctrl+b` to page, and `m` to mark a file reviewed. | Name | Default | Action | | --- | --- | --- | | diff_close | `escape``q` | Close diff viewer | | diff_toggle | `enter``space` | Toggle diff viewer item | | diff_expand | `right` | Expand diff viewer item | | diff_expand_all | `E` | Expand all diff viewer folders | | diff_collapse | `left` | Collapse diff viewer item | | diff_switch_focus | `tab` | Switch diff viewer focus | | diff_next_hunk | `]` | Jump to next diff hunk | | diff_previous_hunk | `[` | Jump to previous diff hunk | | diff_next_file | `n` | Jump to next diff file | | diff_previous_file | `p` | Jump to previous diff file | | diff_toggle_file_tree | `b` | Toggle diff viewer file tree | | diff_single_patch | `s` | Toggle single patch view | | diff_switch_source | `d` | Switch diff viewer source | | diff_toggle_view | `v` | Toggle diff viewer split or unified view | | diff_help | `?` | Show more diff viewer shortcuts | ## Windows On Windows, `terminal_suspend` is turned off and `ctrl+z` is added to `input_undo`, unless you set those yourself. See also The TUI for what each part of the screen does. Source: https://latentstack.dev/docs/latentcode/keybindings --- # CLI reference Every latentcode command and flag. Run latentcode with no command to open the TUI; add a command to script it, manage configuration or inspect state. ## Commands | Command | What it does | | --- | --- | | latentcode [project] | Start the TUI in the current directory, or in project. | | latentcode run [message..] | Send one message and print the result, without the TUI. | | latentcode config | Show or change the gateway connection: URL, API key, default model. | | latentcode models [provider] | List the models you can use. | | latentcode agent create \| list | Create a custom agent, or list agents. | | latentcode mcp add \| list \| auth \| logout \| debug | Manage MCP servers and their OAuth logins. | | latentcode session list \| delete | List or delete saved sessions. | | latentcode export [sessionID] | Print a session as JSON. | | latentcode stats | Show token usage and cost. | | latentcode pr | Check out a GitHub pull request, then start LatentCode on it. | | latentcode plugin | Install a plugin and add it to your config. Alias `plug`. | | latentcode attach | Open the TUI against a running LatentCode server. | | latentcode serve | Start a headless LatentCode server. | | latentcode acp | Start an Agent Client Protocol server on stdin/stdout, for editors that speak ACP. | | latentcode db path | Print where the local sessions database is. | | latentcode debug … | Troubleshooting tools. See below. | | latentcode upgrade [target] | Update LatentCode. | | latentcode uninstall | Remove LatentCode and its files. | | latentcode completion | Print a shell completion script. | ## Global flags These work with every command. | Flag | Description | | --- | --- | | -h, --help | Show help for the command. | | -v, --version | Print the version. | | --print-logs | Write logs to stderr as well as to the log file. | | --log-level | `DEBUG`, `INFO`, `WARN` or `ERROR`. Default `INFO`. | | --pure | Run without external plugins. | ## latentcode [project] Starts the TUI. `project` is the directory to work in; the default is the current directory. Bash ``` latentcode # new session in the current directory latentcode ~/src/api # new session in another directory latentcode -c # continue the most recent session latentcode -s ses_abc123 --fork # branch off an existing session latentcode --prompt "explain the build system" ``` | Flag | Description | | --- | --- | | -m, --model | Model for the session, for example `latentrouter/bedrock-anthropic/anthropic/claude-sonnet-5`. See Models. | | --agent | Agent to start with, for example `plan`. | | -c, --continue | Continue the most recent session. | | -s, --session | Continue the session with this ID. | | --fork | Continue in a copy of the session, leaving the original untouched. Needs `--continue` or `--session`. | | --prompt | Submit this prompt when the TUI opens. Text piped on stdin is added in front of it. | | --mini | Start the minimal interface instead of the full-screen TUI: the same split-footer prompt as `run --interactive`, with output printed into your normal terminal scrollback. | | --no-replay | With `--mini`: don't replay earlier messages on resume or after a resize. | | --replay-limit | With `--mini`: replay only the newest `n` messages. | | --fusion | Turn on the Fusion harness for this session. | | --sidekick-model | Fusion sidekick model. Implies `--fusion`. | ## latentcode run Sends one message, prints the agent's answer and exits when the session goes idle. Use it in scripts and CI. Bash ``` latentcode run "summarize what changed in the last commit" git diff | latentcode run "review this diff" latentcode run -f src/app.ts -f README.md "does the README match the code?" latentcode run --format json "list the TODOs in src/" > events.jsonl latentcode run --command review main # run a slash command with arguments ``` | Flag | Description | | --- | --- | | message.. | The message. Words are joined with spaces. Text piped on stdin is sent too. | | --command | Run a slash command instead of a plain message; `message` becomes its arguments. | | -c, --continue | Continue the most recent session. | | -s, --session | Continue the session with this ID. | | --fork | Fork the session before continuing. Needs `--continue` or `--session`. | | -m, --model | Model to use. | | --agent | Agent to use. | | --effort | Reasoning effort, for example `low`, `high` or `max`. With `--model`, the run stops with an error if that model doesn't offer the level. | | -f, --file | Attach a file or directory. Repeat for more. | | --title [text] | Title for a new session. With no value, the first 50 characters of the message. | | --format | `json` prints one JSON event per line, each with `type`, `timestamp` and `sessionID`. Types: `step_start`, `text`, `tool_use`, `step_finish`, `error`, and `reasoning` with `--thinking`. | | --thinking | Print the model's reasoning. On by default with `--interactive`. | | -i, --interactive | Keep the session open in a split-footer prompt instead of exiting after one answer. Needs a terminal. | | --replay-limit | With `--interactive`: replay only the newest `n` messages on resume. | | --no-replay | With `--interactive`: don't replay history on resume or after a resize. | | --auto, --dangerously-skip-permissions | Approve every permission request that isn't explicitly denied. Has no effect with `--interactive`. | | --dir | Directory to run in. With `--attach`, a path on the server. | | --attach | Send the message to a running server (see serve) instead of starting one. | | -p, --password / -u, --username | Basic-auth credentials for `--attach`. Default to `LATENTCODE_SERVER_PASSWORD` and `LATENTCODE_SERVER_USERNAME` (or `latentcode`). | | --port | Port for the local server. Random by default. | | --org | LatentStack organization for this run only. `""` uses your default organization. | | --team | LatentStack team within the organization, for this run only. `""` uses no team. | Warning Permissions without a TUI Nobody is there to answer approval prompts, so `run` rejects any action that would ask and prints `permission requested: … auto-rejecting`. The agent also can't ask you questions or switch into plan mode. Allow what the task needs in your permission config, or pass `--auto` in a sandbox you trust. Press `Ctrl+C` once to cancel the run cleanly (exit code 130); press it again to exit at once. The exit code is 1 if the request fails. ## latentcode config Manages the connection to your LatentStack gateway. Values are written to your global config file, `~/.config/latentcode/latentcode.jsonc`. | Command | What it does | | --- | --- | | config · config show | Print the connection: config file, gateway URL, masked API key, default model, imported models. | | config set api-key | Save your API key, import the models your tier allows, and fix the default model if it isn't among them. | | config set base-url | Save the gateway URL. It should end in `/v1`; you get a warning if it doesn't. | | config set default-model | Set the model new sessions use. The `latentrouter/` prefix is added if you leave it out. | | config get | Print `api-key`, `base-url` or `default-model` as plain text. Prints nothing if unset. | | config models [--refresh] | List imported models (`●` marks the default). `--refresh` re-imports them from the gateway. | | config clear | `api-key`, `base-url`, `default-model`, `models`, or `all` to remove the whole connection. | ## latentcode models ``` latentcode models ``` Fetches the current model list for your organization and team, then prints one `provider/model` ID per line. If the gateway can't be reached, it prints a warning and the last known list. | Flag | Description | | --- | --- | | provider | Only list this provider's models, for example `latentrouter`. | | --verbose | Print each model's metadata as JSON. | | --refresh | Refresh the cached model catalog first. | | --org, --team | Scope for this command only, as for `run`. | ## latentcode agent | Command | What it does | | --- | --- | | agent create | Describe what you want; a model writes the agent's prompt and saves it as a Markdown file. See Create an agent. | | agent list | List every agent with its mode and resolved permission rules. | | Flag | Description | | --- | --- | | --path | Write the agent to `/agents/` instead of asking. | | --description | What the agent should do. | | --mode | How the agent can be used. | | --permissions , --tools | Comma-separated permissions to allow; the rest are denied. Pass `""` to allow all. | | -m, --model | Model that generates the agent. | With all four of `--path`, `--description`, `--mode` and `--permissions`, it runs without prompts and prints the new file's path. ## latentcode mcp | Command | What it does | | --- | --- | | mcp add [name] | Add a server interactively, or directly with flags (below). | | mcp list · mcp ls | List servers and whether each is connected, disabled, failed or needs authentication. | | mcp auth [name] | Log in to an OAuth server. Without a name, pick from a list. | | mcp auth list | List OAuth-capable servers and their login status. | | mcp logout [name] | Remove stored OAuth credentials. | | mcp debug | Diagnose a server's OAuth connection. | Bash ``` latentcode mcp add docs --url https://example.com/mcp --header "Authorization=Bearer $TOKEN" latentcode mcp add files --env ROOT=/srv -- npx -y @modelcontextprotocol/server-filesystem /srv ``` With a name, give either `--url` (remote) or a command after `--` (local). `--header` only applies to remote servers and `--env` only to local ones; both take `KEY=VALUE` and repeat. Servers added this way go in your global config. See MCP servers. ## latentcode session, export and stats ### session list | Flag | Description | | --- | --- | | -n, --max-count | Only the N most recent sessions. | | --format | Default `table`, shown in a pager when output is a terminal. | ### session delete Deletes the session. ### export [sessionID] Prints the session and all its messages as JSON on stdout. Without an ID, you pick a session from a list. `--sanitize` redacts transcript text and file contents so you can share the structure. ``` latentcode export ses_abc123 ,>, session.json ``` ### stats | Flag | Description | | --- | --- | | --days | Only the last N days. Default: all time. | | --tools | How many tools to list. Default: all. | | --models [n] | Show per-model statistics, optionally only the top N. | | --project | Filter by project. `""` means the current project. | | --session | One session, including what its subagents spent. Needs the gateway. | | --org, --team | Scope for this command only. | ## latentcode pr ``` latentcode pr 128 ``` Runs `gh pr checkout 128` into a local branch named `pr/128` (replacing it if it exists), adds the fork as a remote for pull requests from forks, then starts the TUI. Needs the GitHub CLI, logged in, and must be run inside a git repository. ## latentcode plugin ``` latentcode plugin my-plugin --global ``` | Flag | Description | | --- | --- | | module | npm package name. | | -g, --global | Add it to your global config instead of the project's. | | -f, --force | Replace a version that's already installed. | ## serve, attach and acp `latentcode serve` runs LatentCode as a headless HTTP server. `attach` opens the TUI against it, and `run --attach` sends it one message. Bash ``` export LATENTCODE_SERVER_PASSWORD=choose-a-password latentcode serve --port 4096 # in another terminal latentcode attach http://localhost:4096 ``` | Flag | Description | | --- | --- | | --port | Port. Default `0`, a free port. | | --hostname | Interface. Default `127.0.0.1`. | Warning Without `LATENTCODE_SERVER_PASSWORD` the server has no authentication and prints a warning. Set it before binding to anything other than localhost. `attach ` takes `--dir`, `-c/--continue`, `-s/--session`, `--fork`, `-p/--password`, `-u/--username` and `--mini`, with the same meaning as above. `acp` takes `--port`, `--hostname` and `--cwd`. ## latentcode debug | Command | What it shows | | --- | --- | | debug config | The fully merged configuration LatentCode is using. | | debug paths | Where config, data, logs, cache and state live. | | debug info | Version, OS, terminal and loaded plugins. Include it in bug reports. | | debug agent | One agent's resolved configuration. | | debug skill | Every skill LatentCode found. | ## latentcode db Sessions and messages are stored in a local database. `latentcode db path` prints where it is, for example so you can back it up. ## upgrade and uninstall ### upgrade [target] Downloads the latest version, or `target` (for example `0.1.48`), from the LatentStack deployment you're connected to. ### uninstall Removes LatentCode's data, cache, config and state directories and, for a script install, the binary and the PATH line the installer added. It lists everything first and asks to confirm. | Flag | Description | | --- | --- | | -c, --keep-config | Keep your configuration. | | -d, --keep-data | Keep sessions and snapshots. | | --dry-run | Show what would be removed and stop. | | -f, --force | Don't ask for confirmation. | ## Other commands `latentcode completion` prints a shell completion script to add to your shell's startup file, for example `latentcode completion >> ~/.bashrc`. Source: https://latentstack.dev/docs/latentcode/cli --- # Slash commands Every built-in command you can type at the start of a prompt. Type / to see them, with your own commands, skills and MCP prompts. Aliases are shown after a slash. Commands that take arguments are shown with them. You can also run most commands from the command palette (`ctrl+p`), and any command with `latentcode run --command ` except those that only exist in the TUI. ## Sessions | Command | Does | Key | | --- | --- | --- | | /new · /clear | Start a new session. | `ctrl+x``n` | | /sessions · /resume · /continue | Switch to another session. | `ctrl+x``l` | | /rename | Rename this session. | | | /fork | Copy the session up to a message you choose into a new session. | | | /undo | Remove your last message and restore the files changed since. | `ctrl+x``u` | | /redo | Reverse an undo. | `ctrl+x``r` | | /compact · /summarize | Summarize the conversation to free context. | `ctrl+x``c` | | /timeline | Jump to a message. | `ctrl+x``g` | | /export | Save the transcript as Markdown and open it in your editor. | `ctrl+x``x` | | /copy | Copy the transcript to the clipboard. | | | /stats | Cost and token usage of this session, including subagents. | | | /add-dir \| status | Let this session use another directory without asking. | | | /push-to-registry | Share a summary of this session with your organization, for teammates to pull in with `@sync:`. | | See Sessions and context. ## Working on code | Command | Does | Key | | --- | --- | --- | | /init [focus] | Create or improve `AGENTS.md` for this project. | | | /review [pr \| branch \| commit ] [aspects] | Review changes with a team of reviewer subagents. Without a target, reviews uncommitted changes, including untracked files. Aspects: `code`, `errors`, `tests`, `types`, `comments`, `simplify`, `all`. | | | /diff | Open the diff viewer. | | | /goal \| status \| pause \| resume \| edit \| append \| clear | Keep working until a condition is met. | | | /bug-fix | Set a goal to find, fix, test and verify a bug. | | | /loop [interval] [prompt] \| status \| pause \| resume \| stop | Run a prompt repeatedly. | | | /debate [--rounds n] | Have several models debate a question. | | | /adopt copilot | Convert GitHub Copilot instructions into `AGENTS.md`. | | | /l-spec-explore · -propose · -apply · -update · -sync · -archive | The built-in spec-driven workflow, L-Spec: explore an idea, propose a change with a spec and tasks, apply it, update it, sync the specs, and archive the finished change. In Plan it only explores; switch to Build to write anything. | | See Goals and loops, Common workflows and Debate. ## Memory | Command | Does | Key | | --- | --- | --- | | /remember [type:] | Save a note to this project's memory. | | | /memory [status \| path] | Show what's remembered and where. | | See Memory. ## Models and agents | Command | Does | Key | | --- | --- | --- | | /models · /mo | Choose a model. | `ctrl+x``m` | | /effort · /reasoning · /variants | Choose the reasoning effort. | `ctrl+t` | | /agents | Choose an agent. | `ctrl+x``a` | | /fusion | Turn on Fusion. | | | /org · /orgs · /switch-org | Switch LatentStack organization. | | | /projects | Switch team within the organization. | | | /connect | Change the gateway URL and API key. | | See Models. ## Interface | Command | Does | Key | | --- | --- | --- | | /editor | Write the prompt in `$VISUAL` or `$EDITOR`. | `ctrl+x``e` | | /skills | Browse and run skills. | | | /mcps | Turn MCP servers on and off. | | | /themes | Choose a theme. | `ctrl+x``t` | | /thinking · /toggle-thinking | Show or hide the model's thinking. | | | /detail · /toggle-detail | Expand or collapse reasoning, summaries and tool activity. | `ctrl+l` | | /timestamps · /toggle-timestamps | Show or hide message times. | | | /status | MCP servers, language servers and formatters in use, and their status. | `ctrl+x``s` | | /help | Help. | | | /exit · /quit · /q | Quit. Typing `exit`, `quit` or `:q` on its own also works. | `ctrl+x``q` | Source: https://latentstack.dev/docs/latentcode/slash-commands --- # Environment variables Variables that change how LatentCode behaves for one process or one shell. Most have a config equivalent; use these for CI, scripts and quick experiments. Switches are on when set to `1` or `true`. Bash ``` LATENTCODE_DISABLE_AUTOCOMPACT=1 LATENTCODE_PURE=1 latentcode run "…" ``` ## Configuration | Variable | Effect | | --- | --- | | LATENTCODE_CONFIG | Path to an extra config file, applied after your global config and before project config. | | LATENTCODE_TUI_CONFIG | Path to an extra `tui.json`. | | LATENTCODE_DISABLE_PROJECT_CONFIG | Ignore project config: `latentcode.json`, `.latentcode` folders, project `tui.json` and project rule files. | | LATENTCODE_PERMISSION | Permission rules as JSON, merged over the `permission` config. See Permissions. | | XDG_CONFIG_HOME, XDG_DATA_HOME, XDG_CACHE_HOME, XDG_STATE_HOME | Move LatentCode's config, data, cache and state directories. See Files LatentCode keeps. | ## Behavior | Variable | Effect | | --- | --- | | LATENTCODE_PURE | Don't load external plugins. Same as `--pure`. | | LATENTCODE_DISABLE_AUTOCOMPACT | Don't summarize the conversation automatically. | | LATENTCODE_OS_SANDBOX | Set to `false` to run shell commands without the operating-system sandbox. On by default on macOS and Linux. | | LATENTCODE_FUSION | Turn on Fusion. Same as `--fusion`. | | LATENTCODE_SIDEKICK_MODEL | Fusion sidekick model, as `provider/model`. | | LATENTCODE_DISABLE_AUTOUPDATE | Don't check for updates. | | LATENTCODE_GIT_BASH_PATH | Windows: path to Git Bash, used to run shell commands. | ## Rules and skills from other tools | Variable | Effect | | --- | --- | | LATENTCODE_DISABLE_CLAUDE_CODE | Ignore `CLAUDE.md` files and `.claude/skills`. | | LATENTCODE_DISABLE_CLAUDE_CODE_PROMPT | Ignore `CLAUDE.md` files only. | | LATENTCODE_DISABLE_CLAUDE_CODE_SKILLS | Ignore `.claude/skills` only. | | LATENTCODE_DISABLE_EXTERNAL_SKILLS | Ignore `.claude/skills` and `.agents/skills`. | ## Terminal | Variable | Effect | | --- | --- | | LATENTCODE_DISABLE_MOUSE | Don't capture the mouse, so your terminal's own selection works. | | LATENTCODE_DISABLE_TERMINAL_TITLE | Don't change the terminal window title. | | VISUAL, EDITOR | Editor for `/editor` and `/export`. | ## Server | Variable | Effect | | --- | --- | | LATENTCODE_SERVER_PASSWORD | Password that `serve` requires (HTTP basic auth), and that `attach` and `run --attach` send. | | LATENTCODE_SERVER_USERNAME | Username for the same. Default `latentcode`. | ## Tools and language servers | Variable | Effect | | --- | --- | | LATENTCODE_DISABLE_LSP_DOWNLOAD | Don't download language servers automatically. | Source: https://latentstack.dev/docs/latentcode/environment-variables --- # Troubleshooting Find out what went wrong, fix the common problems, and reset LatentCode if you need to. ## First steps | Command | Tells you | | --- | --- | | latentcode config | Which gateway you're connected to, whether an API key is set, the default model and how many models were imported. | | latentcode models | Whether the gateway accepts your key right now, and your tier. | | latentcode debug config | The configuration LatentCode actually uses, after merging every file. | | latentcode debug info | Version, operating system, terminal and loaded plugins. Include it when you report a problem. | | latentcode debug paths | Where config, data, logs and cache are on this machine. | ## Logs Each run writes a log file to `~/.local/share/latentcode/log/`, named by the time it started, for example `2026-09-28T093951.log`. The 10 most recent are kept. When an unexpected error stops LatentCode, it prints the path of the log file to check. ``` latentcode --print-logs --log-level DEBUG run "hello" ``` `--print-logs` also writes the log to stderr, and `--log-level DEBUG` adds detail. Both work with every command. ## Connection problems "Invalid API key" The gateway rejected the key. It may have been regenerated, which invalidates the old one. Copy the current key from your Account page and save it again: ``` latentcode config set api-key ls-your-key ``` "Could not reach gateway (… → HTTP 404)" or "Could not reach …" The gateway URL is wrong or unreachable. It should be your LatentStack address followed by `/v1`. Check it with `latentcode config get base-url` and fix it with: ``` latentcode config set base-url https://your-host/v1 ``` If the URL is right, check your network, VPN or proxy. "No models returned for this key (empty tier?)" Your key works but your tier allows no models. Ask your administrator to assign models to your tier, then run `latentcode config models --refresh`. The Connect LatentRouter dialog keeps coming back The TUI needs both a gateway URL and an API key, and asks until both are saved. Enter them, or quit with `ctrl+c` and run `latentcode config set base-url …` and `latentcode config set api-key …`. A model I expect isn't in the list, or requests fail with a permissions error Models depend on your organization and tier. Check which organization is active with `/org`; run `latentcode models` to see what the gateway allows right now. ## Startup and configuration LatentCode stops at startup with a config error A config file has invalid JSON or a value of the wrong type. The message names the file, and for JSON syntax errors the line and column. Fix it, or move the file aside to check. Unknown keys don't cause errors; they're ignored, so a misspelled setting silently does nothing. Compare with `latentcode debug config`. My setting has no effect Another file may override it: project config beats global config, and settings your administrator enforces beat both. `latentcode debug config` shows the final values. `theme` and `keybinds` belong in `tui.json`, not `latentcode.json`. See Configuration. A plugin breaks LatentCode Start with `latentcode --pure` to skip external plugins. If that works, remove plugins from the `plugin` list or the `plugins/` folders one at a time. ## While working "Shell command could not start because OS sandbox preparation failed" Shell commands run in an operating-system sandbox. On Linux that needs bubblewrap: install the `bubblewrap` package so `/usr/bin/bwrap` exists. To run without the sandbox, set `LATENTCODE_OS_SANDBOX=false`. latentcode run prints "permission requested: … auto-rejecting" Nobody can approve requests in `run`, so they're rejected. Allow what the job needs in your permission config or `LATENTCODE_PERMISSION`, or use `--auto` in a disposable environment. The agent keeps asking about the same kind of command Choose Yes, don't ask again this session, or add an `allow` rule to your config to make it permanent. /undo removed my message but didn't restore the files File snapshots only work in git repositories, and only when `snapshot` isn't set to `false`. Untracked files over 2 MB aren't snapshotted. Run `git init` in projects you want to undo in. The conversation never compacts and hits the context limit Check that `compaction.auto` isn't `false` and `LATENTCODE_DISABLE_AUTOCOMPACT` isn't set. Compaction also needs the model's context window from your gateway; if the sidebar shows no limit, ask your administrator to set it. Run `/compact` to compact by hand. shift+return sends the message instead of adding a line Many terminals send the same key for both. Use `ctrl+j`, which works everywhere, or `alt+return`. See Keybindings. I can't select text with the mouse LatentCode captures the mouse for scrolling and clicking. Set `"mouse": false` in `tui.json` (or `LATENTCODE_DISABLE_MOUSE=1`) to give it back to your terminal. "Session not found" The ID passed to `-s` doesn't exist in this machine's database. `latentcode session list` shows the IDs you have. For MCP connection and login problems, see MCP servers. ## Update LatentCode checks for updates on start. When one has been installed it restarts once your sessions are idle, or tells you it will be used next time. To update by hand: ``` latentcode upgrade ``` Turn automatic updates off with `"autoupdate": false` in your global config, or get a notice without installing with `"autoupdate": "notify"`. ## Reset ### Reconnect To start the connection over while keeping your sessions and settings: Bash ``` latentcode config clear all latentcode config set base-url https://your-host/v1 latentcode config set api-key ls-your-key ``` ### Start from scratch These folders hold everything LatentCode keeps. Quit LatentCode and back them up before deleting anything: | Folder | Contains | Deleting it | | --- | --- | --- | | ~/.config/latentcode | Global config, API key, agents, commands, skills | Resets your settings and disconnects you. | | ~/.local/share/latentcode | Sessions database, memory, snapshots, logs, MCP logins | Deletes all sessions and memory. | | ~/.local/state/latentcode | Recent and favorite models, selected organization | Resets those choices. | | ~/.cache/latentcode | Cached downloads, such as the model catalog | Safe; it's rebuilt. | `latentcode uninstall` removes all of these and the program itself. Add `--keep-config` or `--keep-data` to keep settings or sessions, and `--dry-run` to see what would go. Warning There's no way to recover deleted sessions. Back up the file shown by `latentcode db path` first if you might want them back. Source: https://latentstack.dev/docs/latentcode/troubleshooting --- # LatentWork LatentWork is the LatentStack desktop app. You describe a task in plain language, and an agent does the work in a folder on your computer while you watch each step and approve anything sensitive. ## Who it's for LatentWork is for anyone who wants an agent to do real work with their files, not only engineers. You don't need a terminal. You pick a folder, type what you want, and LatentWork reads, creates and edits files in that folder for you: spreadsheets, documents, reports, web pages and code. If you prefer working in a terminal or an editor, the same agent is available as LatentCode. Both use your LatentStack API key and the models your organization allows. ## What it can do - Work in your folders. Each workspace is a folder on your computer. The agent reads what's there and creates or edits files in it. Workspaces and folders - Take attachments. Attach PDFs, Word documents, spreadsheets, images, text and code files to a message, or upload a whole folder into the workspace. Prompts and attachments - Show what it made. PDFs, Word documents, spreadsheets, slides, Markdown, HTML and images open in a side panel. You can edit Markdown, text and spreadsheets there. Files, artifacts and the browser - Browse the web. A built-in browser panel that the agent can drive for you. Files, artifacts and the browser - Ask before acting. The agent asks before running most shell commands, going online, touching sensitive files or leaving the workspace folder. Permissions and approvals - Connect your tools. Add MCP apps such as Notion, Linear, Sentry or Stripe, your own MCP servers, and skills. Apps, skills and extensions - Remember you. Save standing instructions and let the agent remember facts about you and your projects. Memory - Track cost. A per-task context and cost meter, and your account's usage over time. Models, teams and usage ## How it works The agent works on your computer. It reads and writes files in your workspace folders, and runs commands there when you allow it. Requests to the AI model go through your LatentStack gateway, so your organization's models and budgets apply. Your tasks, their messages and your workspace list are stored on your computer, not on the server. See Data and privacy for exactly what is stored where. ## System requirements | Platform | Build | | --- | --- | | macOS | Disk image (.dmg) | | Linux | AppImage | | Windows | Installer (.exe) | The app is downloaded from your LatentStack server, which hosts one build per platform. If it has none for yours, the installer says so. Builds are specific to a processor type. If the installed app doesn't match your computer's processor, LatentWork stops at an Install the correct LatentWork build screen instead of starting. You also need a LatentStack account and API key, and network access to your LatentStack server. Nothing else needs to be installed. ## Start here ### Install and first launch Install the app and connect it to your gateway. ### Quickstart Run your first task end to end in five minutes. ### Tasks and history Start, find, rename, archive and delete tasks. ### Workspaces and folders Add folders and give the agent access to more of them. ### Prompts and attachments Write tasks, attach files, use commands and skills. ### Files, artifacts and the browser Preview and edit what the agent makes. ### Permissions and approvals What the agent asks before doing, and how to answer. ### Models, teams and usage Pick a model, switch team, watch context and cost. ### Apps, skills and extensions Connect MCP apps and use skills. ### Memory Standing instructions and what the agent remembers. ### Settings reference Every settings page and switch. ### Troubleshooting Connection problems, stuck tasks and error messages. Source: https://latentstack.dev/docs/latentwork --- # Install and first launch Install LatentWork from your LatentStack server, connect it to your gateway, and pick the folder it works in. ## Before you begin - Your LatentStack API key. It starts with `ls-`. Copy it from the API Key card on your Account page, or select Generate API key there if you don't have one yet. - Your LatentStack server's address, for example `https://latentstack.dev`. It's the address of the site these docs are served from. - On macOS and Linux, `curl`. ## Install The LatentStack installer on the Install page installs LatentWork together with the LatentCode CLI and the editor extension. To install only the desktop app, run: ``` curl -fsSL https://latentstack.dev/install-desktop.sh | bash ``` The script downloads the app from your server and installs it: | Platform | What the script does | | --- | --- | | macOS | Installs LatentWork in Applications. | | Linux | Installs LatentWork and adds it to your app menu. | | Windows | Installs LatentWork with Start Menu and Desktop shortcuts. | If the script ends with `No … desktop build available`, your server has no LatentWork build for your platform. Ask your administrator. ## First launch Open LatentWork from Launchpad, Spotlight, your app menu or the Start Menu. The first time, you see the Welcome to LatentWork screen. - 01Enter your gatewayLatentRouter is the app's name for your LatentStack gateway. Under Connect to LatentRouter, fill in LatentRouter URL with your server's address, for example `https://latentstack.dev`, and paste your key into API Key. Show reveals the key so you can check it.Test Connection checks that LatentWork can reach the server and shows `Connection successful.` if it can. - 02Pick a folderSelect Pick a folder to get started. LatentWork saves the connection and opens a folder picker titled Authorize folder. Choose the folder you want the agent to work in. It becomes your first workspace. You can pick an empty folder or one that already has files. - 03Start workingLatentWork shows Creating workspace…, then opens a new task with the cursor in the message box, ready for your first instruction. Continue with the Quickstart. Note The connection is checked again when you continue Selecting Pick a folder to get started tests the connection first. If it fails, the error appears under the button and nothing is saved. See the connection errors below. The welcome screen appears only until you finish it. After that, if LatentWork has no API key, it shows a Connect to LatentRouter dialog on top of the app instead, with the same fields, Test Connection and Save & Continue. To change the connection later, use Settings → LatentRouter. ## Connection errors | Message | What it means | | --- | --- | | Server unreachable. Check the URL and try again. | LatentWork got no answer from that address. Check the URL, and that this computer can open it in a browser. | | Server returned an error (…) | Something answered, but not successfully. Check the URL points at your LatentStack server and not at another site. | | Invalid API key — the server rejected the credentials. | The server refused the key. Copy it again from your Account page. | Test Connection confirms the server is reachable. If the profile menu (bottom left) shows Gateway unreachable after you connect, see Troubleshooting. ## Updates LatentWork checks for new versions in the background and tells you when one is available. You choose when to download and when to restart. The controls are in Settings → Updates. Running the installer again also installs the latest version your server has. ## Uninstall The LatentStack uninstaller removes LatentWork along with the other tools. See Install. It also deletes your task history and settings unless you choose to keep them. Your workspace folders are never touched. ## Installation FAQ macOS says the app is damaged or from an unidentified developer This happens when the app was downloaded in a browser. Reinstall with the install script. macOS: it was installed in my own Applications folder, not the main one It works from either place. Linux: nothing happens when I open the AppImage myself Use the install script instead of opening the AppImage directly. Where do I get an API key? From your Account page. Regenerate replaces your key, and the old one stops working immediately, including in LatentWork and LatentCode. Source: https://latentstack.dev/docs/latentwork/install --- # Quickstart Ask LatentWork to build a spreadsheet, approve what it asks, open the result, and change it with a follow-up. ## Before you begin Install LatentWork and finish the welcome screen, as described in Install and first launch. You should be looking at an empty task in your first workspace, with the message box at the bottom showing Describe your task.... ## 1. Describe the task Click in the message box and type: ``` Create a CSV file called expenses.csv with 15 rows of made-up business expenses: date, vendor, category and amount. Then tell me the total per category. ``` Press `Enter` or select Run task. Use `Shift`+`Enter` when you want a new line instead of sending. The model and team selectors under the message box show what this task uses. The defaults are fine for this example; see Models, teams and usage to change them. ## 2. Follow the work While the agent works, the task view shows what it is doing: - Thinking while it plans. Turn on Show model reasoning in Settings → Preferences to read the reasoning when the model provides it. - Each step as it happens: files it reads or writes, searches, and commands it runs. - A Progress list above the message box when the agent breaks the work into steps, updated as it finishes each one. The task also gets a title from your first message, shown in the sidebar under your workspace. ## 3. Answer approvals Writing a CSV in your workspace doesn't need approval. If the agent wants to do something that does, such as run a command that changes things or fetch a web page, a panel appears above the message box, for example Run a shell command?, with three choices: - Deny: refuse the request. - Allow once: allow this request only. - Allow for session: allow this and matching requests for the rest of this task. The task waits until you answer. See Permissions and approvals for what the agent asks about. ## 4. Open the result When the agent finishes, it names the file it made, such as `expenses.csv`, and lists the totals. Open the file: - 01Click the fileClick the file name in the reply, or the Artifacts button at the top right of the task. The file opens in a panel on the right. - 02Edit it if you likeCSV files open as an editable table. Change a cell, add a Row or a Column, then select Save to write it back to the file. Discard throws away your edits. - 03Find it on diskShow in folder opens the file's folder in Finder or File Explorer. Download artifact saves a copy somewhere else. Tip Open files automatically Turn on Auto-open generated files in Settings → Preferences to open documents and files the agent creates as soon as they appear. ## 5. Follow up A task keeps its conversation and its files. Send a follow-up in the same task: ``` Add a chart of the totals as a Markdown report called expenses-report.md ``` If you send a message while the agent is still working, `Enter` doesn't send it straight away. Choose Steer to send it now and let the agent adjust mid-task, or Queue to send it once the agent finishes. To stop the agent, select Stop, or press `Esc` twice in the message box. ## Next steps - Prompts and attachments: attach PDFs and spreadsheets, use `@` and `/`. - Tasks and history: find, rename, branch and revert tasks. - Apps, skills and extensions: connect the tools you already use. Source: https://latentstack.dev/docs/latentwork/quickstart --- # Tasks and history Every conversation with the agent is a task. Start tasks, find old ones, organize them in the sidebar, and roll a task back when it goes the wrong way. Note Tasks and sessions are the same thing Some places in the app say session instead of task; they mean the same thing. ## Start a task Each task belongs to one workspace and works in that workspace's folder. To start one: - Select + (New task) on the workspace in the sidebar. - Press `⌘`+`N` on macOS or `Ctrl`+`N` on Windows and Linux, when you're not typing in a text field. The task starts in the selected workspace. - Open the command palette (`⌘`/`Ctrl`+`K`) and choose Create new session. A new task is called New session until you send your first message. It's then titled from what you asked. ## The sidebar The sidebar lists your workspaces, each with its tasks underneath. Expand or collapse a workspace to show or hide its tasks. Long lists show the first few tasks and a Show … more link. A dot beside a task means it's working right now. - Pinned tasks stay at the top. - Groups collect tasks under a heading of your choice, such as Done or In progress. Tasks in no group appear under Ungrouped. - Archived tasks move to a collapsed Archived section at the bottom of the workspace. Hide or show the sidebar with `⌘`/`Ctrl`+`B`. Drag its edge to make it wider. ## Task menu Hover a task and select … for these actions. Right-clicking a task offers the most common ones. | Action | What it does | | --- | --- | | Pin session | Keeps the task at the top of the workspace. Unpin session undoes it. | | Rename session | Opens Rename session. Type a new Session name and select Save. | | Open in split view | Shows this task beside the one you have open, so you can read both. Only offered for another task in the workspace that's open. Close split view (or Close pane) goes back to one. | | Move to group | Moves the task into a group, or to No group. New group... asks for a name and creates one. | | Archive session | Moves the task into Archived. Unarchive session brings it back. | | Delete session | Asks Delete session? first, then permanently deletes the task and its messages. | Pins, groups and the order of tasks are kept on this computer only. Warning Delete can't be undone Deleting a task removes its conversation for good. Files the agent created or changed in your workspace stay where they are. ## Find a task Press `⌘`/`Ctrl`+`K` and choose Search sessions. Type part of a task's title or its workspace name, use the arrow keys to pick one, and press `Enter` to open it. Tasks in the workspace you're in are listed first, then the rest, newest first. Search matches titles and workspace names, not the text of messages. Rename tasks you want to find later. ## Message actions Hover a message to see its actions. | Action | On | What it does | | --- | --- | --- | | Edit message | Your messages | Rolls the task back to before that message and puts its text in the message box, so you can change it and send it again. Not available for messages with attachments. While the agent is working it's Stop and edit. | | Copy | Any message | Copies the message text. | | Branch in new chat | Any message | Starts a new task containing the conversation up to that point. The original task is unchanged. | | Revert | Any message | Rolls the task back to just before that message, removing it and everything after it, and undoes the file changes the agent made in that part. | ### When to revert and when to branch Revert when the agent went the wrong way and you want the files back as they were. Branch when you want to try a different direction and keep the original task too. ## Long tasks and context Every model can read a limited amount of conversation at once, its context window. The ring next to the message box shows how full it is. When a task gets close to the limit, LatentWork summarizes the earlier conversation so the task can continue (this is on by default). You can also type `/compact` to do it yourself. See Models, teams and usage. ## Where tasks are stored Tasks are stored on your computer, in LatentWork's app data folder, not on your LatentStack server. A task appears only while its workspace is in the sidebar: remove the workspace and its tasks are hidden but kept, and they come back when you add the same folder again. See Data and privacy for the exact location. Source: https://latentstack.dev/docs/latentwork/tasks --- # Workspaces and folders A workspace is a folder on your computer that the agent works in. Add a workspace for each project, and authorize extra folders when a task needs files from elsewhere. ## What a workspace is When you add a workspace, LatentWork can read the files in that folder and create and edit files there for you: spreadsheets, documents, images, anything. You can drop files into the folder at any time and the agent can pick them up. Each workspace has its own tasks, its own connected apps, and a few settings of its own (see Workspace settings). Your first workspace is the folder you picked on the welcome screen. ## Add a workspace - 01Open Create WorkspaceSelect Add workspace at the top of the sidebar, then choose Local workspace (Create a workspace on this device.). - 02Pick the folderSelect Select folder and choose the folder. The path appears in the dialog; Change picks a different one. - 03Create itSelect Create Workspace. The workspace appears in the sidebar, named after the folder. To switch workspace, select it in the sidebar. The task you last had open in it opens again. ## Workspace menu Hover a workspace in the sidebar and select … (Workspace options): | Action | What it does | | --- | --- | | Edit name | Changes the name shown in the sidebar. The folder isn't renamed. | | Share... | Opens Share workspace. | | Reveal in Finder | Opens the folder in Finder (Reveal in Explorer on Windows). | | New group... | Creates a group for organizing this workspace's tasks. See Tasks and history. | | Remove workspace | Asks first, then removes the workspace from the sidebar. Its tasks and the files on disk are kept. | ## Folders outside the workspace The agent can work anywhere inside the workspace folder without asking. Before it reads or edits anything outside it, it asks with Access an external folder? (see Permissions and approvals). If a workspace regularly needs another folder, authorize it once instead: - 01Open PermissionsOpen Settings and select Permissions, under Workspace. It applies to the workspace you have selected. - 02Add the folderUnder Authorized folders, select Add folder and choose the folder. The list saves right away. The agent can then read and edit files in that folder without asking, in this workspace only. The workspace folder itself is always listed first, marked Workspace root, and can't be removed. Select × next to any other folder to remove it. Warning Authorize with care An authorized folder is open to the agent in every task in the workspace, for reading and for editing. Don't authorize your whole home folder; add the specific folders a project needs. ## Workspace settings The Workspace group in Settings applies to the workspace selected in the sidebar. Select a different workspace first to change its settings. | Setting | Per workspace | | --- | --- | | Preferences | Auto context compaction is set per workspace. The other two switches on the page apply everywhere. | | Permissions | Authorized folders. | | Extensions | Apps you connect, and skills saved in the workspace. | ## Files LatentWork adds to a workspace | Path in the folder | What it holds | | --- | --- | | .latentcode/skills/ | Skills saved for this workspace. See Skills. | | .latent/docs/ | Copies of documents you attach to messages, so you can open them again from the conversation. | These are ordinary files. If the folder is shared, synced or under version control, they travel with it. The workspace's settings, such as authorized folders and connected apps, aren't stored in the folder: LatentWork keeps them on this computer. Source: https://latentstack.dev/docs/latentwork/workspaces --- # Prompts and attachments Everything you ask starts in the message box at the bottom of a task. Attach files, point at files in the workspace, run commands and skills, and steer the agent while it works. ## Write a task Type what you want in the message box (Describe your task...) and press `Enter` or select Run task. `Shift`+`Enter` starts a new line. Good tasks say what to produce and where: - Summarize the attached contract in one page and save it as contract-summary.md. - Rename every photo in this folder to its date, like 2026-03-14-001.jpg. - Read sales.xlsx and make a slide deck of the five biggest changes since last quarter. The agent works in the task's workspace folder. When it creates a file, it tells you the path so you can open it; see Files, artifacts and the browser. Long pasted text collapses into a chip such as Pasted · 12 lines. The full text is sent. ## Attach files Attach files to a message in any of these ways: - Select the paperclip (Attach files) and choose files. - Drag files onto the message box. - Paste an image or file from the clipboard. - To add a whole folder, select Upload a folder next to the paperclip, or drag one folder onto the message box. See Upload a folder. Attached files show as chips above the message. Select Remove on a chip to take it off. You can attach up to 8 files per message; extra files are left out with a warning. While attached PDFs are being prepared for the agent, a Preparing N files… row shows under your message. It goes away once the agent starts on the task. | Type | Extensions | Size limit | | --- | --- | --- | | PDF | .pdf | 100 MB | | Images | .png .jpg .jpeg .gif .webp .bmp .svg .avif .heic .tif .tiff .ico | 25 MB | | Word | .docx | 25 MB | | Excel | .xlsx .xls | 25 MB | | PowerPoint | .pptx .pptm .potx | 100 MB | | CSV and TSV | .csv .tsv | 10 MB | | Text and code | .txt .md .json .yaml .html .css .py .js .ts .sql and many more | 5 MB | Text taken from a single file is limited to 200,000 characters. Anything beyond that is cut off, and the model is told the file was truncated. A PowerPoint file is saved to `uploads/attachments` in the workspace when you send the message, and the agent reads it there, with the `pptx` skill when you have it. Select the chip to see the slides. If the file can't be saved, the message isn't sent and stays in the message box. ### Files that can't be attached These are refused when you attach them, with a message saying what to do instead: | Files | Do this instead | | --- | --- | | .ppt (older PowerPoint) | Save as .pptx. | | .doc .docm (older Word) | Save as .docx. | | .rtf | Save as .docx. | | .odt .ods .odp (OpenDocument) | Save as .docx, .xlsx or PDF. | | .key .numbers .pages (Apple iWork) | Export to PDF or an Office format. | Other unknown types are refused with `.xyz files aren't supported yet.` Files with no extension are refused unless they're a well-known text file such as `README` or `LICENSE`. Note The agent can already read your workspace You don't need to attach files that are already in the workspace folder. Mention them instead (below), or name them in your message. ### Delete an attached document LatentWork keeps a copy of each document you attach so the agent can read it. To delete that copy after sending, hover over the attachment's chip in the conversation, select the bin (Delete …), and confirm. The agent can no longer read the document. The chip stays in the conversation but no longer opens. ### Page references in PDF answers When Cite pages from attached PDFs is on in Settings → LatentRouter, answers taken from an attached PDF include a reference to the page used. Clicking it opens the PDF at that page in the side panel. Your organization's administrator has to allow it first. ## Upload a folder To give the agent a whole folder of documents, select Upload a folder (the folder button next to the paperclip) and choose a folder, or drag one folder onto the message box. - The folder is copied into the workspace at `uploads/`, with its subfolders kept. If that name is already taken, a number is added, such as `uploads/reports-2`. - The folder isn't attached to your message, so the 8-attachment limit doesn't apply. Ask the agent about its files by name or path, for example "Summarize every PDF in uploads/reports". - Common dependency, build and system folders and files, such as .git, node_modules, build output and .DS_Store, are skipped. - Drop one folder at a time. | Limit | Value | | --- | --- | | Files per folder | 5,000 | | Total size | 200 MB | | Size of one file | 100 MB | While it uploads, a notice shows Uploading X of N files…. Select Cancel to stop. The upload is all or nothing: if any file fails, nothing is saved and you can try again. If some file names can't be stored in the workspace, Some files can't be uploaded lists them with the reason. Select Cancel to rename them first, or Upload the other N to upload the folder without them. For other messages, see Troubleshooting. ## Mention files with @ Type `@` to mention a file from the workspace. Keep typing to search; the list shows up to 8 matches, including files you used recently. Use `↑` `↓` and `Enter` or `Tab` to insert one, or `Esc` to close the list. ## Commands and skills Type `/` in an empty message box to list commands and skills. Keep typing to filter. Choosing a command inserts it, such as `/compact`; choosing a skill inserts a skill chip, and the agent follows that skill for the task. | Built-in command | What it does | | --- | --- | | /compact | Summarizes the task so far to free up context. Use it when the context meter warns you. Needs a task with messages. | The plug button (Commands, skills, and MCPs) opens the same things as a menu with four tabs: | Tab | Shows | | --- | --- | | Commands | Commands available in this workspace. | | Skills | Installed skills. Choosing one inserts it into your message. | | Extensions | Enabled built-in extensions. Choosing one starts your message for you, for example "Use the LatentWork Browser extension to ". | | MCPs | Apps connected to this workspace and their status. | Configure in that menu opens the matching settings page. See Apps, skills and extensions. ## While the agent is working You can keep typing while the agent works. What happens to the message depends on the button you choose: | Button | What it does | | --- | --- | | Steer | Sends now and lets the agent adjust mid-task. | | Queue | Sends once the agent finishes the current task. The button shows how many are waiting, such as 2 queued, and the waiting messages are listed above the message box, where you can remove them. | | Stop | Stops the agent. | Pressing `Enter` while the agent is working doesn't send: the Steer and Queue buttons shake to remind you to pick one. Pressing `Esc` shows Hit Escape again to stop the agent; press it again within 3 seconds to stop. ## Controls under the message box | Control | What it sets | | --- | --- | | Model | The model this task uses. Its button shows the model name. | | Organization | Which organization the task runs under. Shown only if your key belongs to more than one. | | Teams | The team whose model list and limits apply, or No team. Shows the team's name once you pick one. | | Behavior | Model variants such as reasoning effort. Shown only when the model offers them. | They can't be changed while the agent is working. See Models, teams and usage. Source: https://latentstack.dev/docs/latentwork/composer --- # Files, artifacts and the browser The panel on the right of a task shows what the agent made, lets you browse the workspace, and holds a web browser and a terminal. ## Panel buttons The buttons at the top right of a task open the side panel. Select the same button again to close it. | Button | Opens | | --- | --- | | Browser | The built-in web browser. | | Files | A searchable folder tree of the workspace. | | Artifacts | The files this task created or mentioned. The button shows how many, and reads No artifacts yet until there are some. | | Terminal | A terminal in the workspace folder. Also `⌘`/`Ctrl`+`J`. | | Voice Mode | The voice panel, when the Voice Mode extension is enabled. See Apps, skills and extensions. | The panel can hold several tabs at once, for example two documents and a web page. Drag the divider to resize it. ## Artifacts When the agent creates or updates a file, it names the file in its reply. Click the name, or use the Artifacts button, to open it in the panel. To open new files automatically as they appear, turn on Auto-open generated files in Settings → Preferences (off by default). ### What opens in the panel | Kind | Extensions | In the panel | | --- | --- | --- | | Markdown | .md .markdown .mdx | Formatted. Edit shows the source for editing. | | Spreadsheets | .csv .tsv .xlsx .xlsm .xlsb .xls .ods | An editable table. | | Word | .docx .docm | The formatted document, read-only. | | PDF | .pdf | The pages, read-only. | | Slides | .pptx .pptm | The slides, read-only. | | Web pages | .html .htm | The rendered page. Edit shows the source for editing. | | Images | .png .jpg .jpeg .gif .webp .svg | The image. | | Text and code | Text files in the workspace | The text. Edit makes it editable. | Anything else shows Preview unavailable. Open externally to view this file. Use Show in folder and open it with another app. ### Artifact controls | Control | What it does | | --- | --- | | Edit | Switches Markdown, text and web pages to an editor. Save changes writes the file; Discard changes drops your edits. | | Download artifact | Saves a copy of the file somewhere you choose. | | Show in folder | Opens the folder that contains the file. | | Close artifact | Closes this tab of the panel. | ### Edit a spreadsheet Spreadsheets open as a table you can type into. + Row and + Column add space, Discard throws away your edits, and Save writes the file. Warning Saving an Excel file keeps only the first sheet's values The table shows the first sheet of a workbook. Saving writes a new workbook with just that sheet's values, so other sheets, formulas and formatting are lost. Ask the agent to make changes to workbooks with several sheets or formulas, or save a copy first. CSV and TSV files have no such limit. ## Browse workspace files Files shows the workspace as a folder tree. Select a folder to expand it, and a file to open it in the panel. Long folders show the first entries; select See more to load the rest. Type in Search workspace files to filter by name. Refresh files picks up files added since you opened the panel. ### Delete uploaded files and folders You can delete files and folders you uploaded, from inside the uploads folder. Hover over the item and select the bin (Delete ). - For a file, Delete this file? asks you to confirm. Select Delete. - For a folder, Delete this folder? asks you to type the folder's name exactly, then select Delete folder. Any searchable pages made from it, such as from PDFs, are removed too, so the agent can no longer read it. This can't be undone. Only items inside uploads can be deleted here; ask the agent or use your file manager for anything else. To delete a document you attached to a message, see Delete an attached document. ## The built-in browser The Browser panel is a web browser inside LatentWork. Type an address in Enter URL..., use Back, Forward and Reload, and open more pages with New tab. Right-click a tab for Copy URL, Open in Browser (your usual browser), Close Tab and Close All Tabs. The agent can use this browser too, through the LatentWork Browser extension, which is enabled by default. Ask for things like: - Open example.com in the browser and list the links on the home page. - Search the web for three suppliers of recycled packaging and put them in suppliers.csv. The browser stays visible while the agent works, so you can watch each step. ### Web apps the agent starts When the agent builds a website and starts it on your computer, it gives you an address such as `http://localhost:5173`. Click it to open it in the browser panel. The command palette's Accessible items lists the servers and artifacts found in the current task, so you can reopen them. ## The terminal Terminal opens a terminal at the bottom of the task, in the workspace folder, using your usual shell. It's yours: commands you type here run directly, without the agent and without approvals. Hiding it keeps it running, and the button then reads Terminal (running). Select Close terminal to end it. Source: https://latentstack.dev/docs/latentwork/files --- # Permissions and approvals The agent works freely inside your workspace, but asks before anything riskier: most shell commands, going online, sensitive files, and folders outside the workspace. ## When the agent asks A request appears in a panel above the message box, and the task waits until you answer. The panel shows what kind of request it is (Permission), what it covers (Scope), such as the command or the files, and a Details section with everything the agent sent. | Panel title | The agent wants to | | --- | --- | | Run a shell command? | Run a command in the workspace. Scope shows the command. | | Modify files? | Change a protected file, such as a credentials or configuration file. | | Read files? | Read a file that holds passwords, keys or other credentials. | | Access an external folder? | Read or change something outside the workspace folder. | | Start a subtask? | Hand part of the work to another agent. | | Approve …? | Anything else, named after the permission, for example `Approve webfetch?` (the agent wants to open a web page). | | Doom Loop Detected | The agent keeps repeating the same step. Deny to stop it, or allow it to keep trying. | ## Your choices | Choice | Effect | | --- | --- | | Deny | Refuses the request. Any other requests the task is waiting on are refused too. | | Allow once | Allows this one request. The next similar request asks again. | | Allow for session | Allows this request and remembers it for the rest of the task, so matching requests go through without asking. Other tasks still ask. | The panel's own advice: allow once for this request, or allow for session when you trust this scope. A request allowed for the session is remembered only while LatentWork is running. Warning Read the scope before allowing a command for the session Allowing a shell command for the session allows commands that match the same pattern for the rest of the task. If you're not sure what a command does, choose Allow once. ## What needs approval These are the agent's default rules. ### Asks first - Shell commands, except a few that only look at files without changing anything. - Going online: fetching web pages, web searches and other network access. - Reading secrets: files that hold passwords, keys and other credentials. - Editing protected files: credentials, project configuration files, and LatentWork's own settings in the workspace. - Anything outside the workspace folder, unless you authorized that folder. - Repeating itself: the agent keeps repeating the same step. ### Doesn't ask - Reading, creating and editing other files in the workspace folder and in authorized folders. - Searching and listing files. - Keeping its progress list, and using skills. ## Give access to another folder If a workspace often needs files from another folder, authorize it in Settings → Permissions instead of approving each request. The agent can then read and edit it without asking, in that workspace only. See Folders outside the workspace. ## Your own terminal Approvals apply to the agent. Commands you type yourself in the Terminal panel run straight away. See The terminal. Source: https://latentstack.dev/docs/latentwork/approvals --- # Models, teams and usage LatentWork uses the models your organization allows through your LatentStack gateway. Pick one per task, switch team or organization, and keep an eye on context and cost. ## Where the model list comes from Once LatentWork is connected to your gateway, the model list is exactly the models your tier allows, for the organization and team you've selected. To get a model added, ask your organization's administrator; see Admin Console. ## Choose a model for a task The model button under the message box shows the task's model. Select it, type in Search models... to filter, and pick one. The choice applies to this task only and is remembered for it. New tasks start with your team's default model, as set by your administrator, or the first model on the list if there's no default. If you switch to a team whose tier doesn't include a task's model, the task moves to the new default. Some models have variants, such as how much they reason before answering. For those, a Behavior menu appears next to the model. The model, organization and team can't be changed while the agent is working. Note Model no longer available If a task's model has been removed from your tier, the message box shows Model no longer available, and sending fails with `Selected model is unavailable. Choose another model before sending.` Pick another model and send again. ## Organizations and teams Your organization and team decide which models you can use, which limits and budgets apply, and where your usage is counted. ### Team The Teams button under the message box lists the teams you belong to, each with its tier. Choose one, or No team. The model list reloads for that team; a spinner shows while it does. The button then shows the team's name. ### Organization If your API key belongs to more than one organization, you can switch in three places: - The organization button under the message box. - The profile menu at the bottom left of the sidebar, under Organization. - Settings → LatentRouter, under Organization. Default follows your default organization. Switching organization clears the selected team and reloads the model list. Changing team or organization takes effect right away. Changing the gateway URL or API key stops running tasks. ## Context and cost Once the first reply arrives, a ring appears at the right end of the row under the message box. It fills as the task uses up the model's context window, and turns red at 80%. Click it for the detail: - How full the context is (… of context), in tokens and as a percentage, and the number of turns. - The cost of the task so far, as reported by the provider, or cost not reported. - A line per model used, with tokens split into in, out, cache r (cache reads), cache w (cache writes) and, when the model reports it, reasoning. Cost comes from the provider, not an estimate. If the model's context window is unknown, no percentage is shown. ### Running out of context With Auto context compaction on (the default, in Settings → Preferences), the agent summarizes the earlier conversation by itself when the context fills up, and the task carries on. The summary keeps what matters; nothing is deleted. With it off, LatentWork warns you at 80%, 90% and 95% with Context N% full. Type `/compact` and send it to summarize the task yourself. ## Usage over time Settings → Usage shows your spend through the gateway: Cost, Calls, Input tokens and Output tokens, then a table by model with cost, calls and tokens. Choose 7d, 30d (the default) or All. | What you see | Meaning | | --- | --- | | Loading usage… | Fetching from the gateway. | | No usage recorded yet. | No calls in that period. | | An error message | The gateway couldn't be reached or refused the key. | These are your account's figures from the gateway. For more detail, use the My Usage page in the console. Source: https://latentstack.dev/docs/latentwork/models --- # Apps, skills and extensions Give the agent more to work with: connect apps over MCP, add skills that teach it how to do a job, and turn on built-in extensions. ## Where to find them Open Settings and select Extensions, under Workspace. Everything here belongs to the workspace selected in the sidebar. The page has: - Add Custom App, to connect your own MCP server. - A search box (Search extensions...) and filters: All, MCPs, Skills and Show hidden. - Available apps: apps you can connect in one click, built-in extensions, and your installed skills. Select a tile to see its details and connect it. - Your apps: the apps connected to this workspace, with their status. - Advanced settings: where the configuration file is, for editing by hand. Refresh, at the top, reloads the lists. ## Connect an app Apps are MCP servers: they give the agent tools for a service such as Notion or Linear. - 01Choose the appUnder Available apps, select the app's tile (Tap to connect). Its details open, including whether it needs you to sign in. - 02ConnectSelect Connect. The app is added to this workspace. - 03Sign in, if askedFor apps that use your account, LatentWork opens your browser to sign in. Follow the steps there. If the browser can't hand back to LatentWork, paste the callback URL or code it shows into Callback URL or code and select Complete connection. - 04ReloadA Reload required notice appears: LatentWork needs a quick reload to use the new app. Select Reload now, or Later to finish what you're doing first. | App | What it's for | Sign-in | | --- | --- | --- | | Notion | Pages, databases, and project docs in sync. | Yes | | Linear | Plan sprints and ship tickets faster. | Yes | | Sentry | Track releases and resolve production errors. | Yes | | Stripe | Inspect payments, invoices, and subscriptions. | Yes | | Context7 | Search product docs with richer context. | No | Once connected, just ask: "Create a Linear issue for the bug we found", or "Summarize the Q3 planning page in Notion". The agent picks the app's tools itself. You can also point it at one from the MCPs tab of the plug menu in the message box. ## Add a custom app Connect any MCP server, such as an internal tool or a hosted app. - 01Open Add Custom AppSelect Add Custom App at the top of Extensions. - 02Describe the serverFill in App name with a name you'll recognize, then choose a Type:Remote (URL): enter the Server URL the app's provider or your administrator gave you. Tick This app requires sign-in if it needs you to sign in.Local (command): enter the Command that starts the app on this computer, as given in the app's instructions. - 03Add itSelect Add App, sign in if asked, and select Reload now when prompted. ## Manage connected apps Each app under Your apps shows its status: | Status | Meaning | | --- | --- | | Ready | Connected and available to the agent. | | Sign in needed | Select Sign in to connect your account. | | Paused | Disabled. The agent can't use it until you enable it. | | Offline | Not connected. Check the server is running and reachable. | | Issue | Something went wrong. The error is shown with the app. | Select an app to see its details: Connection is Cloud (sign in with your account) or Local (runs on this device), and Technical details shows how it's configured. From there you can Disable or Enable it, Log out of its account (which removes the stored sign-in), or Remove it from the workspace. ### Edit the configuration file Advanced settings shows the path of the config file for This workspace or All workspaces, and opens it in Finder or File Explorer. Reload LatentWork after editing it. ## Skills A skill is a written procedure that teaches the agent how to do a particular job, such as filling in a report template or following your house style. The agent reads a skill's description and uses it when it fits the task. ### Use a skill - Just ask. If a skill fits the task, the agent uses it. - To choose one yourself, type `/` in an empty message box and pick it, or open the plug menu and pick it from Skills. It's added to your message as a chip. ### See installed skills In Extensions, choose the Skills filter. Select a skill to see its description, where it's stored and the start of its instructions. Reveal in Finder opens its folder. ### Where skills come from Skills saved in this workspace, skills installed with LatentStack, skills you already use with other agent tools, and skills synced from your organization's skill registry. Synced skills show a Synced tag. They're read-only here: select View (instead of Edit) to read them. Any change made on this computer would be replaced the next time the skill syncs, so edit it in the registry instead, or select Override in project to make your own copy in this workspace. Synced skills can't be uninstalled here. The desktop app syncs the skills in your SkillPatch library, which include the Word, Excel, PowerPoint and PDF skills, using your LatentStack API key. They download when the agent first looks for skills; with no connection, it uses the skills already on this computer. A skill you keep locally with the same name is used instead of the synced one. To turn syncing off, add `SKILLPATCH_BASE` with an empty value to `~/.config/latentwork/env.json` (`%APPDATA%\latentwork\env.json` on Windows) and restart the app. A skill without a description shows Agent can't see this. The agent never sees it, so it's never used. Add a description to fix it. ### Add a skill Ask the agent to write one, for example "Turn how we just built this report into a skill called weekly-report". Select Reload now if LatentWork shows Reload required. Write a skill by hand Create a folder in the workspace's `.latentcode/skills/` folder with a `SKILL.md` file inside. Give it a short name, and a description that says what the skill does and when to use it: this is what the agent reads to decide. The description is required: a skill without one is never used. .latentcode/skills/weekly-report/SKILL.md ``` --- name: weekly-report description: Build the weekly sales report from sales.xlsx. Use when asked for the weekly report. --- 1. Read sales.xlsx and total revenue by region for the last 7 days. 2. Compare with the previous 7 days. 3. Write reports/weekly-.md with a table and three bullet points of highlights. ``` ### Remove a skill Open the skill and select Uninstall. This deletes the skill's folder from the workspace. Skills installed with LatentStack and synced skills can't be uninstalled here. To just keep a skill out of the list, select Hide; Show hidden brings it back. ## Built-in extensions Built-in extensions appear under Available apps. Select one to see what it needs, and to enable or set it up. Extensions marked Preview are still in development. | Extension | What it does | Needs | | --- | --- | --- | | LatentWork Browser | Lets the agent drive the built-in browser panel. See The built-in browser. | Enabled by default in the desktop app. | | OpenAI Image Gen | Generates images as files in the workspace. | An OpenAI API key, entered in the extension's details. | | Voice Mode | Talk to LatentWork through a voice panel. Preview. | Enabling, and an OpenAI API key. | | Google Workspace | Help with meetings, selected Drive files, and Gmail drafts. Preview. | Connecting your Google account. | Show hidden shows tiles you've hidden. Selecting Hide on any tile moves it there. Enabled extensions also appear in the Extensions tab of the plug menu in the message box. Choosing one starts your message, such as "Use the OpenAI Image Gen extension to ", for you to finish. Source: https://latentstack.dev/docs/latentwork/extensions --- # Memory LatentWork can remember things about you and your projects so you don't have to repeat them, and always follow standing instructions you write yourself. ## How memory works As you work, the agent saves short notes about things worth keeping: how you like answers, facts about a project, decisions you've made. It uses them in later tasks. Each note records what it remembers and why. Memory is personal. It's kept on this computer, and it's never shared with anyone you share a workspace with. Open it in Settings → Memory, under Global. | Group | Applies | | --- | --- | | About you | In every project. | | The workspace's name (This project) | Only in the workspace selected at the top of the Memory page. | To see another workspace's memories, pick it with the workspace selector next to the Memory title. ## Ask the agent to remember something Tell it in a task, in your own words: ``` Remember that our fiscal year starts in April. ``` When it has nothing saved yet, the Memory page suggests exactly this: tell the agent something you'd otherwise have to repeat, such as "always give me the diff first", and it keeps it. ## Your instructions Your instructions are standing rules in your own words, for example: ``` Always reply in British English. Never open with a summary of what I asked. ``` - The agent always follows them, and they win over anything it has worked out for itself. - Only you can change them; the agent can never edit or delete them. - They are not memories and don't appear in the memory lists. Type them in the box and select Save instructions. When they're saved, the page shows Saved — the agent is following this. Discard changes undoes unsaved edits. ## Review, edit and delete memories - 01Open a groupUnder What is remembered, select Open on About you or on the workspace. Each group shows how many memories it holds. - 02Find a memoryType in Search memories. Click a memory to expand it and see the full note, why it was saved, and when. - 03Edit or delete itSelect the pencil to change What it remembers and Why it remembers this, then Save. Select the bin to delete it, and confirm with Delete. There's no undo. Changes apply to new tasks. Long lists are split into pages with Previous and Next. ### Forget everything about you In the About you group, Forget all deletes every memory in it after you confirm. Workspace groups have no forget-all button; delete their memories one at a time. ## Stop the agent from remembering Turn off Let the agent remember new things at the top of the Memory page. The agent stops saving new memories, and tells you plainly when it can't save rather than pretending it did. What it already remembers stays, and is still used. Note Memory switched off entirely If Memory is missing from Settings, or the page says memory has been switched off, memory has been turned off for this installation. Contact your administrator. Source: https://latentstack.dev/docs/latentwork/memory --- # Settings reference Every page in LatentWork's settings, with each option as it's labelled in the app, its default, and what it does. ## Open settings - Select your name at the bottom left of the sidebar, then Settings. - On macOS, press `⌘`+`,` or choose LatentWork → Settings.... - Open the command palette (`⌘`/`Ctrl`+`K`) and choose Settings, or one of the settings pages listed there. Settings opens over your task. The list on the left groups the pages; the × at the top right closes it. Pages under Workspace apply to the workspace selected in the sidebar, so select a workspace before changing them. | Group | Pages | | --- | --- | | (top) | Settings | | Workspace | Preferences, Permissions, Extensions | | Global | LatentRouter, Memory, Appearance, Updates, Recovery | | Cloud | Usage | ## Settings The first page is an overview: a card for each page, grouped under Workspace and Global. Under Help, Send feedback opens an email to the LatentWork team. ## Preferences | Option | Default | What it does | | --- | --- | --- | | Show model reasoning | Off | Expands the model's reasoning in the conversation when the model provides it. | | Auto-open generated files | Off | Opens documents and files the agent creates in the side panel as soon as they appear. | | Auto context compaction | On | Summarizes a task's earlier conversation when the context fills up. Set per workspace. Select Reload now on the notice that appears. See Context and cost. | ## Permissions Authorized folders: folders outside the workspace that the agent can read and edit without asking, in this workspace. Add folder adds one; × removes one. The workspace folder is always listed as Workspace root and can't be removed. See Folders outside the workspace. ## Extensions Apps, skills and built-in extensions for this workspace. See Apps, skills and extensions. ## LatentRouter Your connection to your LatentStack gateway. LatentRouter is the app's name for your LatentStack gateway. ### Gateway connection | Field | What to enter | | --- | --- | | Gateway URL | Your LatentStack server's address, for example `https://latentstack.dev`. | | LatentStack API Key | Your key, starting with `ls-`, from your Account page. | Test connection checks that the server can be reached. Save doesn't test the connection first, so test before saving if you changed the URL. Warning Saving reconnects Save stores both fields and reconnects. Any running tasks stop, so wait for them to finish first. ### Organization Which organization's models, limits and budgets apply, and which one your usage is billed to. Default follows your default organization. Each other entry shows the organization's name and your role. Switching organization clears the selected team. Before a key is set, the page shows Set an API key to load organizations. ### Document handling Cite pages from attached PDFs: when the agent answers from a PDF you attached, it adds a reference to the page it used, and clicking it opens that page in the side panel. It can only be turned on if your organization allows it; otherwise the switch is off and the page says an administrator enables it in the LatentStack admin settings. ## Memory Standing instructions, the switch Let the agent remember new things, and what the agent remembers. See Memory. This page appears only while memory is enabled. ## Appearance | Option | Choices | | --- | --- | | Theme | System (follows your operating system), Light or Dark. | | Language | English, 日本語, 简体中文, Tiếng Việt, Português (BR), ไทย, Français, Català, Español, Русский. | Text size isn't here: use `⌘`/`Ctrl`+`+` and `-`. See Keyboard shortcuts. ## Updates The page shows your Current version and the update status: You're up to date (with when it last checked), Checking for updates…, Update available: v… (with its release date and notes), Downloading update… with a progress bar, Ready to install: v…, or Couldn't check for updates with the reason. | Control | Default | What it does | | --- | --- | --- | | Check now | | Checks for a new version. | | Download | | Downloads the available update. | | Install & restart | | Installs the downloaded update and restarts LatentWork. | | Check automatically | On | Looks for new versions in the background. | | Download automatically | Off | Downloads new versions as soon as they're found. You still choose when to restart. | A downloaded update is also installed when you quit LatentWork. Updates come from LatentStack's release server; see Data and privacy. ## Recovery | Item | What it offers | | --- | --- | | Workspace config | The path of the selected workspace's settings file, and Reveal in Finder (Reveal in Explorer on Windows, Show in Files on Linux) to open its folder. | To start over, see Reset LatentWork. ## Usage Your cost, calls and tokens through the gateway for the last 7 days, 30 days, or all time, with a breakdown by model. See Usage over time. Source: https://latentstack.dev/docs/latentwork/settings --- # Keyboard shortcuts Shortcuts for the LatentWork desktop app. On macOS use ⌘; on Windows and Linux use Ctrl. ## App | Action | macOS | Windows and Linux | | --- | --- | --- | | New task in the selected workspace | `⌘`+`N` | `Ctrl`+`N` | | Open or close the command palette | `⌘`+`K` | `Ctrl`+`K` | | Show or hide the terminal | `⌘`+`J` | `Ctrl`+`J` | | Show or hide the sidebar | `⌘`+`B` | `Ctrl`+`B` | | Open settings | `⌘`+`,` | — | | Make text bigger | `⌘`+`+` | `Ctrl`+`+` | | Make text smaller | `⌘`+`-` | `Ctrl`+`-` | | Reset text size | `⌘`+`0` | `Ctrl`+`0` | The new-task shortcut works when you're not typing in a text field. Text size goes from 80% to 160% in steps of 10%, and LatentWork remembers it. ## Message box | Action | Keys | | --- | --- | | Send the message | `Enter` | | New line | `Shift`+`Enter` | | Stop the agent while it's working | `Esc` twice within 3 seconds | | Open commands and skills (empty message box) | `/` | | Mention a file | `@` | | Move through a list of commands, files or skills | `↑` `↓` | | Choose the highlighted item | `Enter` or `Tab` | | Close the list | `Esc` | While the agent is working, `Enter` doesn't send; choose Steer or Queue. See While the agent is working. ## Command palette | Action | Keys | | --- | --- | | Move through results | `↑` `↓` | | Run the highlighted item | `Enter` | | Close | `Esc` | The palette can start a task, search tasks by title or workspace (Search sessions), reopen servers and files from the current task (Accessible items), show or hide the terminal, and open settings pages. Source: https://latentstack.dev/docs/latentwork/shortcuts --- # Data and privacy What LatentWork runs on your computer, what it stores there, and what it sends over the network. ## How LatentWork runs LatentWork does all its work on your computer. Only the AI model runs elsewhere, reached through your LatentStack gateway. The agent reads and writes the files in your workspaces and runs commands there, asking you first where the approval rules say so. Every workspace is a folder on this computer. ## What's stored on your computer | Data | Where | | --- | --- | | Tasks: conversations, attachments sent, and the file checkpoints Revert uses | In the app data folder. | | Your list of workspaces | In the app data folder. | | Gateway URL, API key, selected organization, team and model | `~/.latentwork/config.json` | | Workspace settings: authorized folders and connected apps | Kept by LatentWork on this computer, not in the workspace folder. | | Memory and your instructions | A local database on this computer. | | Copies of attached documents | `.latent/docs/` in the workspace folder. | | Uploaded folders | `uploads/` in the workspace folder. | | Workspace skills | `.latentcode/skills/` in the workspace folder. | | Display preferences: theme, text size, pinned tasks, groups, each task's model | The app's own storage in the app data folder. | Tasks you run in LatentWork don't appear in LatentCode, and the other way round. Note Where the app data folder is If support asks for it: on macOS `~/Library/Application Support/com.differentai.latentwork`, on Windows `%APPDATA%\com.differentai.latentwork`, on Linux `~/.config/com.differentai.latentwork`. Warning Your API key is stored in plain text `~/.latentwork/config.json` holds your API key unencrypted, readable by anyone who can read your home folder. Don't share or sync this file. If it leaks, select Regenerate on your Account page, then enter the new key in Settings → LatentRouter. ## What's sent over the network | Destination | What | When | | --- | --- | --- | | Your LatentStack gateway (the Gateway URL) | Each model request: your messages, attachments, and the file contents and command output the agent includes. Also requests for your account details (models, teams, usage). | Whenever a task runs, and when LatentWork loads models or usage. | | Apps you connect | Whatever the agent sends to that app's tools, and your sign-in with it. | When the agent uses the app. | | Websites | Normal web requests, including icons for connected apps. | When you or the agent open pages in the built-in browser, the agent fetches a web page, or the app shows app icons. | | latentstack.dev | Update checks and update downloads. | In the background, if Check automatically is on, and when you select Check now. | Your task history stays on your computer. The gateway sees each model request as it passes through, applies your organization's models, limits and policies, and records usage such as tokens and cost for your account. See the Admin Console for what administrators can see and set. Note Updates come from LatentStack, not your own server The app checks for and downloads updates from latentstack.dev even if you installed it from your own LatentStack server. To avoid background checks, turn off Check automatically in Settings → Updates. ## Remove your data - One task: Delete session in the task's menu. See Task menu. - Memories: delete them in Settings → Memory, or Forget all. See Memory. - Attachment copies: hover over an attachment's chip in the conversation and select the bin to delete that copy. See Delete an attached document. To remove them all, delete the `.latent/docs` folder in the workspace. - Uploaded folders and files: delete them from the Files panel. See Browse workspace files. - Your saved key: delete `~/.latentwork/config.json`. LatentWork asks you to connect again at next start. - Everything: run the LatentStack uninstaller and don't choose to keep your data. It removes the app, the app data folder and `~/.latentwork`. See Install. Removing a workspace from the sidebar doesn't delete anything: its tasks and files are kept. Source: https://latentstack.dev/docs/latentwork/data --- # Troubleshooting Find the message or symptom you see, then the cause and the fix. For installer problems, see Install. ## Check the connection first Most problems come from the gateway connection. Select your name at the bottom left of the sidebar: the menu shows the connection status. A red dot on your avatar means something is wrong. - Gateway connected: LatentWork reached your gateway and loaded your models. - Checking gateway…: it's loading. This normally takes a second. - Gateway unreachable: LatentWork couldn't load your model list. See below. - Gateway not configured: no API key is saved. ## Connection and sign-in Server unreachable. Check the URL and try again. Cause: LatentWork got no answer from the URL. Fix: Check the URL is your LatentStack server's address, for example `https://latentstack.dev`, and that this computer can open it in a browser. On a company network, check your VPN. Server returned an error (…) Cause: Something answered at that address, but not successfully. Fix: Check the URL points at your LatentStack server and not at another site on the same host. Invalid API key — the server rejected the credentials. Cause: The server refused the key. Fix: Copy your key again from your Account page and paste it into API Key. The profile menu says Gateway unreachable Cause: The server is reachable but your model list didn't load: usually a wrong or regenerated key, or no models available for your organization and team. Fix: Open Settings → LatentRouter, paste your current key from your Account page, and select Save. If it still fails, try No team in the Teams menu, and ask your administrator which models your tier allows. No AI model connected. Add a provider to run tasks. Cause: No models are available to LatentWork, so tasks can't run. Fix: Select the message to open Settings → LatentRouter and check the URL and key, as for Gateway unreachable. The Connect to LatentRouter dialog appears every time I start LatentWork Cause: No API key is saved. Fix: Enter the URL and key and select Save & Continue. It only closes once the connection works. If it keeps happening, contact your administrator. Couldn't load organizations. / No organizations found for this key. Cause: The organization list couldn't be fetched, or your key isn't a member of any organization. Fix: Check the connection as above. If you should be in an organization, ask its administrator to invite you. ## Tasks The agent seems stuck Cause: It is usually waiting for you: an approval panel above the message box pauses the task until you answer. Fix: Answer the panel with Deny, Allow once or Allow for session. To give up on the task, select Stop, or press `Esc` twice in the message box. Pressing Enter does nothing and the buttons shake Cause: The agent is still working, so a new message must be steered or queued. Fix: Choose Steer to send now or Queue to send when it finishes. Model no longer available Cause: The task's model is no longer on your tier. Fix: Select the model button under the message box and choose another model. Context 80% full (or 90%, 95%) Cause: The task is using most of the model's context window, and Auto context compaction is off. Fix: Send `/compact` to summarize the task, or turn on Auto context compaction in Settings → Preferences. Select a session with messages before running /compact. Cause: /compact only works in a task that has messages. Fix: Open the task you want to compact first. A task I had is missing from the sidebar Cause: Tasks are listed under their workspace, and only workspaces in the sidebar are shown. It may also be archived. Fix: Look in the workspace's collapsed Archived section. If you removed the workspace, add the same folder again with Add workspace; its tasks come back. `⌘`/`Ctrl`+`K` → Search sessions finds tasks by title. Workspace or session not found Cause: The task or workspace you opened no longer exists, for example it was deleted or removed. Fix: Pick another task or workspace in the sidebar. ## Attachments and files Can't attach … (with a reason) Cause: That file type isn't supported, for example an older .ppt or .doc. Fix: Do what the message says, usually saving as PDF, .pptx, .docx or .xlsx. The full list is in Attach files. … exceeds the 8MB limit. / N files exceed the attachment size limit. Cause: The file is over its size limit: 100 MB for PDFs and PowerPoint, 10 MB for CSV and TSV, 5 MB for text and code, and 25 MB for everything else. Fix: Split or shrink the file, or put it in the workspace folder and mention it instead of attaching it. Only 8 attachments per message Cause: A message can carry up to 8 attachments. Fix: Send the rest in a follow-up, or put them in the workspace folder. Messages with attachments cannot be edited Cause: Edit message isn't available for messages with attachments. Fix: Use Revert on the message and send a new one. Can't upload that folder The notice says why. The most common reasons: - `That folder has … files. The limit is 5,000 — try a subfolder.` / `That folder is …. The limit is 200 MB — try a subfolder.` Upload a smaller subfolder instead, or several one at a time. - `"…" is …. Single files are limited to 100 MB.` Move that file out of the folder, or split it, and try again. - `Every file in that folder was skipped (… ignored, such as .git or node_modules).` The folder only held folders and files that are always skipped. Choose a folder with documents in it. … could not be read on your computer Cause: A file in the folder is locked, open in another app, blocked by permissions, or stored in the cloud and not downloaded yet. The message names the files. Fix: Close the file, or download it to your computer first (or move it out of the folder), then upload the folder again. Drop one folder at a time Cause: You dragged more than one folder, or a folder together with loose files, onto the message box. Fix: Drop each folder on its own. Each one is uploaded under its own name. That folder was not uploaded: It is too large to read in full by drag-and-drop. Cause: The folder is too big to read completely when dragged in. Fix: Select Upload a folder next to the paperclip and choose the folder instead. X of N files didn't upload … The folder was not added — try again. Cause: Some files failed partway through the upload. Nothing was saved, so the agent never sees a half-uploaded folder. Fix: Upload the folder again. Preview unavailable. Open externally to view this file. Cause: The side panel can't show this file type. Fix: Select Show in folder and open the file in another app. ## Workspaces and apps LatentWork server is unavailable. Start or reconnect the server before creating a workspace. Cause: LatentWork hadn't finished starting when you added the workspace. Fix: Quit LatentWork completely and open it again, then add the workspace again. An app shows Sign in needed Cause: The app needs your account, or your sign-in expired. Fix: In Settings → Extensions, select the app under Your apps and choose Sign in. A new app or skill doesn’t show up for the agent Cause: New apps and skills are only picked up after a reload. Fix: Select Reload now on the Reload required notice. If you chose Later, finish your task and reload from the next notice. Cause: For a skill: it has no description. Its tile in Extensions shows Agent can't see this, and the agent never uses it. Fix: Add a description to the skill. See Skills. The agent keeps asking to access an external folder Cause: The folder is outside the workspace. Fix: Authorize it in Settings → Permissions. See Folders outside the workspace. ## Starting the app For problems running the install script, see Install. Install the correct LatentWork build Cause: The installed app was built for a different processor than your computer's. Fix: Select Download correct version, install it, quit this copy and open LatentWork again. Your workspaces and settings are kept. macOS: the app is damaged or from an unidentified developer Cause: The app was downloaded with a browser instead of the install script. Fix: Reinstall with the install script. Linux: the app doesn’t open Cause: The downloaded app file can't start on some Linux systems. Fix: Use the install script instead of opening the AppImage directly, then start LatentWork from the app menu. ## Information to include when you ask for help - Your LatentWork version: it's at the bottom of the profile menu (Version …) and in Settings → Updates. - The exact message you saw, and what you were doing. - Your operating system. - On Linux, the end of `~/.local/share/LatentWork/latentwork.log`. Settings → Send feedback opens an email to the LatentWork team. For account, key and model access questions, contact your LatentStack administrator. ## Reset LatentWork To start over, quit LatentWork, then: - 01Reset the connection onlyDelete `~/.latentwork/config.json`. At the next start, LatentWork asks for the gateway URL and API key again. Your tasks and workspaces are kept. - 02Reset everythingDelete LatentWork's app data folder and `~/.latentwork`. See Data and privacy for where the app data folder is.At the next start, you see the welcome screen again. Danger Resetting everything deletes your task history The app data folder holds all your tasks. Deleting it can't be undone. Your workspace folders and the files in them aren't affected. Source: https://latentstack.dev/docs/latentwork/troubleshooting --- # Admin Console overview The web console is where you manage your LatentStack account and API key, and where organization owners and admins control who can use which models, at what limits, and under which policies. ## Who uses the console Everyone with a LatentStack account signs in to the same console. What you see depends on your role in the organization you're working in: - Every signed-in user manages their account and API key, joins organizations, checks their own usage and limits, sets budget alerts, shares sessions, sends feedback, and configures the LStack Cloud Agent. - Organization owners and admins also get the Administration group: users, tiers, teams, guardrails, usage analytics, platform settings, the session registry, credit requests and the feedback inbox. Everything in the Administration group applies only to the active organization, the one shown in the organization switcher at the top left. Switch organizations and the pages show that organization's users, tiers and settings instead. ## Roles Each organization member has one role. The console only shows actions your role allows. | Role | What it can do | | --- | --- | | Member | Use the organization: send requests under its tiers and teams, see their own usage, request credits, send feedback, and share sessions. No access to the Administration group or the Members page. | | Admin | Everything a member can, plus the whole Administration group and the Members page: invite and approve people, change members' roles, assign tiers, set credit limits, and change the organization's guardrails, prompts and settings. An admin can act only on members, not on other admins or the owner. | | Owner | Everything an admin can, plus act on admins and transfer ownership. Each organization has exactly one owner. The person who creates an organization is its owner. | ### Platform admins Platform admin is a separate account-level role, not an organization role. It shows as an Admin badge in your account menu. A platform admin can grant or remove the flag on other accounts and delete accounts from the Users page. Inside an organization, a platform admin has only the access their role in that organization gives them. ## Console map The sidebar has three groups. The top bar holds the organization switcher, the notifications bell, the theme toggle and your account menu (Account settings, Budget alerts, Log out). | Sidebar entry | Group | Who sees it | Docs | | --- | --- | --- | --- | | Overview | Administration | Owner, Admin | Usage analytics | | Users | Administration | Owner, Admin | Users | | Tiers | Administration | Owner, Admin | Tiers and limits | | Teams | Administration | Owner, Admin | Teams | | Guardrails | Administration | Owner, Admin | Guardrails | | Usage Analytics | Administration | Owner, Admin | Usage analytics | | Settings | Administration | Owner, Admin | Platform settings, Prompt management | | Session Registry | Administration | Owner, Admin | Shared sessions | | Credit Requests | Administration | Owner, Admin | Credits | | Feedback | Administration | Owner, Admin | Feedback and notifications | | Organizations | Organization | Everyone | Organizations and members | | Members | Organization | Owner, Admin | Organizations and members | | My Teams | My account | Everyone | Teams | | My Usage | My account | Everyone | My usage and budget alerts | | LStack Cloud Agent | My account | Everyone | LStack Cloud Agent | | Shared Sessions | My account | Everyone | Shared sessions | | Budget Alerts | My account | Everyone | My usage and budget alerts | | Send Feedback | My account | Everyone | Feedback and notifications | Your account page is in the account menu rather than the sidebar; see Sign in and your account. Tip Missing the Administration group? It shows only when your role in the active organization is Owner or Admin. Check the role next to each organization in the switcher, and switch to the one you administer. ## Where to start ### Sign in and your account Create an account, sign in, reset your password, and find or rotate your API key. ### Organizations and members Create or join an organization, invite people and manage roles. ### Users Add people one at a time or in bulk, assign tiers and manage access. ### Tiers and limits Control which models people can use, and their rate and spend limits. ### Guardrails Screen every request with an AI judge and a PII detector. ### Usage analytics Spend, requests, tokens and latency across your organization. ### Platform settings The model registry, providers, pricing and gateway behaviour. ### LStack Cloud Agent Connect GitHub for hosted agents and run agent jobs from the browser. Source: https://latentstack.dev/docs/console --- # Sign in and your account Create an account, sign in, reset a forgotten password, and manage your profile, password and API key. ## Create an account Anyone can create an account from the sign-up page. You don't need an organization first: you create or join one after signing in. If an administrator added you, you already have an account; see Accounts created by an administrator. - 01Open the sign-up pageGo to /signup, or select Sign up on the sign-in page. - 02Fill in the formEnter your Name, Email and a Password of at least 8 characters. - 03Select Create accountYou're signed in and taken to Organizations, where you can create an organization or join one. Your account gets an API key straight away. Your administrator may have set things up so you join an organization automatically. In that case you land in that organization as soon as you sign up. ### Signing up from an invite If you open an organization invite link without an account, select Create an account to join. After you create the account with the invited email address, you join the organization automatically. See Accept an invite. ## Sign in - 01Open the sign-in pageGo to /login. - 02Enter your email and passwordThen select Sign in. Platform admins land on the Overview dashboard. Everyone else lands on Organizations. A sign-in lasts 8 hours; after that, or if your session ends early, you're returned to the sign-in page. To sign out, open the account menu at the top right and select Log out, then confirm. Logging out doesn't affect your API key: LatentCode, LatentWork and your scripts keep working. ## Reset a forgotten password - 01Request a codeOn the sign-in page select Forgot password?, enter your Email and select Send reset code. - 02Enter the codeType the 6-digit Verification code from the email. The code is valid for 10 minutes. If it doesn't arrive, select Resend code (available after 30 seconds). - 03Choose a new passwordEnter a New password of at least 8 characters, repeat it in Confirm password, and select Update password. You're returned to the sign-in page. For privacy, the page shows the same message whether or not an account exists for the address. After 5 incorrect codes the code is cancelled and you need to request a new one. ## Your account page Open the account menu at the top right and select Account settings, or go to /account. The page has these cards: | Card | What it does | | --- | --- | | Profile | Shows your Email, Name, Role (Admin for platform admins, otherwise User) and your Tier in the active organization. Select Edit profile to change your name or email. | | API Key | Shows your key masked, with show, copy and Regenerate controls. | | One-paste setup | Select Copy setup prompt to copy instructions that install and configure LatentCode and LatentWork with your key. Paste them into a terminal AI agent such as Claude Code. Preview prompt shows the text first. | | Change password | Change your password. | | Product Tour | Select Start tour or Replay tour for a guided walkthrough of the console. | ### Edit your profile - 01Select Edit profileOn the Profile card. - 02Change Name or EmailThe email is also your sign-in email. It must be a valid address that no other account uses. - 03Select SaveUse your new email the next time you sign in. ### Change your password - 01Open Change passwordSelect the Change password card to expand it. - 02Fill in the formEnter your Current password, a New password of at least 8 characters, and repeat it in Confirm new password. - 03Select Update passwordYour current sign-in stays active. ## Your API key Your API key starts with `ls-`. It identifies you to the LatentStack gateway from LatentCode, LatentWork and the Agents API, sent as `Authorization: Bearer `. ### View and copy On the API Key card, select the eye icon to show the full key and Copy to copy it. Your key is always available here; you don't need to save it anywhere else. ### Rotate (regenerate) your key - 01Select RegenerateOn the API Key card. If you don't have a key yet, the button is Generate API key. - 02ConfirmThe old key stops working immediately and the new one is shown. - 03Update your clientsPaste the new key into LatentCode, LatentWork and any scripts that used the old one. Warning Regenerating breaks existing clients Every client using the old key gets `401 Invalid API key` until you give it the new key. Regenerate only when the key may have leaked, or when you're ready to update every client. ### Your key and organizations You have one key, whatever organizations you belong to. Select the organization in LatentCode or LatentWork; its tier, limits and credits apply. ## Accounts created by an administrator An organization admin can create your account for you. You're then a member of their organization, with a random password and an API key. Depending on how they created it: - You receive a welcome email with a temporary password, your API key and the gateway base URL. Sign in with the temporary password, then change it on your account page. - If you didn't get an email, ask the admin for your credentials, or set your own password with Forgot password? on the sign-in page. ## Troubleshooting I was sent back to the sign-in page Sign-ins last 8 hours. Sign in again. Your API key isn't affected. "An account with this email already exists" Sign in instead, or reset your password with Forgot password?. "Too many sign-up attempts from this network" Sign-ups are rate limited per network. Wait a few minutes and try again. "Code expired or invalid" or "Too many incorrect attempts" Request a new code from Forgot password?. Only the most recent code works, for 10 minutes. My clients stopped working with 401 Invalid API key The key was regenerated, from your account page or by you in another browser. Copy the current key from the API Key card into each client. Source: https://latentstack.dev/docs/console/account --- # Organizations and members Create, join and switch organizations, invite people, approve join requests, and manage roles and ownership. ## How organizations work An organization is a separate workspace with its own members, tiers, teams, guardrails, prompts, settings, credits and usage. You can belong to several. The one selected in the organization switcher (top left of the console) is the active organization: console pages show its data, and changes apply to it. - Private organizations are invite-only. - Public organizations appear in Discover public organizations. Their join policy is either Admin approves (people request to join) or Auto-approve (join instantly). A new organization starts with one default tier, so its members can make requests straight away. Edit it on the Tiers page. ## Switch organization - 01Open the organization switcherSelect the organization name at the top left. Each organization is listed with your role in it. - 02Pick an organizationThe console reloads the current page for that organization. You can also select an organization card on the Organizations page. To find or create another organization, select Find or create an org at the bottom of the switcher. ## Create an organization Note Required role Any signed-in user, unless your deployment has turned organization creation off. In that case the New organization button is hidden and you'll see "Organization creation is disabled by your administrator". - 01Open OrganizationsGo to Organizations and select New organization. - 02Name itEnter the Organization name. - 03Choose visibilitySelect Private — invite only or Public — discoverable. For a public organization, choose what happens When someone requests to join: Admin approves or Auto-approve (join instantly). - 04Select CreateYou become the organization's owner and it becomes your active organization. ## Join an organization ### Join a public organization - 01SearchOn Organizations, type in Search public organizations…. Each result shows its member count and join policy. - 02Join or requestSelect Join to join an auto-approve organization immediately, or Request to join for one that needs approval. The result then shows Requested until an admin decides; you get a notification when they approve or decline. You always join as a member. ### Accept an invite Invites arrive by email, and, if you already have an account, in the notifications bell. An invite is valid for 14 days and can be accepted only by the email address it was sent to. - From the bell, select Accept or Decline on the invite. - From the email link, when you're signed in: select Join followed by the organization name. - From the email link, without an account: select Create an account to join and sign up with the invited address. If you already have an account, sign in first, then reopen the link. ## Leave an organization On Organizations, select the leave icon on the organization's card and confirm. You lose access until you're invited back. The owner can't leave; transfer ownership first. ## Invite people Note Required role Owner or Admin of the organization. You can invite from Members (Invite by email) or from Users (Invite to your organization). Both work the same way. - 01Enter an email addressAs you type, matching accounts are suggested, marked has an account or already a member. You can't invite an existing member. - 02Choose a roleSelect member or admin. Ownership can't be given by invite. - 03Select InviteThe invite is emailed, and its link is copied to your clipboard so you can also share it yourself. People who already have an account also get it in their notifications bell. Pending invites are listed under the invite box with their role. Select link to copy an invite link again, or revoke to cancel it. Inviting the same address again replaces the earlier invite, whose link stops working, and restarts the 14-day expiry. Tip Adding people without an invite Admins can also create accounts directly, or add an existing account to the organization, from the Users page. Those people join at once, without accepting anything. ## Approve join requests Note Required role Owner or Admin of the organization. Requests to join a public organization appear under Join requests on both the Members and Users pages, and you get a notification for each. Select Approve to add the person as a member, or Decline. They're notified either way. ## Change visibility and join policy Note Required role Owner or Admin of the organization. On Members, the Access card switches the organization between Private and Public. For a public organization, choose Admin approves requests or Auto-approve (join instantly). Changes save immediately. ## Manage members and roles Note Required role Owner or Admin of the organization. The Members page lists everyone in the organization, 50 per page, with a search box for name or email. The same controls are on the Users page. | Task | How | Who can do it | | --- | --- | --- | | Change a role | Pick member or admin in the member's role menu. | Owner: on admins and members. Admin: on members. | | Remove a member | Select the trash icon and confirm. Their account isn't deleted. | Owner: admins and members. Admin: members. | | Transfer ownership | Select Make owner and confirm. You become an admin. | Owner only. | Nobody can change the owner's role or remove the owner, and you can't change your own role or remove yourself (use Leave on the Organizations page). When an action isn't allowed, the console doesn't offer it. Warning Transferring ownership is immediate The new owner gets a notification and an email, and you drop to admin. Only the new owner can transfer it back. ## Troubleshooting "This invite has expired" Invites last 14 days. Ask an admin to invite you again. "Invite not found or already used" The invite was accepted, declined or revoked, or a newer invite replaced it. Use the most recent invite email, or ask for a new one. "This invite was sent to … Sign in as that user to accept it." You're signed in with a different email. Log out and sign in as the invited address, or ask the admin to invite the address you use. "This organization is invite-only" The organization is private. Ask one of its admins for an invite. "Transfer ownership before leaving" An organization must always have an owner. Make another member the owner from Members, then leave. I can't see Members or the Administration group Both need the Owner or Admin role in the active organization. Check your role in the organization switcher. Source: https://latentstack.dev/docs/console/organizations --- # Users Add people to your organization one at a time or from a spreadsheet, assign their tiers, and manage their roles, limits and access. Note Required role Owner or Admin of the active organization. A few account-level actions (making someone a platform admin, deleting an account) also need you to be a platform admin. ## The Users page Open Users from the Administration group. It lists the members of the active organization, 50 per page, with the total at the top. Besides the table, the page has the organization's Join requests, the Invite to box and the organization's Credits card. Invites and join requests are covered in Organizations and members, credits in Credits. | Column | What it shows | | --- | --- | | User | Email and name. | | Role | The person's role in this organization. It's a menu when you're allowed to change it. A shield icon marks platform admins (visible to platform admins only). | | Tier | The tier the person uses in this organization; pick another to reassign it. (inherited) means no tier is set in this organization yet; pick one. Unknown tier (deleted) — reassign means the tier no longer exists; pick a new one. | | Registered | When the account was created. | Use the search box (Search by email, name, or ID…) and the filters: All tiers narrows to one tier, and All roles narrows to Platform admin or User (the platform-wide flag, not the organization role). Clear filters resets both. ## Add a user - 01Select Add userAt the top right of the Users page. - 02Enter the EmailPlatform admins also see Make this user a platform admin. - 03Choose whether to email themLeave Email the user their API key ticked to send a welcome email with a temporary password, their API key and the gateway base URL. - 04Select Create userThe account is created as a member of the active organization, on the organization's default tier. - 05Copy the credentialsA panel shows the new account's API key. Copy it now: it isn't shown again here (the user can always see it on their own account page). If no email is sent, the panel also shows the Email and Web UI password for you to pass on. If the email was supposed to go out but failed, the page says so. Note Adding someone who already has an account If the email belongs to an existing account that isn't in your organization, Create user adds that account as a member. No new password or key is created. If they're already a member, you'll see "This user is already a member of this organization". ## Add users in bulk Create many accounts at once from a CSV or Excel file. - 01Prepare the fileUse `.csv`, `.xlsx` or `.xls`. Only the first sheet is read. The first row must be a header with a column named `email`, `emails`, `mail` or `mails` (any case). Other columns are ignored, duplicates are removed, and anything without an `@` and a dot is skipped.users.csv`email,department ana@example.com,Risk raj@example.com,Trading lee@example.com,Ops` - 02Select Bulk uploadThen Click to choose a file. The preview shows how many unique emails were found and lists the first 20. - 03Choose whether to email themLeave Email each user their temporary password and API key ticked to send welcome emails. - 04Select Create N accountsThe upload runs in the background. A progress panel at the bottom right shows the Created, Skipped and Failed counts; you can minimise it and keep working. When it's done it lists every skipped or failed address with the reason. New accounts join the active organization as members on its default tier. An address that already has an account is skipped (reason "already exists"); to add those people, use Add user or send an invite. Warning Bulk credentials are only sent by email Unlike Add user, bulk upload never shows passwords or keys on screen. If you don't send the emails, people set a password with Forgot password? on the sign-in page and then find their key on their account page. ## Assign a tier Pick a tier in the person's Tier menu. The change applies to their requests in this organization only; the same person can be on different tiers in different organizations. Only this organization's tiers are offered. See Tiers and limits for what a tier controls and how a team's tier takes precedence. You can change your own tier. For anyone else, the same rule as roles applies: an admin can reassign members, and the owner can reassign admins and members. ## Row actions Select the ⋮ menu at the end of a row. You only see the actions you're allowed to take on that person. | Action | What it does | Who can do it | | --- | --- | --- | | View usage | Opens the person's usage in this organization: spend, requests, models, their tier's limits and how much of each they've used. | Owner, Admin | | Set credit limit | Sets or clears the person's personal credit limit in this organization. See Credits. | Owner, Admin (on members and themselves) | | Reset rate limits | Clears the requests and spend counted against the person's rate-limit and budget windows, in this organization and in its teams. Their limits don't change, and credit balances aren't touched. Use it to unblock someone now. | Owner (on admins and members), Admin (on members) | | Make organization owner | Transfers ownership to this person. You become an admin. | Owner | | Remove from organization | Removes their membership. Their account and API key remain, and they keep access to any other organizations. | Owner (on admins and members), Admin (on members) | | Make platform admin / Remove platform admin | Grants or removes the install-wide platform admin flag. It doesn't change anyone's organization role. | Platform admins | | Delete user | Deletes the account everywhere: credentials, API key and memberships in every organization. It can't be undone. | Platform admins | For the owner, or someone at or above your own role, the menu explains why there's nothing to change. You can't delete your own account or remove your own platform admin flag, and an account that owns an organization can't be deleted until ownership is transferred. ## Set credit limits for many people Tick the checkbox at the left of each row, or tick the header checkbox to select everyone matching the current search and filters (across all pages). A bar titled Set limits for individual users appears. Enter a Limit in dollars and select Apply, or select Clear to remove the personal limit from everyone selected. People whose role you can't act on are skipped, and the result says how many. ## Troubleshooting "Only a platform administrator can create admin accounts" Untick Make this user a platform admin. Organization roles are given with the role menu instead. "You can't modify members at or above your own role" Admins can act only on members. Ask the owner. "This account owns … organization(s)" The account can't be deleted while it owns an organization. Transfer ownership of each one first. The welcome email didn't arrive Check the message shown after creating the user. If sending failed, pass the credentials on yourself, or ask the person to use Forgot password?. A tier shows in red as Unknown tier (deleted) The tier was removed. Pick a current tier from the menu. Source: https://latentstack.dev/docs/console/users --- # Tiers and limits A tier decides which models someone can use, which models run LatentCode's background work, and how many requests and dollars they can spend per window. Note Required role Owner or Admin of the active organization. ## How tiers work Each organization has its own tiers; one of them is the default. Every member uses exactly one tier in each organization. The gateway picks the tier for each request in this order and uses the first one it finds: - For a request made from a team: the member's tier override in that team, then the team's tier. - The tier assigned to the person in this organization, on the Users page. - The organization's default tier. New members start on the organization's default tier. A request is refused if no tier applies, if its model isn't on the tier, or if it would go over a limit. The errors are listed below. ## The Tiers page Open Tiers from the Administration group. Each tier card shows a Default badge on the default tier, an Incomplete badge when a required model is missing, the number of Allowed models and Rate policies, the Default model, and how many of the four required Background models are set. Select a card to expand the full list of models, per-model rate limits, background models and the Ultra-Plan setting. The icons on each card Set default (star), Edit (pencil) and Delete (trash). The default tier can't be deleted; make another tier the default first. ## Create or edit a tier - 01Select New tierOr the pencil icon on an existing tier. - 02Name itEnter a Name (unique within the organization) and, optionally, a Description. - 03Choose the allowed modelsTick models under Allowed models, or use Select all. The search box filters by model or provider. Only models with a provider configured in Settings are listed. - 04Set the background and default modelsEvery required model must be one of the tier's allowed models (see the field reference below). - 05Set limitsFill in the rate-limit and budget tables. `0` means unlimited. - 06SaveSelect Create tier or Save changes. The button stays disabled until every required model is set. The first tier you create in an organization becomes its default automatically. ## Field reference ### Models | Field | Required | Meaning | | --- | --- | --- | | Name | Yes | Shown on the Users, Teams and My Usage pages. | | Description | No | Free text. | | Allowed models | Yes, at least one | The models members on this tier can call. Requests for any other model are refused. | | Subagent model | Yes | Runs helper agents. | | Goal / Loop model | Yes | Runs goals and /loop. | | Title model | Yes | Writes short session titles. | | Fusion advisor model | Yes | Plans how work is shared between models. | | Review model — high, medium, low | No | Models for the /review reviewers, by difficulty. Unset ones use the subagent model. | | Default main-agent model | Yes | Pre-selected the first time someone opens LatentCode or LatentWork, and the model a session falls back to if its current model errors. People can still pick any allowed model for their sessions. | | Enable Ultra-Plan mode | No | Adds a planning mode in which a second model checks the finished plan against the codebase before the user approves it. Costs one extra model pass per plan. When off, the mode doesn't appear in the client. | | Plan revisor model | When Ultra-Plan is on | The model that checks plans. Pick a capable model, ideally from a different vendor than the default main-agent model. | | Default tier (new users get this) | No | Makes this the organization's default tier. | People can't change the background models in their client. If a model the tier allows no longer has a provider, the editor leaves it out of the selection and asks you to Acknowledge that before you save. ### Limits | Table | Unit | Windows | Meaning | | --- | --- | --- | --- | | Rate limits per model | Requests | min, hour, 6h, day | Requests each member may make in each window. A model with its own row uses that row; every other allowed model uses the default (any other model) row. | | Budget limits | USD | min, hour, 6h, day | Total spend per member across all models in each window. | | Budget limits per model | USD | day | Daily spend per member on one model, with the same default row. Enforced in addition to the tier-wide budget: whichever cap is reached first blocks the request. | Limits count each person separately, per organization. Usage through a team is counted separately from the same person's own usage, against the team's tier. To see how close someone is, use View usage on the Users page; people see their own on My Usage. To clear someone's current windows, use Reset rate limits on the Users or Teams page. ## Change the default tier Select the star icon on a tier, or tick Default tier (new users get this) in its editor. Exactly one tier is the default. The default applies to new members, and to existing members who have no tier assigned in this organization. ## Delete a tier Select the trash icon and confirm. Anyone assigned to the deleted tier, including team and team-member tier assignments, is moved to the organization's default tier. ## What users see when a limit is hit | HTTP status and type | Cause | | --- | --- | | 403 `no_tier_assigned` | No tier applies to this person in the selected organization. | | 403 `model_not_allowed` | The requested model isn't on the tier. The message names the tier. | | 429 `rate_limit_exceeded` | A request window is full. The request waits briefly, then fails if the limit hasn't cleared (Settings → Rate Limits). | | 402 `budget_exceeded` | A spend cap for the window has been reached. Requests fail until the window resets. The error names the window and, for a per-model cap, the model. | | 402 `credit_limit_exceeded` | An organization or personal credit balance has run out. See Credits. | Tip Warn people before they hit a budget People can set budget alerts to get an email when their daily spend passes a percentage of their tier's daily budget. ## Troubleshooting A tier shows Incomplete One of the four required background models, the default main-agent model, or (with Ultra-Plan on) the plan revisor model isn't set. Edit the tier and set them. "… must be one of this tier's allowed models" A background or default model isn't ticked under Allowed models. Tick it, or pick a different model. "These are not registered models, so nothing can serve them" The tier lists a model that was removed from Settings → Model Settings. Untick it, or add the model back. "A tier with this name already exists" Tier names must be unique within an organization. The model list is empty No models have a provider yet. Configure providers and models in Settings. Source: https://latentstack.dev/docs/console/tiers --- # Teams A team gives a group of members its own tier and system instruction. Members pick the team in their client, and requests made from it use the team's models and limits. ## How teams work Teams live inside an organization. A member can belong to several teams and still make requests without one. When a client sends a request for a team, the gateway checks the person belongs to the team in the selected organization, then applies: | Setting | Effect on requests made from the team | | --- | --- | | Tier | The member's own override in the team if set, otherwise the team's tier, otherwise the person's usual tier in the organization. See Tiers and limits. | | Team instruction | Text added to the start of the system prompt of every request made from the team. | | Per-model RL overrides | Request limits for one member that replace the tier's limits for that member in this team. | Usage from a team is counted separately from the person's own usage, so a team has its own rate-limit and budget windows. ## Use a team (members) Open My Teams from My account to see the teams you belong to, each with its tier, rate limits and models. Select the ID under a team name to copy it. Then choose the team in LatentCode or LatentWork; see LatentCode and LatentWork. Your admin adds you to teams; you get an email when they do. ## Manage teams Note Required role Owner or Admin of the active organization. Open Teams from the Administration group. Each card shows the team's tier and member count, a Manage members button, and a ⋮ menu with Limits & usage, Manage members, Edit, Reset rate limits and Delete team. ### Create a team - 01Select New teamAt the top right of the Teams page. - 02Fill in the formSee the field reference below. Only Name is required. - 03Select Create teamThen add members. | Field | Meaning | | --- | --- | | Name | Required and unique within the organization. | | Description | Optional. | | Tier (allowed models + rate limits) | A tier from this organization. Default tier means no team tier: each member uses their own tier. | | Team instruction (system prompt) | Optional. Added to the start of the system prompt of every request made from this team, for example rules or context specific to the team's work. | ### Add and manage members - 01Open Manage membersOn the team's card. - 02Find the personType in Search users to add…. Only members of the organization can be added; current team members are marked Member. - 03Choose a tierLeave Team tier to use the team's tier, or pick a tier override for this person. - 04Select AddThe person is emailed that they were added. Each row in the member list has: | Control | What it does | | --- | --- | | Tier menu | Change the member's tier override, or set it back to Team tier. | | Sliders icon | Opens RL overrides: per-model request limits for this member only, per minute, hour, 6 hours and day. `0` keeps the tier's limit. Select Save overrides. | | Gauge icon | Resets this member's current request and budget windows in this team. | | Trash icon | Removes the member from the team (not from the organization). | Reset team RLs at the top of the dialog resets every member's windows in the team at once. Limits themselves don't change. ### Check a team's limits and usage Select Limits & usage in the card menu to see the team's Budget (USD) spend against its tier's budgets, Requests (per model, whole team), and the per-member rate limits. Reset team limits clears the whole team's request and budget windows. ### Delete a team Select Delete team in the card menu and confirm. All its memberships are removed. The people stay in the organization. Note Teams and budget alerts Members see a separate bar for each team with a daily budget on their Budget Alerts page. ## Troubleshooting 403 "You are not a member of this project" The client selected a team the person doesn't belong to. Add them on the Teams page, or pick another team in the client. 403 "This team is not available in the selected organization" The team belongs to a different organization from the one the client selected. Switch the client's organization. "A team with this name already exists" Team names must be unique within an organization. A person doesn't appear when adding members Only members of the active organization can join its teams. Add or invite them to the organization first. Source: https://latentstack.dev/docs/console/teams --- # Credits Credits are a prepaid dollar balance that spending draws down. Set one for the whole organization, give individual members their own allowance, and handle members' requests for more. ## Credits compared with tier budgets | | Credits | Tier budgets | | --- | --- | --- | | Set on | Users page and Credit Requests | Tiers | | Shape | A balance that goes down as requests are billed | A cap per time window (minute, hour, 6 hours, day) | | Refills | Only when an admin tops up, resets or sets a new limit | Automatically when the window resets | | Error when used up | 402 `credit_limit_exceeded` | 402 `budget_exceeded` | Both apply at the same time: a request is refused as soon as any one of them runs out. Credits are optional; with no credit limit set, spending is limited only by tiers. ## The two credit levels - Organization pool: one balance that every member's spending in the organization draws from. - Personal credit limit: one member's own allowance inside the organization. It's checked in addition to the pool, so the member stops when either runs out. Both belong to one organization. A person's limit in one organization has no effect on their use of another. The last request before the balance runs out may go slightly over. ## Set the organization's credit pool Note Required role Owner or Admin of the organization. The Credits card on the Users page shows the pool: how much is remaining of the limit and the percentage used. It reads No credit limit configured — usage is unlimited. until you set one. The balance is live since the limit was last set or reset, so it differs from the date-range totals in usage analytics. - 01Select EditOn the Credits card. - 02Fill in one or both fieldsFieldEffectSet limitThe pool's ceiling in dollars. Setting it for the first time fills the balance to the limit. Changing it later never raises the current balance; it only lowers the balance if it's above the new limit.Top upAdds this amount to both the balance and the limit. A negative amount corrects a mistake; nothing goes below zero. - 03Select SaveBoth fields are applied together. Reset to limit refills the balance to the current limit, for example at the start of a new billing period. ## Set a member's personal limit Note Required role Owner, or Admin acting on members and on themselves. - 01Open the member's menuOn the Users page, select ⋮ on their row, then Set credit limit. - 02Enter the limitIn Set limit ($) — blank clears it. The dialog shows how much they've used of their current limit. - 03Select SaveThe member's balance is set to the full new limit. Leaving the field blank removes the personal limit, so only the pool applies. Reset to limit refills the member's balance without changing the limit. To set or clear the same limit for many people, see Set credit limits for many people. Note A new personal limit replaces the balance Unlike the organization pool, there's no top-up for a member. Saving a limit always resets their balance to that amount. ## Credit requests ### Ask for more credits (members) - 01Open My UsageGo to My Usage with the organization selected. - 02Select Request CreditsOptionally add a Note (up to 500 characters) explaining why. - 03Select Send requestThe organization's owner and admins are notified. The button changes to Request pending until they decide. You can have one open request per organization. You get a notification and an email with the outcome; an approval tells you your new limit. ### Review requests (admins) Note Required role Owner or Admin of the organization. Open Credit Requests from the Administration group. Pending requests are grouped by day, newest first. Each shows the requester, what they've used of their current personal limit (or No personal limit yet), and their note. - Select Add credits, enter the New limit (pre-filled with their current limit) and select Grant. This sets their personal limit to that amount and refills their balance to it. - Select Decline to close the request without changing anything. The organization pool isn't changed by either action. ## Troubleshooting Requests fail with 402 credit_limit_exceeded The error's `scope` is `org` when the pool is empty and `member` when the person's own limit is. Top up or reset the pool, or raise or reset the member's limit. "No credit limit is configured for this organization" Reset to limit needs a limit. Set one with Edit first. "That member is no longer in this organization" The requester left the organization while their request was pending. The request can't be granted. Source: https://latentstack.dev/docs/console/credits --- # Guardrails Screen every request your organization sends through the gateway: an AI judge that enforces your written policies, and a PII detector that blocks or redacts sensitive data before it reaches a model provider. Note Required role Owner or Admin of the active organization. ## How guardrails work Open Guardrails from the Administration group. The page has two tabs, each with an ON/OFF badge. Both are off until you turn them on, and each organization has its own configuration. | Tab | What it does | Cost | | --- | --- | --- | | Layer 1 | A model you choose (the judge) reads the request and blocks it if it breaks one of your policies. | One extra model call per request. It isn't counted against the person's tier budgets or credits. | | Layer 2 | Detects sensitive data such as card numbers, national IDs and email addresses by pattern and checksum, then blocks the request or rewrites it. | No model call (unless you turn on the optional name and place detection). | Every chat request made through the gateway in the organization, from LatentCode, LatentWork or any API client, goes through Layer 1 and then Layer 2 before it's sent to the provider. A request blocked by either layer never reaches the model and returns HTTP 400: Blocked by Layer 1 ``` { "error": { "message": "The message contains a US Social Security number.", "type": "guardrail_blocked_llm", "policy": "Block PII" } } ``` Layer 2 blocks use the type `guardrail_blocked_pii` and list the `entities` found. Only the content your users send is screened. ## Layer 1: AI judge ### Set it up - 01Pick a Judge modelAny model the organization has configured. The judge runs on every request, so choose a fast, inexpensive one. - 02Add policiesSelect Add policy. Give it a short Label (for example "Block PII") and write the Instruction to the judge model, in plain language: what to block. Select Add policy to save it. Add as many as you need. - 03Test itUnder Test the judge, paste a sample message and select Run test. You see BLOCKED or ALLOWED, how long the judge took, and for a block, the policy and the reason. Tests use the current settings; nothing needs saving first. - 04Turn it onSwitch the toggle on. It needs a judge model and at least one policy. The card then reads AI enforcement active. ### Settings | Field | Default | Meaning | | --- | --- | --- | | Judge model | None | The model that evaluates requests. | | On judge error / timeout | Allow the request (fail-open) | What happens when the judge fails, times out, or gives an answer that can't be read. Block the request (fail-closed) is stricter but blocks everything while the judge is unavailable. | | Timeout (seconds) | 8 | How long to wait for the judge, from 1 to 60. | | Block message (shown to caller) | "Your request was blocked by an AI safety policy." | Returned when a request is blocked and the judge gave no reason, or when a fail-closed error blocks it. Normally the judge's own reason is returned. | The judge reviews the conversation and blocks only clear policy violations. To remove a policy, select its trash icon. Tip Writing policies Write each policy as a clear instruction about what to block, one topic per policy. The judge reports which policy it applied, so specific labels make blocks easier to understand. Test borderline examples before turning enforcement on. ## Layer 2: PII detection If the layer shows "Presidio isn't installed on this deployment", PII detection isn't available on this installation; contact your LatentStack administrator. ### Choose a mode | Mode | Effect when something is detected | | --- | --- | | Block | Rejects the request with the Block message. This is the default mode. | | Sanitize | Rewrites each detected item according to its action and forwards the cleaned request. If something is found in tool-call arguments, which can't be rewritten, the request is blocked instead. | | Off | Nothing is scanned. | The toggle turns the layer on or off; the mode decides what it does. ### Choose what to detect Under Entities & actions, tick the entities to watch and pick an action for each. Out of the box, `CREDIT_CARD` and `EMAIL_ADDRESS` are masked and `US_SSN`, `IN_PAN` and `IN_AADHAAR` are redacted. | Group | Entities | | --- | --- | | Global | CREDIT_CARD, EMAIL_ADDRESS, PHONE_NUMBER, IBAN_CODE, IP_ADDRESS, CRYPTO, MEDICAL_LICENSE | | India | IN_PAN, IN_AADHAAR, IN_VEHICLE_REGISTRATION | | US | US_SSN, US_BANK_NUMBER, US_ITIN, US_PASSPORT | | Names & places (needs NER model) | PERSON, LOCATION, NRP, DATE_TIME | | Action | In Sanitize mode, the detected text is… | | --- | --- | | redact | Removed. | | mask | Overwritten with `*` (up to 12 characters). | | replace | Replaced with the entity name, such as ``. | | hash | Replaced with its SHA-256 hash. | | keep | Left as is (still counts as a detection in Block mode). | ### Add your own patterns - Browse library opens a catalogue of ready-made patterns grouped by category, each marked with its compliance area and false-positive risk. Tick cards and add them, or select Add on the Recommended starter pack for the low-false-positive set. Added patterns are redacted by default. - Custom rule adds your own regular expression: an Entity name (for example `EMP_ID`), an Action, the Regex, and a Confidence score (default 0.7). Invalid regular expressions are rejected. Custom and library rules appear under Custom rules, where you can change their action or delete them. ### Other settings | Field | Default | Meaning | | --- | --- | --- | | Detection engine | Regex + checksum only | Local NER model also detects names and places, if available (the page shows whether it is). | | Min confidence | 0.35 | Detections scoring below this are ignored. Raise it to reduce false positives. | | Scan roles | user | Which messages to scan: user, assistant and/or system. | | Block message | "Your request was blocked because it contained sensitive data." | Returned in Block mode. | | Deny-list | Empty | Comma-separated words that are always flagged, such as internal project code names. | | Allow-list | Empty | Comma-separated words that are never flagged. | Changes on this tab save as you make them. ### Test detection Paste text under Test detection and select Run test. The result lists each entity found with its score, and shows the text as it would look after sanitizing. ## Troubleshooting "Pick a judge model and add at least one policy first" Layer 1 can't be turned on until both are set. Legitimate requests are being blocked Run them through the test box to see which policy or entity triggers. For Layer 1, make the policy wording more specific. For Layer 2, raise Min confidence, add the term to the Allow-list, or change the entity's action and use Sanitize instead of Block. Requests got slower Layer 1 adds a judge call to every request. Use a faster judge model or lower the timeout. Names aren't detected Name and place detection needs Local NER model selected, and it must be available; the page shows whether it is. Source: https://latentstack.dev/docs/console/guardrails --- # Platform settings Register models and providers, set prices and context windows, and set rate limits and retry behaviour for your organization. Note Required role Owner or Admin of the active organization. ## How settings work Open Settings from the Administration group (the top bar calls it Platform Settings). Every setting starts at a built-in default. When you change one, your value is saved for the active organization only and marked overridden; everything you haven't changed keeps following the built-in default. Changes take effect within about a minute. The page shows one card per category, with how many settings it holds and how many are overridden. Select a card to open it and All settings to go back. The cards are General, Model Settings, PDF Citations, Rate Limits, Providers, Logging and Prompt Management (see Prompt management). ## Change a single setting - 01Open the cardEach setting shows its name, description and Default. - 02Enter a valueOn/Off settings use a menu; others a text or number box. A Save button appears once you change the value. - 03Select SaveThe setting is marked overridden. To go back to the default, select the reset icon next to it. ## Settings reference ### General | Setting | Default | Meaning | | --- | --- | --- | | Default Provider | openai | Provider used when a request doesn't name one. | | Default Timeout (s) | 300 | How long a single model call may take before it's retried. | | Default Max Retries | 3 | How many times a transient failure is retried before the request fails. | ### Rate Limits | Setting | Default | Meaning | | --- | --- | --- | | Model RL — Enabled | On | Turns on the per-model request caps set in the RPM (model cap) column of Model Settings. | | Max Rate-Limit Sleep (s) | 300 | How long a request waits for a rate limit to clear before failing with 429. | | User RL — Enabled | Off | Caps every user independently with the four limits below, on top of their tier. | | User RL — per 1 min, per 1 hour, per 6 hours, per 1 day | 0 | Requests per user per window. 0 means unlimited. | Per-person limits by model and budget are set on tiers instead; see Tiers and limits. ### PDF Citations | Setting | Default | Meaning | | --- | --- | --- | | PDF Citations — Enabled | Off | Lets the agent add clickable references to answers drawn from an attached PDF, showing the document and printed page. This is the organization-wide switch; each person must also turn it on for themselves. | ### Logging | Setting | Default | Meaning | | --- | --- | --- | | Enable Request Logging | On | Records requests for usage analytics. Turn it off and usage analytics stop recording. | ## Model Settings The model registry: one row per model. A model must be here, with a provider, before it can be allowed on a tier or picked as a judge or agent model. Rows you haven't changed follow the built-in catalogue. | Column | Meaning | | --- | --- | | Model | The model's name. | | Served as | The provider the model is published under. Clients see it as `/`, and tier allow-lists match that exact string. | | Configure | Per-provider details: the ID each provider knows the model by, input, output, cache-read and cache-write prices (dollars per million tokens), the context window and the maximum output tokens. Also lists other providers the model can be routed to. | | Tools | The model supports tool calls. | | Allowed tools | Needs Tools on. Empty allows every tool; otherwise the model may use only the ticked LatentCode tools and other tool requests are rejected. | | Vision | Accepts images. | | PDF | Accepts PDF attachments. Turn on only for models whose provider accepts PDFs, or requests with a PDF fail. | | Reasoning | The model can reason. The second Reasoning column declares which effort levels it accepts and whether reasoning can be turned off. Declare only what the model really supports: an undeclared level fails the request. | | JSON mode | Supports JSON output mode. | | Stream | Supports streaming. | | RPM (model cap) | Requests per minute allowed to this model, enforced when Model RL — Enabled is on. Required; new rows start at 100. | ### Add a model - 01Select AddIn the Models section of Model Settings. - 02Fill in the minimumA Model name, Served as, and the ID the serving provider uses for it. Prices, limits and capabilities are pre-filled for known models. For a model that isn't known on its provider, enter both the input and output price (0 is allowed), the context window and the max output tokens yourself: Save changes refuses the row without them. - 03Check and correctOpen Configure… to see what each provider resolves to and correct anything wrong. Test live calls the model at each reasoning level it declares, using the row as you've edited it, including unsaved prices. It spends tokens. If the row names several providers, pick the one to test. - 04Select Add row, then Save changesEdits to this section aren't saved until you select Save changes at the bottom. Discard throws them away. ### Section tools - Export downloads the section as a JSON file. Provider API keys are exported masked. - Import loads an exported file for the same section and shows which rows it would add, change and remove. Untick any change you don't want, then select Save changes. - The row reset icon reverts one row to its built-in default. The trash icon at the top of the section resets every override in it. - The filter box narrows the rows shown. ## Providers The endpoints and credentials the gateway uses to reach model providers. One row per provider. | Column | Meaning | | --- | --- | | Name | The provider name used in Served as and in model IDs. | | SDK Provider | The vendor this endpoint belongs to. Set it only if you gave the provider a custom name. | | Protocol | Leave blank unless your provider needs a specific API. | | Base URL | The endpoint URL. | | API key | The provider credential. After saving it's shown masked. | | Extra headers | JSON object of headers sent with every call. | | Extra config | JSON object of provider-specific options. | Danger Secrets in exports API key is masked in exports, but anything you store in Extra headers or Extra config is exported as written. Treat exported provider files as secret. Deleting a provider that models are served from leaves those models with no route; the page warns you and lists them. Saving also removes the provider's ID and per-host prices from every model, so pick a new Served as for each. ## Troubleshooting A model doesn't appear in the tier editor Only models with a provider are offered. Check its Served as column and that the provider exists. Save changes is disabled with "served as a host with no id" A model is served by a provider but has no ID for it. Open Configure… and add the ID. Save changes fails with "`input` and `output` rates are required together" or "`context_window` is required" The model isn't known on the provider serving it, so its prices and limits can't be filled in for you. Open Configure…, enter both prices (0 if it's genuinely free), the context window and the max output tokens for that provider, then save. Requests fail with "… has no price, so every call would bill at zero" The model has no price on the provider serving it, so the gateway refuses to call it. This also applies to rows saved before prices were required. Set both the input and output price for that provider under Configure… and select Save changes. Requests fail after adding a model Check the model ID the provider expects, the provider's API key, and the Reasoning declaration. An effort level the model doesn't support fails the request. My change hasn't taken effect Changes take effect within about a minute. Select Refresh to confirm the saved value. Source: https://latentstack.dev/docs/console/settings --- # Prompt management Set the base system prompt that LatentCode and LatentWork run with in your organization, per product and per model. Note Required role Owner or Admin of the active organization. ## What the platform prompt is LatentCode and LatentWork get their base system prompt from the gateway. Each request from them starts with that base prompt; the client's own system instructions follow it and are kept. Prompt Management lets you replace the built-in base prompt with your own, for the whole product or for one model. - Only requests from LatentCode and LatentWork get a platform prompt. Other clients of the gateway get none. - Prompts are per organization. - A team instruction, when the request is made from a team, is added in front of it. For each request, the gateway uses the first of these that's set: | Order | Prompt | Where you set it | | --- | --- | --- | | 1 | The model's own prompt | Per-model prompts | | 2 | The product prompt for LatentCode or LatentWork | The product prompt editor | | 3 | The product's built-in prompt | Ships with LatentStack | ## Open Prompt Management Go to Settings and select the Prompt Management card, or go to /prompts. Platform Settings at the top of the page takes you back. ## Turn custom prompts on or off The System prompt injection toggle (on by default) decides whether your prompts are used. When it's off, LatentCode and LatentWork still get a base prompt, but always the built-in one; your product and per-model prompts are kept and ignored until you turn it back on. ## Edit a product prompt - 01Pick the productChoose LatentCode or LatentWork in the menu above the editor. A built-in or customized badge shows which is in use. - 02Edit the textThe editor starts with the prompt in use. You can use the variables `{model}` and `{date}`; they're filled in for each request. - 03Select SaveIt applies to that product's requests in the organization. Reset to built-in (shown once the prompt is customized) removes your version and goes back to the built-in prompt. ## Set a prompt for one model - 01Find the modelThe Per-model prompts table lists every registered model with its provider and whether its prompt is Custom or Default. - 02Select the pencil iconThe System prompt dialog opens. - 03Write the prompt and select SaveThe same `{model}` and `{date}` variables work here. The model's prompt then replaces the product prompt for requests to that model, from both products. To remove a model's prompt, open it and select Reset to default, or save it empty. Warning Test prompt changes The base prompt shapes how the agent behaves in every session. Try a change with a few real tasks before relying on it, and keep a copy of the previous text. ## Troubleshooting My prompt isn't being used Check that System prompt injection is on, that the model doesn't have its own per-model prompt overriding the product prompt, and that the request comes from LatentCode or LatentWork rather than a direct API call. Where is the regular Settings page? Select Platform Settings at the top of Prompt Management, or Settings in the sidebar. Source: https://latentstack.dev/docs/console/prompts --- # Usage analytics See your organization's spend, requests, tokens and latency, break them down by model, person, provider and team, and email yourself a report. Note Required role Owner or Admin of the active organization. Everyone can see their own usage on My Usage. All figures cover the active organization only, and costs are in US dollars at the prices set in Settings → Model Settings. They count requests over a date range, so they can differ from live credit balances. ## Overview dashboard Overview is the first entry in the Administration group: a summary of the organization at a glance. Pick the range at the top right: 7d, 30d (the default), 90d or All. - Spend, Requests, Input tokens and Output tokens for the range. - Users, Teams and Tiers counts; select one to open that page. - Spend over time and Requests over time charts. - Top models by spend and Top users by spend; select a user to see their usage. Analytics → opens Usage Analytics. ## Usage Analytics Open Usage Analytics from the Administration group for the full breakdown. ### Filter - 01Select FiltersA badge on the button counts the filters in use. - 02Choose a Time frameToday, 7d (the default), 30d, 90d, 1yr, All, or Custom for a start and end date. - 03Narrow it downOptionally pick one Model, User or Product (for example LatentCode, LatentWork, or direct API calls). - 04Select ApplyEvery chart and table on the page updates. ### What the page shows | Section | What it shows | | --- | --- | | Summary cards | Total Cost, Total Requests, Input Tokens, Output Tokens, Avg Cost / Req, Cache Hit Rate, and average input, output, cache-read and cache-write cost per request. | | Token breakdown (cost drivers) | How input, output and cache tokens split, to show what drives cost. | | Requests heatmap | Requests by day of week and hour, in India Standard Time (IST). Hover a cell for that hour, or a day label for the whole day. | | Daily Cost, Daily Requests | Day-by-day totals. | | Cost Trend by Provider | Daily cost, one line per provider. | | Cost by Model, Requests by Model, Avg Latency by Model | Per-model comparisons. | | Latency Distribution | How request latencies are spread. | | Cost by Provider | Share of cost per provider. | | Top Users by Cost | The heaviest users, with requests, cost and the teams they used. | | Usage Explorer | A table you can Group by Model, User, Provider or Project (team), with extra provider and team filters. Columns: requests, cost, input, output, cache-read and cache-write tokens. Grouped by user, select a row for that person's full analytics. | ### Email a report Select Email report to send a summary for the selected time frame to your own email address. The page confirms where it was sent. The report covers the whole organization; the model, user and product filters aren't applied to it. ## One person's usage On the Users page, select ⋮ then View usage on the person's row. You'll see their spend, requests, per-model table and charts in this organization, plus their tier's allowed models, rate limits and budgets with how much of each they've used. It's the admin's view of the person's My Usage page. ## Troubleshooting The dashboard is empty There's no usage in the selected range for the active organization. Widen the range, and check the organization switcher. Totals don't match a credit balance Analytics count requests in a date range; a credit balance counts spending since the limit was last set or reset. I was sent to My Usage instead of the dashboard The dashboard needs the Owner or Admin role in the active organization. Source: https://latentstack.dev/docs/console/usage --- # My usage and budget alerts Check your tier, what you've used of your limits, and your spend, and get an email before you reach your daily budget. These pages are available to everyone. They show your usage in the active organization; switch organizations in the top bar to see another. ## My Usage Open My Usage from the My account group. It has two tabs. If you belong to teams, a menu at the right switches between your Personal usage and each Team; both tabs follow that choice. ### Tier & Budgets tab | Section | What it shows | | --- | --- | | Current Tier, Total Spent, Total Calls | Your tier and your total spend and requests. | | Allowed models | The models your tier lets you call. | | Rate limit usage (per model) | For each model, how many requests you've used of each window's limit (per minute, per hour, per 6 hours, per day). | | Budget usage (USD) | Your spend against each of the tier's budget windows. | | Budget usage (per model) | Your daily spend per model against any per-model caps. | | Credits | Shown when you have a personal credit limit: how much of Your credit limit you've used. | What limits mean and what happens when you reach one is explained in Tiers and limits. ### Overview tab Analytics for your own requests. Select Filters to choose the Time frame (Today, 7d by default, 30d, 90d, 1yr, All, or Custom dates), a Model and a Product. You'll see cost, requests and tokens, average cost per request, cache hit rate, a token breakdown, Requests by hour (IST), a Usage by model table, daily cost and request charts, cost by provider and model, and latency. ### Email yourself a report Select Email me the report to send a usage summary to your account email. ### Request more credits When an organization is selected, Request Credits asks its admins to raise your credit limit. See Credit requests. ## Budget alerts Budget alerts email you when your spend for the day passes a percentage of your tier's daily budget. You're alerted once per threshold per day. Open Budget Alerts from My account, or Budget alerts in the account menu. The page first shows Today's spend: one bar for your personal usage and one for each team with a daily budget. If neither your tier nor any of your teams' tiers has a daily budget, the page says there's nothing to alert on and the controls are disabled. - 01Turn on Email alertsWith the toggle at the top of the card. - 02Add thresholdsUnder Alert me at these % of my daily budget, select the presets (+ 50%, + 75%, + 90%, + 100%) or type a custom value from 1 to 100 and select +. Select the × on a threshold to remove it. - 03Select Save alertsAlerts take effect right away. - Alerts are set per organization: thresholds you save apply to your spend in the active organization. - At 100% your daily budget is used up, and further requests fail with `402 budget_exceeded` until the next day. Tip Suggested thresholds 50% and 90% give you an early notice and a final warning. Add 100% to know when requests start failing. ## Troubleshooting My Usage shows no data Check that the right organization, and the right Personal or Team choice, is selected, and widen the time frame on the Overview tab. I didn't get an alert email Check that Email alerts is on, the thresholds are saved, and your tier has a daily budget. Each threshold is emailed only once a day. Request Credits isn't shown It needs an organization selected. If it shows Request pending, you already have a request waiting for an admin. Source: https://latentstack.dev/docs/console/my-usage --- # Shared sessions Share a LatentCode session with your organization so teammates can pull it into their own sessions as context, and manage what's been shared. ## How sharing works - In LatentCode, run `/push-to-registry` to share the current session with the organization it runs in. - Before it's stored, personal data, secrets and local file paths are stripped from it. - Teammates in the same organization pull it into a session as context with `@sync:reg_`. A shared session is visible only inside its organization. By default each person can share up to 20 sessions an hour, and very large sessions are rejected. See LatentCode for the commands. ## Your shared sessions Open Shared Sessions from My account to see what you've shared in the active organization. Each card shows the title and the goal from the session summary. | Control | What it does | | --- | --- | | Hide / Unhide | Hides the share from teammates without deleting it. The card is marked Hidden by uploader. | | Delete | Removes the share permanently after you confirm. | If an admin hid one of your shares, it's marked Hidden by admin; you still see it, your teammates don't. ## Session Registry (admins) Note Required role Owner or Admin of the active organization. Session Registry in the Administration group lists every session shared to the organization, from any member, grouped by day. Search by title, summary or uploader. Your own shares carry a You badge. - Hide makes a share invisible to everyone except the person who shared it. Unhide reverses it. - Delete removes it permanently. ## Troubleshooting A teammate can't find my session Check that you shared it from the same organization they're working in, and that it isn't hidden. The page says it failed to load Select another organization and back, or reload. The error text says what went wrong. Source: https://latentstack.dev/docs/console/sessions --- # Feedback and notifications Send feedback to your organization's admins, read what members have sent, and keep up with invites, requests and changes through the notifications bell. ## Send feedback Feedback goes to the owner and admins of the active organization, who get a notification for each message. You need an organization selected. - 01Open Send FeedbackFrom the My account group, or go to /feedback. - 02Pick a category (optional)Under What kind of feedback?: Idea, Bug, Praise or Other. - 03Write itA Title and Your feedback are both required. Feedback can be up to 5,000 characters; a counter shows how many you've used. - 04Select Send feedbackYou'll see a confirmation. Send more feedback opens a new form. ## Read feedback (admins) Note Required role Owner or Admin of the active organization. Open Feedback in the Administration group (/feedback-inbox). Messages are grouped by day, newest first; the inbox shows the most recent 500. Filter with All categories. Select a message to see who sent it (From), its Title, Category and Message. ## Notifications The bell in the top bar shows an orange badge with your unread count (up to 9+). New notifications appear within a minute. Unread items are highlighted. ### Act on notifications Select a notification to mark it read and go to the related page. Invites instead have Accept and Decline buttons, so you can answer without leaving the list; an invite that has expired or been revoked disappears when you try to act on it. Mark all read clears the badge. ### What you're notified about | Event | Who is notified | Also emailed | | --- | --- | --- | | You're invited to an organization (if you have an account) | The invitee | Yes | | Someone requests to join, or joins | Owner and admins | No | | Your join request is approved or declined | The requester | Yes | | Your role changes | The member | No | | Ownership is transferred to you | The new owner | Yes | | A member asks for credits | Owner and admins | No | | Your credit request is approved or declined | The requester | Yes | | A member sends feedback | Owner and admins | No | ## Troubleshooting Send feedback is disabled Fill in both the title and the message, and select an organization in the switcher. An invite in the bell shows an error The error explains why. Usually the invite was sent to a different email address from the one you're signed in with. Source: https://latentstack.dev/docs/console/feedback --- # LStack Cloud Agent Connect your GitHub account so hosted agents can work on your repositories, choose the agent's model, and run agent jobs from the browser. Open LStack Cloud Agent from the My account group. The page is titled LatentStack Agent and has two tabs: Agent for running jobs and Settings. A badge at the top right reads Ready once a model is chosen, or Setup required. Every signed-in user can use it; the settings are your own. The GitHub App, GitHub token and allowed repositories are the same ones the Repositories tab under Agents shows; hosted sessions read them from there, and either place changes them. ## Settings The Setup checklist at the top shows whether you have a gateway API key and a model selected. | Card | What it does | Scope | | --- | --- | --- | | Gateway API key | Your API key, read-only, with a copy button. Agent calls use it, so your tier, budgets and guardrails apply to them. | Your account | | GitHub token | A GitHub personal access token used to clone your repositories. It's stored encrypted; once set, only its last four characters are shown. Remove token deletes it. | Your account, in every organization | | Allowed repositories | The repositories you allow agent jobs started from this page to use. Select Load repos to list what the token can reach (up to 1,000), then tick the ones to allow. | Your account | | Model | The model agent jobs from this page use. Only models your tier allows are listed. | The active organization | ### Connect GitHub - 01Create a token on GitHubA personal access token that can read the repositories you want agents to work on. - 02Paste it into GitHub tokenThe field shows `ghp_…` as a hint. - 03Select Load reposThe token is saved and your repositories are listed, private ones with a lock icon. - 04Tick the Allowed repositoriesThen choose a Model. - 05Select Save settingsYou'll see Saved ✓. To replace the token, paste a new one and save. The old one is overwritten. ## Hosted agents (Agents API) The Agents API uses the GitHub token saved here whenever a session works on a repository. Your token must be able to read each repository the session uses. git in the session clones, fetches and pushes with it, through LatentStack, and the `gh` command in the sandbox has it too. Give it only the access you want agents to have. - No token saved: sessions on a repository fail with `github_not_connected`. - The token can't read a repository: `repo_not_accessible`. - Sessions with no repository don't need a token. Note Allowed repositories and Model apply to this page only The Agents API takes its repositories and model from each API request. It doesn't use the Allowed repositories or Model settings here. ## Run a job from the browser - 01Open the Agent tabIf no model is chosen yet, a prompt sends you to Settings. - 02Describe the taskType it in New Job. - 03Select RunOr press `⌘`+`Enter`. The job runs in a sandbox and can take a few minutes. History lists your jobs, newest first. Select one to see its details and result. Job statuses are Queued, Running, Done, Failed and Timeout. Jobs belong to the active organization and use that organization's tier. Before a job starts, the model is checked against your tier, so a disallowed model fails straight away. ## Troubleshooting "Set a GitHub token first" Paste a token before selecting Load repos. "GitHub error: …" when loading repos GitHub rejected the token. Check it hasn't expired and has access to your repositories, then paste it again. "No model selected. Pick one in Agent Settings." Choose a Model on the Settings tab and save. "Model … is not allowed for your tier" Your tier in the active organization doesn't include that model. Pick another, or ask an admin to add it to your tier. "No access tier is assigned for this account" Ask an admin of the organization to assign you a tier. Source: https://latentstack.dev/docs/console/cloud-agent --- # Console troubleshooting Common problems in the console and the gateway errors that console settings cause, with what to change. ## Gateway errors caused by console settings When a request from LatentCode, LatentWork or an API client is refused, the error's `type` tells you which console setting to look at. | Status and type | Meaning | Where to fix it | | --- | --- | --- | | 401 `invalid_api_key` | The API key is wrong or was regenerated. | Copy the current key from your account page. | | 403 `org_access_denied` | The key's user isn't a member of the organization the client selected. | Organizations and members | | 403 `no_tier_assigned` | No tier applies to the person in that organization. | Tiers, or the Tier column on Users | | 403 `model_not_allowed` | The model isn't on the person's tier. | Tiers | | 403 `project_access_denied` | The client selected a team the person isn't in, or a team from another organization. | Teams | | 400 `guardrail_blocked_llm` | The AI judge blocked the request. The response names the policy. | Guardrails, Layer 1 | | 400 `guardrail_blocked_pii` | Sensitive data was detected. The response lists the entities. | Guardrails, Layer 2 | | 402 `budget_exceeded` | A tier spend cap is used up for the current window. | Wait for the window, raise the budget on Tiers, or use Reset rate limits on Users | | 402 `credit_limit_exceeded` | The organization pool or the person's credit limit is empty. | Credits | | 400 `invalid_request_error`: "… has no price, so every call would bill at zero …" | The model has no price on the provider serving it, so it isn't called. | Set its input and output price in Model Settings | | 429 `rate_limit_exceeded` | A request limit is full and didn't reset in time. | Tier rate limits, or Reset rate limits on Users | ## Console problems I don't see the Administration group It needs the Owner or Admin role in the active organization. Open the organization switcher, check your role next to each organization, and pick one you administer. Being a platform admin doesn't show it by itself. A page I opened sent me somewhere else Administration pages send people without the Owner or Admin role to Organizations, and the Overview dashboard sends them to My Usage. I was signed out Sign-ins last 8 hours. Sign in again. API keys aren't affected. The page shows another organization's data Everything follows the organization switcher. Pick the organization you meant; the page reloads for it. "Organization creation is disabled on this deployment" Your installation only allows joining existing organizations. Join a public one or ask for an invite. A change in Settings hasn't taken effect Changes apply within about a minute. Select Refresh on the Settings page to check what's saved. Someone can't use a model I added Adding a model to Model Settings doesn't grant it to anyone. Tick it under Allowed models on their tier. An action is missing from a person's menu on Users Menus only offer what your role allows. Admins can act on members, the owner on admins and members, and nobody on the owner. Account-wide actions need a platform admin. Source: https://latentstack.dev/docs/console/troubleshooting --- # Agents API Run LatentCode agents in the cloud from your own code. The Agents API gives your application the LatentCode agent as a hosted service. LatentStack runs each agent in its own sandbox, keeps its conversation, pauses it when it's idle and brings it back when you write to it again. Your application sends tasks and reads what the agent does. An agent can read and edit code, run commands and tests, and use git in a workspace of its own. That workspace can be empty or hold one or more of your GitHub repositories. When the agent is done, you get back a patch, and any files it made for you. ## Pricing The agent's model calls are billed at the selected model's rates, against your organization and tier, like any other LatentStack request. They appear in My Usage. ## Try an example - Run your first session: run a task in a sandbox, then have an agent change code in a repository. - Review a pull request: check out a PR branch with read-only permissions and collect the review. - Fix failing tests in CI: run an agent from a GitHub Actions job and upload its patch. - Ask a human: stream an agent's work to a terminal and approve risky commands as they come up. ## Core concepts The Agents API is built around four concepts: - Agent: the model, instructions and permissions the agent works with. - Environment: where the agent works and what it can reach. Either an empty workspace, or up to six GitHub repositories on the branch, tag or commit you choose. - Session: a durable instance of an agent. It works on tasks, responds to your input, and survives pauses. - Events: everything the agent does, as a numbered stream you can follow live and resume from. ### A session from start to finish - 01Create a session.Configure the agent and its environment. LatentStack starts a sandbox and clones your repositories. - 02Give it a task.Your first message starts a run as soon as the sandbox is ready, usually within seconds. - 03Follow progress.Stream events, or wait until the session settles. Answer approvals when the agent asks. - 04Continue or steer.Send another message to the same session, or guide the agent while it is working. - 05Collect the result.Read the agent's reply and download its patch, then delete the session. A complete session ``` import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Answer briefly." }, input: "Write a Python script that prints the first 10 prime numbers, run it, and show me the output.", }) for await (const event of sessions.events(session.id)) { if (event.type === "tool.called") console.log("tool:", event.data?.tool) if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } const { last_seq } = await sessions.get(session.id) await sessions.message(session.id, "Now make it print the first 20.") for await (const event of sessions.events(session.id, { after: last_seq })) { if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } await sessions.delete(session.id) ``` ## What the hosted agent provides - Reading, searching and editing code in its own workspace. - Running commands and tests in a sandbox. - Working across several repositories at once, with one patch per repository. - Files in and out: you upload files for the agent, show it images with a message, and download what it makes. - Outputs: files you name are copied out at the end of each run and kept after the session, with links that need no API key. - Webhooks: a signed request to your server when a run finishes or the agent needs you, so nothing has to stay connected. - Schedules: start a session at set times, such as every weekday morning. - A network mode per session: an allowlist of package registries, source hosts and documentation sites; `pip` and `npm` installs only; or nothing at all. - Spend limits in turns, tokens or dollars. At a cap the agent wraps up and the session stops. - Asking before risky actions, under permission rules you set. - Steering while it works, and queueing follow-up tasks. - Summarizing earlier work to keep long sessions within the model's context window. - Pausing when idle and resuming later with its conversation and files intact. Agents use the models, tiers and guardrails your organization already has. Official clients are available for TypeScript and Python, and an MCP server gives the same sessions to any MCP client, such as Claude Code, Cursor or LatentCode, as tools. ## Data and access - A session is visible only to the person who created it, in the organization it was created in. - Repository access uses the GitHub token saved in the console's Repositories tab. git in the sandbox reaches GitHub through LatentStack with that token, so the agent can clone, fetch and push any repository the token can reach, and `gh` has the token in the sandbox (in the `open` network mode). Give the token only the access you want the agent to have. - Authenticate with your personal `ls-` API key. Keep it on your server; never ship it to a browser. Source: https://latentstack.dev/docs/agents --- # Quickstart Run a task in a hosted sandbox, continue the conversation, then have an agent change code in a repository. ## Prerequisites - A LatentStack API key. It starts with `ls-`, and you can copy it from your Account page. - A model on your tier. The examples use `anthropic/claude-sonnet-5.5`; `latentcode models` lists yours. - For step 3, a GitHub token saved in the console's Repositories tab that can read the repository. ``` export LS_API_KEY="ls-…" ``` ## Install the SDK The SDKs are distributed by LatentStack, not npm or PyPI. Install from the URL: ``` npm install https://latentstack.dev/dl/latentcode-sandbox-agents-0.1.4.tgz ``` TypeScript runs on Node 22+, Bun and Deno, with no dependencies. The examples use top-level `await`, so run them as ES modules, for example with `npx tsx quickstart.ts`. Python needs 3.10+. ## 1. Run a task This session has no repository: the agent works in an empty sandbox with a shell, Python 3 and Node.js. With the default rules, it runs commands there without asking. Run a task and print the reply ``` import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Answer briefly." }, input: "Write a Python script that prints the first 10 prime numbers, run it, and show me the output.", }) for await (const event of sessions.events(session.id)) { if (event.type === "tool.called") console.log("tool:", event.data?.tool) if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } ``` ``` tool: bash I created primes.py, which checks divisibility up to the square root of each candidate, and ran it. Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] ``` `events()` yields everything the agent does as it happens. The loop stops at `run.completed`, when the agent has finished the task. ## 2. Continue the conversation A session keeps its conversation and its files. Send another message, and read only the new events by passing `after`: Send a follow-up message ``` const { last_seq } = await sessions.get(session.id) await sessions.message(session.id, "Now make it print the first 20.") for await (const event of sessions.events(session.id, { after: last_seq })) { if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } await sessions.delete(session.id) ``` ``` Updated the loop to collect 20 primes and ran it. Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71] ``` ## 3. Change code in a repository Give the session a repository and a task, then download what it changed as a patch. The agent works on its own clone, and nothing is pushed. Add a file to a repository and get the patch ``` import { writeFile } from "node:fs/promises" import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Keep changes small.", // This task only needs the file tools. Denying the shell also means the agent never stops to ask. permissions: [{ action: "bash", effect: "deny" }], }, environment: { type: "repos", repos: ["acme/demo"] }, input: "Add a CONTRIBUTING.md that explains how to set up this project and run its tests, based on what you find in the repository.", }) try { for await (const event of sessions.events(session.id)) { if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } const patch = await sessions.artifact(session.id) await writeFile("contributing.patch", patch) // apply with: git apply contributing.patch console.log(patch) // a unified diff adding CONTRIBUTING.md } finally { await sessions.delete(session.id) } ``` The patch is a unified diff against the commit the agent started from. Apply it with `git apply contributing.patch`, or open a pull request with it. Note Why the example denies the shell By default the agent still asks before commands that reach the network, such as `git fetch`. A script that doesn't answer would wait forever. This task only needs the file tools, so denying the shell keeps it unattended. See Approvals to answer instead. ## Next steps - Configuring agents: model, instructions and permissions. - Run and continue: steering, queueing and cancelling. - Examples: complete programs to start from. Source: https://latentstack.dev/docs/agents/quickstart --- # Configuring agents Choose the model, write the instructions, and decide what the agent may do without asking. You configure an agent when you create its session. The configuration stays with the session for its whole life, across pauses and resumes. To run with different settings, create a new session. ## Session settings `agent`objectrequired `model`stringrequired A model your tier allows, e.g. `anthropic/claude-sonnet-5.5`. `latentcode models` lists yours. `instructions`stringoptional How the agent should work: its role, constraints and the shape of its answer. Up to 20,000 characters. `permissions`list of rulesoptional What the agent may do alone, must ask about, or may never do. See Permissions. `mcp_servers`list of serversoptional Remote MCP servers whose tools the agent may use. See MCP servers. `environment`objectoptional Where the agent works, and what it can reach. Omit it for an empty sandbox. See Repositories and patches and Network. `limits`objectoptional Caps on what the session may spend, in turns, tokens or dollars. See Spend limits. `input`stringoptional The first task. It runs as soon as the sandbox is ready. You can also create the session without it and send a message later. `metadata`objectoptional Your own key/values, e.g. a ticket or pull request number. Returned unchanged on the session. `files`objectoptional Files to put in the workspace before the first message runs. See Send files with create. `outputs`list of pathsoptional Files to copy out at the end of each run and keep after the session ends. See Outputs. `end_after_run`booleanoptionaldefault `false` Stop the session once its run has ended. See End after the run. `webhook`objectoptional A URL to tell about this session as it changes state. See Webhooks. `idempotencyKey · idempotency_key`stringoptional Makes creation safe to retry. The same key with the same settings returns the first session instead of starting another. ## Instructions Instructions are added to LatentCode's own system prompt, so you don't need to explain how to use tools. Say what good work looks like for your task: - The goal and the limits: "Fix the failing tests. Do not change test assertions or add dependencies." - What to do when unsure: "If a fix needs a schema change, stop and explain instead." - The shape of the answer, when your code reads it: "End with a Markdown list of files changed and why." Put anything that changes per task in the message, not the instructions. You don't need to describe the sandbox. When it starts, LatentStack writes a note into the agent's instructions: where each repository is, where files go, what a pause keeps and what the network allows. Your instructions come after that note and win where the two meet. ## Permissions Every tool call is checked against the session's rules. Each rule has one of three effects: | Effect | What happens | | --- | --- | | allow | The tool runs. | | ask | The agent stops and asks you. See Approvals. | | deny | The call is refused and the agent is told, so it can try another way. | ### Default rules Without `permissions`, the agent works on its own. The sandbox is the boundary, not a prompt: inside its workspace the agent can read, edit and run most commands without asking. An earlier default asked before most commands, and real tasks needed 34 to 94 approvals each. | Tool | Default | | --- | --- | | read · glob · grep · list | allow | | edit | allow, except secrets and keys (`*.env`, `*.env.*`, `*.pem`, `*.key`, `*/.ssh/*`, `*/.aws/*`), which are denied | | bash | allow, any command | | external_directory | deny, except the whole workspace (`/work/*`), which is allowed | | webfetch · websearch | allow when the session's network is `open`; deny otherwise, since they couldn't reach anything | | task | allow. Subagents run as sessions of their own, and their spend counts toward this session's limits. | | an MCP server's tools | allow; only the listed ones when the server has a `tools` list | LatentCode itself still asks before some commands, even with `bash` allowed. These are its own checks, separate from the `bash` rule: commands that reach the network (`curl`, `gh`, `git fetch`, `git push`, `pip install`, `npm install` and similar), dangerous commands (a recursive `rm`, `sudo`, deleting a branch) and commands that write git metadata (`git add`, `git commit`, `git checkout`). See Approvals. ### Writing rules A rule is `{ action, resource, effect }`. Rules apply in order and the last matching rule wins, so write the general rule first and exceptions after it. | Field | Values | | --- | --- | | action | A tool: `read`, `edit`, `glob`, `grep`, `list`, `bash`, `task`, `webfetch`, `websearch`, `external_directory`, `skill`, `lsp`, `todowrite`, an MCP server's tool as `_` or all of them as `_*`, or `*` for every tool. | | resource | What the call targets, with `*` as a wildcard: a command line for `bash` (`git *`), a path for `read` and `edit` (`src/*`). Defaults to `*`. `webfetch`, `websearch` and `todowrite` take only `*`. | | effect | `allow`, `ask` or `deny`. | A read-only reviewer ``` const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "You review code. Read before you judge, name files and lines, and never modify files.", permissions: [ { action: "*", effect: "deny" }, // anything not allowed below is refused { action: "read", effect: "allow" }, { action: "glob", effect: "allow" }, { action: "grep", effect: "allow" }, { action: "list", effect: "allow" }, { action: "bash", resource: "git *", effect: "allow" }, { action: "bash", resource: "git push*", effect: "deny" }, // later rules win ], }, environment: { type: "repos", repos: ["acme/demo"] }, input: "Review the most recent commit (git show HEAD). List up to three concrete risks or improvements.", }) ``` Warning Your rules replace the default rules When you pass `permissions`, your list replaces the table above entirely, including its denies on secret files and outside the workspace. Tools you leave out follow LatentCode's own rules, not the table. To stay in control, start with `{ action: "*", effect: "ask" }` or `deny` and allow what the task needs after it. An invalid rule, such as an unknown tool, an unknown effect, or a resource on a tool that takes none, is rejected when you create the session, with an error naming the rule. ### Common setups | Goal | Rules | | --- | --- | | Let it work on its own | Omit `permissions`. It still asks before network and dangerous commands. | | Never wait for a person | Start with `{ action: "*", effect: "deny" }`, then allow what the task needs. | | Approve every command yourself | `{ action: "bash", effect: "ask" }` after your other rules | | Keep it inside the code | Set `network` to `none`, or add `{ action: "webfetch", effect: "deny" }` and `{ action: "websearch", effect: "deny" }` to your rules | ## Network `environment.network` sets what the sandbox can reach. The sandbox never gets a route of its own: everything it reaches goes through LatentStack. ``` environment: { type: "repos", repos: ["acme/payments"], network: "readonly" } ``` | network | The sandbox can reach | | --- | --- | | open | The default on latentstack.dev. Package managers, `curl`, `go`, `cargo`, `apt` and the agent's own web search and fetch go through an egress proxy to an allowlist of package registries, source hosts and documentation sites. A host that isn't on the list is refused. | | readonly | Only `pip` and `npm`, through the gateway, for reading: packages install, and nothing can be uploaded. No web search or fetch. | | none | The gateway and nothing else. Nothing can be installed. | - The proxy can't see inside HTTPS, so an `open` session can upload to a host on the list. Use `readonly` or `none` when that matters. - On a deployment without the proxy, `readonly` is the default and `open` is refused with `invalid_request`. - git is the same in every mode. Clone, fetch and push of any GitHub repository your token can reach go through the gateway with your token, and `gh` has your token in the sandbox. `gh` calls the GitHub API, so it works in `open` only. See Repositories and patches. ## MCP servers Give the agent the tools of remote MCP servers, such as GitHub, your issue tracker or your own APIs. Name each one in `agent.mcp_servers` when you create the session: ``` const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", mcp_servers: [{ name: "github", url: "https://api.githubcopilot.com/mcp/", headers: { Authorization: `Bearer ${process.env.GITHUB_TOKEN}` }, }], }, input: "Summarise the open issues labelled bug in acme/payments.", }) ``` `name`stringrequired Up to 32 lower-case letters, digits and `-`, starting with a letter. It can't be a built-in tool's name, such as `read` or `bash`, or the first word of one, such as `create` (`create_docx`). `url`stringrequired The server's https URL. `headers`objectoptional Sent with every request to the server, e.g. `{ "Authorization": "Bearer …" }`. `tools`list of stringsoptional Only these of the server's tools. Leave it out for every tool. `timeout_seconds`integeroptionaldefault `60` How long one request to the server may take, from 1 to 600. A session takes up to 10 servers. ### Tool names and permissions The agent sees each tool as `_`: the `get_issue` tool of the `github` server is `github_get_issue`. They run without asking unless your rules say otherwise; a rule for every tool (`action: "*"`) covers them too. A rule names one tool the same way, or every tool of a server as `github_*`, with no `resource`: JSON ``` "permissions": [ { "action": "github_*", "effect": "ask" }, { "action": "github_get_issue", "effect": "allow" } ] ``` ### Choosing tools With `tools`, the agent gets only the tools you list. LatentStack leaves the others out of the server's tool list and refuses any call to them before it reaches the server, whatever the agent tries. ### Credentials Header values are write-only. LatentStack keeps them encrypted, makes each request to the server itself and adds the headers then, so they never enter the sandbox and the agent can't read or print them. Reading the session back shows each server's `name`, its `url` with any query values shown as ``, the names of its headers (`header_names`), its `tools` and its `timeout_seconds`, never a header's value. ### Network MCP servers work in every network mode, `none` included: the request to the server is made by LatentStack, not from the sandbox. ### Which servers work - Servers that speak MCP's Streamable HTTP transport. The older SSE transport isn't supported. - A public https URL on port 443. A self-hosted deployment can let in its own private hosts by listing them in `AGENT_MCP_PRIVATE_HOSTS`. - A server that signs in with a header, such as a token or an API key. Servers that need you to sign in through a browser (OAuth) aren't supported. ## Spend limits `limits` caps what one session may spend. Set any of the three caps; leave out the ones you don't need. ``` const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5" }, limits: { max_turns: 50, max_cost_usd: 5 }, input: "Fix the failing tests.", }) ``` `max_turns`integeroptional Model calls, subagents' included. A failed call counts. `max_tokens`integeroptional Every token processed, cache reads and writes included. `max_cost_usd`numberoptional Dollars. Refused with `invalid_request` on a deployment that can't price usage. ### When a cap is reached - The agent is told to wrap up: no more tools, and a short text of what is done and what is left. - The session is paused after that step, with the cap as its `pause_reason`. Its patch is captured first, and it keeps its disk and conversation. - While it wraps up, new messages are refused with `limit_reached`. Approvals and cancel still work. Raising the cap past what it has spent during the wrap-up lets it go on afterwards instead of pausing. - To go on, raise the cap with `sessions.update()` (`PATCH /v1/agents/sessions/{id}`), then send a message or resume. Until then, continuing is refused with `limit_reached`, and nothing about the session changes. The same goes for a session you deleted at its cap: while its disk is kept, raise the cap, then resume it. - A cap can be exceeded by about two steps: the step that crossed it and the wrap-up step are both spent. ### What a session has spent Every read of a session carries `limits`: the caps, and the running tally they are checked against. JSON ``` "limits": { "max_turns": 50, "max_tokens": null, "max_cost_usd": 5.0, "spent": { "turns": 12, "tokens": 418230, "cost_usd": 0.61, "subagents": { "turns": 3, "tokens": 52011, "cost_usd": 0.08 } } } ``` | Field | Meaning | | --- | --- | | limits.spent | What counts toward the caps: `turns`, `tokens` and `cost_usd`. The subagents' share is included, and also shown on its own under `subagents`. | | usage | On a single `get()` only: `input_tokens`, `output_tokens`, `cache_read_tokens`, `cache_write_tokens`, `reasoning_tokens`, `model_calls`, `estimated_cost_usd`, `sandbox_seconds` and `as_of`. It runs a little behind; read it again later for the final figure. | | pause_reason | While paused: the cap it reached (`max_turns`, `max_tokens` or `max_cost_usd`), or `requested`, `idle_timeout`, `hard_limit` or `restored`. | | stop_reason | `null` while the session lives. Then `deleted` or `paused_expired`. A session made with `end_after_run` can also stop with `run_finished`, `idle_timeout` or `hard_limit`. | ## Other limits - Instructions: 20,000 characters. A message: 100,000 characters. - Up to 6 repositories per session. - Your administrator may cap how many active sessions an organization can have at once. Source: https://latentstack.dev/docs/agents/configuration --- # Run and continue Give an agent a task, know when it's done, and keep the conversation going. ## Sessions and runs A session is one agent with one conversation and one workspace. A run is one piece of work inside it: the agent picks up a message, uses tools until it has an answer, and stops. A message sent to an idle session starts a new run. A message sent during a run joins it. ## Start a task `create()` returns straight away with status `provisioning`. The first message runs as soon as the sandbox is ready, usually within seconds. Follow events until `run.completed` to know the task is done: Run a task and print the reply ``` import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Answer briefly." }, input: "Write a Python script that prints the first 10 prime numbers, run it, and show me the output.", }) for await (const event of sessions.events(session.id)) { if (event.type === "tool.called") console.log("tool:", event.data?.tool) if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } ``` Every run ends with one of two events: - `run.completed`: the agent finished, or you cancelled the run. Its answer is in the `text.ended` events before it. - `run.failed`: the run stopped on an error, such as the model provider failing. `data.error` says why. The session is still usable: send another message to retry. Warning Use events, not wait(), to know a task is done `wait()` returns on the first settled status. Right after `create()`, a session is briefly `idle` before its first message starts, so `wait()` can return before the work has begun. Use `wait()` for status changes you started yourself, like a pause, and events for runs. ## Continue the conversation Send another message to the same session. It starts a new run with everything that came before. Pass the session's `last_seq` as `after` to read only what's new. Send a follow-up message ``` const { last_seq } = await sessions.get(session.id) await sessions.message(session.id, "Now make it print the first 20.") for await (const event of sessions.events(session.id, { after: last_seq })) { if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } await sessions.delete(session.id) ``` ## Steer or queue A message sent during a run steers it: the agent takes it into account without starting over. To add work for afterwards instead, send it with `delivery: "queue"`. It becomes a new run when the current one completes. Steer the current run, then queue a follow-up ``` // Joins the run in progress: the agent adjusts without starting over. await sessions.message(session.id, "Make every poem a haiku, and keep going until all five files exist.") // Runs after the current run finishes. await sessions.message(session.id, "Then list the files you created, one per line.", { delivery: "queue" }) ``` ``` message taken: "steer" ← the first task message taken: "steer" ← joined the run in progress message taken: "queue" ← ran after it All five haiku files are done — poem1.md through poem5.md, each a short sea-themed haiku. poem1.md poem2.md … ``` ## Cancel a run Cancelling stops the current run. The session and everything done so far stay, and the next message starts a new run. Cancel the current run ``` await sessions.cancel(session.id) const settled = await sessions.wait(session.id) console.log(settled.status) // "idle": the session is still there for the next message ``` To end the session itself, delete it. See Manage sessions. ## Coming back later You don't need to keep a connection open. Store the session id, and the last event number you handled, with your own data. Later, send a message and read events `after` that number. If the session paused while you were away, the message wakes it with its files and conversation intact. The long-lived assistant example does exactly this. Source: https://latentstack.dev/docs/agents/sessions --- # Events Follow what an agent does as it works, and pick up exactly where you left off. `sessions.events(id)` yields everything that happens in a session, in order, for as long as the session is alive. It reconnects by itself if the connection drops, and ends when the session is deleted. Break out of the loop once you have what you need. To be told when a run finishes without keeping a stream open, use webhooks. ## What you receive | Item | Has seq | What it is | | --- | --- | --- | | session.status | no | The session's status. It comes first, and again whenever the status changes, with `status`, `error` and any `pending_approvals`. Once the session stops, `stop_reason` says why, and while it is paused `paused_at` says since when. | | approval.requested | no | The agent is waiting for your permission. See Approvals. | | event | yes | Something the agent did: `{ seq, type, data, time }`. Events are stored and numbered from 1. | JSON ``` { "type": "session.status", "status": "running", "error": null, "pending_approvals": [], … } { "seq": 7, "type": "tool.called", "data": { "tool": "bash", "input": { "command": "python3 --version" }, … }, "time": "2026-09-28T07:18:16Z" } { "seq": 12, "type": "text.ended", "data": { "text": "The installed Python version is 3.11.2." }, "time": "…" } { "seq": 13, "type": "run.completed", "data": { … }, "time": "…" } ``` Note Only answer requests without a seq An `approval.requested` item without a `seq` is a live request. Check `"seq" in event` before you answer, as every example here does. ## Follow a session Show progress, count tokens, keep your place ``` let answer = "" let outputTokens = 0 let position = 0 // the last event you handled; store it to resume later for await (const event of sessions.events(session.id)) { if (event.type === "session.status" && "status" in event) { console.log("status:", event.status) continue } if (!("seq" in event)) continue // an approval or question: see Approvals and questions position = event.seq if (event.type === "tool.called") console.log("tool:", event.data?.tool, JSON.stringify(event.data?.input)) if (event.type === "step.ended") outputTokens += Number((event.data?.tokens as { output?: number } | undefined)?.output ?? 0) if (event.type === "text.ended") answer = String(event.data?.text) if (event.type === "run.failed") console.error("run failed:", event.data?.error) if (event.type === "run.completed" || event.type === "run.failed") break } console.log(answer, `(${outputTokens} output tokens)`) ``` ``` status: provisioning status: idle status: running tool: bash {"command":"python3 --version","description":"Check Python version"} The installed Python version is 3.11.2. (91 output tokens) ``` ## Resume without gaps Every event has a `seq`. Pass the last one you handled as `after`, and the stream continues with the next event: nothing missed and nothing repeated, whether after a dropped connection, a restart of your own service, or days later. `session.last_seq` is always the newest number. Continue from where you stopped ``` await sessions.message(session.id, "And which version of Node.js?") // Only events after `position`: nothing missed, nothing repeated. for await (const event of sessions.events(session.id, { after: position })) { if ("seq" in event) position = event.seq if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } ``` ### Stopping the stream - Break out of the loop. This closes the connection. - TypeScript: pass `signal` from an `AbortController` to stop it from elsewhere. - Python: pass `stop`, a `threading.Event` (`asyncio.Event` with the async client). It may take a few seconds to stop. ## Event types | type | data | Meaning | | --- | --- | --- | | run.started | | The agent picked up a message. | | run.completed | | The run finished, or was cancelled. | | run.failed | error | The run stopped on an error. The session is still usable. | | text.ended | text | A complete block of the agent's reply. Text arrives whole; there are no partial deltas. | | tool.called | tool, input | The agent called a tool, e.g. `bash` with `{ command }`. | | tool.success · tool.failed | content · error | A tool call finished, or failed. After a failure the agent usually carries on. | | step.ended | tokens, finish | One model call ended. `tokens` has `input`, `output`, `reasoning` and `cache` counts. | | prompt.admitted | prompt, delivery | A message you sent entered the conversation (`steer` or `queue`). | | step.started · text.started | | A model call, or a reply block, began. | | tool.input.started · tool.input.ended | name | The model is writing a tool call. | | reasoning.started · reasoning.ended | text | The model's reasoning, for models that expose it. | | compaction.started · compaction.ended | text | Earlier conversation was summarized to fit the context window. | | retried | attempt, error | A model call was retried after a transient error. | New event types can appear over time. Ignore any you don't recognise. Source: https://latentstack.dev/docs/agents/events --- # Approvals Let an agent work on its own, but decide yourself before it does something risky. When a permission rule says `ask`, the agent stops and the session's status becomes `waiting`. With the default rules that happens only before commands that reach the network, dangerous commands and commands that write git metadata. The agent waits for as long as it takes, and a waiting session is never paused for being idle. ## The request The event stream yields an `approval.requested` item that says what the agent wants to do: JSON ``` { "type": "approval.requested", "request_id": "per_0e6e0f207001Qg0xMR9tdla3uP", "action": "bash", "resources": ["uname -s"], "metadata": {} } ``` | Reply | Effect | | --- | --- | | once | Allow this call. | | always | Allow this call, and matching calls for the rest of the session. | | reject | Refuse it. An optional message tells the agent why, so it can adjust. | ## Answer from code This session asks before every shell command. The code allows `uname` and rejects everything else: Approve some commands, reject the rest ``` const allowed = /^uname\b/ for await (const event of sessions.events(session.id)) { if (event.type === "approval.requested" && !("seq" in event)) { const ok = event.action === "bash" && (event.resources ?? []).every((command) => allowed.test(command)) console.log(ok ? "approve:" : "reject:", event.action, (event.resources ?? []).join(" ")) if (ok) await sessions.approve(session.id, event.request_id, "once") else await sessions.approve(session.id, event.request_id, "reject", "Only uname is allowed here.") } if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } ``` ``` approve: bash uname -s reject: bash whoami - uname -s → Linux - whoami → failed to execute (the command was rejected) ``` ## Ask a person To put a person in the loop, show them the request and send their answer. This terminal chat sets `bash` to `ask`, so it asks you about every shell command: Approve commands from the terminal ``` // A chat with an agent in your terminal. You approve its shell commands as they come up. import * as readline from "node:readline/promises" import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const terminal = readline.createInterface({ input: process.stdin, output: process.stdout }) const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", permissions: [{ action: "bash", effect: "ask" }] }, input: await terminal.question("task> "), }) try { for await (const event of sessions.events(session.id)) { if (event.type === "approval.requested" && !("seq" in event)) { const answer = await terminal.question(`run \`${(event.resources ?? []).join(" ")}\`? [y]es / [a]lways / [n]o `) const reply = answer === "a" ? "always" : answer === "y" ? "once" : "reject" await sessions.approve(session.id, event.request_id, reply) } if (event.type === "tool.called") console.log(` · ${event.data?.tool}`) if (event.type === "text.ended") console.log(`\n${event.data?.text}\n`) if (event.type === "run.completed" || event.type === "run.failed") { const next = await terminal.question("task> (empty to quit) ") if (!next) break await sessions.message(session.id, next) } } } finally { terminal.close() await sessions.delete(session.id) } ``` - The same shape works for a Slack bot or a web UI: forward the request, then answer with the session id and `request_id`. The request stays pending until someone answers, and it's listed under `pending_approvals` on every `session.status` item. - Answering a request twice, or one that no longer exists, raises `not_found`. Treat it as done. ## Never wait for a person For CI jobs and other unattended work, set rules that never ask. Start with a catch-all `deny` and allow only what the task needs. A denied call is refused and the agent looks for another way, so it never stops to wait. A read-only reviewer that never asks ``` const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "You review code. Read before you judge, name files and lines, and never modify files.", permissions: [ { action: "*", effect: "deny" }, // anything not allowed below is refused { action: "read", effect: "allow" }, { action: "glob", effect: "allow" }, { action: "grep", effect: "allow" }, { action: "list", effect: "allow" }, { action: "bash", resource: "git *", effect: "allow" }, { action: "bash", resource: "git push*", effect: "deny" }, // later rules win ], }, environment: { type: "repos", repos: ["acme/demo"] }, input: "Review the most recent commit (git show HEAD). List up to three concrete risks or improvements.", }) ``` Source: https://latentstack.dev/docs/agents/approvals --- # Manage sessions Check a session's state, pause and resume it, fork it, find your sessions, and clean up. ## Session state Retrieve a session ``` const current = await sessions.get(session.id) console.log(current.status, current.last_seq, current.error) ``` JSON ``` { "id": "ags_4843742656c9cbc90685c6d2", "object": "agent.session", "status": "idle", "agent": { "model": "anthropic/claude-sonnet-5.5", "instructions": "Answer in one short sentence.", "permissions": null }, "environment": { "type": "none", "network": "open" }, "metadata": { "customer": "cus_123" }, "created_at": "2026-09-28T07:17:41.522000+00:00", "updated_at": "2026-09-28T07:17:52.106000+00:00", "paused_at": null, "ended_at": null, "instance_number": 1, "instance_context": "new", "last_seq": 8, "error": null, "stop_reason": null, "limits": { "max_turns": null, "max_tokens": null, "max_cost_usd": null, "spent": { "turns": 1, "tokens": 14210, "cost_usd": 0.0071, "subagents": { "turns": 0, "tokens": 0, "cost_usd": 0.0 } } }, "usage": { "input_tokens": 6, "output_tokens": 14, "cache_read_tokens": 0, "cache_write_tokens": 14190, "reasoning_tokens": 0, "model_calls": 1, "estimated_cost_usd": 0.0071, "sandbox_seconds": 11, "as_of": "2026-09-28T07:17:53.004000+00:00" } } ``` | Field | Meaning | | --- | --- | | status | Where the session is in its lifecycle (below). | | last_seq | The newest event number. Pass it as `after` to read only what comes next. | | last_activity_at | When it last did something: a step, a message, an answer or a file change. | | error | `{ type, message }` if something went wrong with the sandbox, otherwise `null`. | | instance_number · instance_context | Whether the conversation was restored after a pause: `instance_context` is `full`, `workspace_only` or `new`. `instance_number` goes up by one each time the session resumes (see Pause and resume). | | environment · metadata | The repositories it works on and its `network`, and your own key/values. | | pause_reason | Why it is paused: `requested`, `idle_timeout`, `hard_limit`, the spend limit it reached, or `restored` after a stop was undone. | | volume_kept_until | When stopped: its disk is kept until then, and a resume before it brings the session back. Its files can't be read while it is stopped: resume it first, or name them in outputs to keep them. | | stop_reason | Why it ended: `deleted` or `paused_expired`. A session made with `end_after_run` stops with `run_finished` after its run, or with `idle_timeout` or `hard_limit` where another session would pause. `null` while it lives. | | limits · usage | Its spend caps and what counts toward them. `usage`, on a single read only, is the fuller sum and runs a little behind. See Spend limits. | ## Statuses | Status | Meaning | | --- | --- | | provisioning | A sandbox is starting. Messages sent now are delivered when it's ready. | | idle | Ready and not working. A message starts a run. | | running | Working on a run. A message steers it. | | waiting | Blocked on an approval. | | pausing · paused | The sandbox has been released. The conversation and files are kept, and a message resumes it. A session paused at a spend limit continues once the limit is raised. | | stopping · stopped | Deleted, or paused for too long. `stop_reason` says which. Its disk is kept for 7 days, and a resume in that time brings it back. Events and patches can still be read. | | failed | Couldn't start, for example because its sandbox wasn't ready within 240 seconds (`start_timeout`). See `error`, and create a new session. | ## Pause and resume Sandboxes are temporary, but sessions aren't. A pause keeps everything: the session's files and its conversation live on its own disk, not in the sandbox. The next message starts a new sandbox on the same disk, and the agent carries on where it left off. Pause, then continue with a message ``` await sessions.pause(session.id) await sessions.wait(session.id, { until: ["paused"] }) // Later: a message resumes it. No need to call resume() first. const { last_seq } = await sessions.get(session.id) await sessions.message(session.id, "What word did I ask you to remember?") for await (const event of sessions.events(session.id, { after: last_seq })) { if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } const resumed = await sessions.get(session.id) console.log(resumed.instance_number, resumed.instance_context) ``` ``` You asked me to remember the word "pelican". 2 full ``` The session resumed (`instance_number: 2`) with the whole conversation restored (`instance_context: "full"`). With `workspace_only`, the files came back but the conversation starts over, so include the context the agent needs in your message. `new` means the session hasn't been resumed yet. | Sessions pause or stop on their own | Default | | --- | --- | | Idle, with nothing to do → paused | 30 minutes | | One sandbox running for a long time → paused | 4 hours | | Paused and untouched → stopped | 4 months (120 days) | After the 4-hour limit, the next message continues the session in a new sandbox on the same disk. A session left paused for 4 months is stopped with `stop_reason` `paused_expired`, and its disk is deleted 7 days later. A session that's waiting for an approval is never paused for being idle. These are the defaults; your administrator may set others. If a sandbox disappears unexpectedly, the session moves to `paused` with an `error`, and the next message resumes it with its files. ## Fork a session A fork is a new session that starts from another one as it is now: the same model, repositories and network, the source's changes to its repositories, and its conversation. The two then go on separately, so you can try a second approach without losing the first. Python ``` fork = client.agents.sessions.fork(session["id"], input="Try it without the cache.") print(fork["id"], fork["forked_from"]) # {"session_id": "ags_…", "seq": 42} ``` TypeScript ``` const fork = await client.agents.sessions.fork(session.id, { input: "Try it without the cache." }) ``` - Only an `idle` session can be forked. A running or waiting one is refused with 409 until its run ends; a paused one must be resumed first. - Each repository starts at the commit the source was cloned at, with the source's changes on top. Commits the source made, pushed or not, arrive as uncommitted changes. - Files outside the repositories (`uploads/`, `out/`) are not carried over. - Spend starts at zero. `metadata`, `outputs` and `end_after_run` default to the source's; `limits` are the source's caps, with any you pass replacing them. - The fork's events start at 1. Its `forked_from` names the source and the source's last event at the time. ## Find your sessions Sessions are listed newest first, 20 per page by default and up to 100. Use `metadata` to tie them to your own records. You only ever see sessions you created, in the organization you're working in. List sessions and filter by metadata ``` const page = await sessions.list({ limit: 20 }) const mine = page.data.filter((s) => s.metadata?.customer === "cus_123") console.log(mine.map((s) => `${s.id} ${s.status}`)) ``` When `has_more` is true, pass `next_after` as `after` for the next page. Over HTTP, `GET /v1/agents/sessions?status=waiting,paused` lists only the statuses you name, and `?needs_you=true` only the sessions waiting on you. `GET /v1/agents/sessions/summary` counts your sessions by status, says how many wait on you (waiting for an answer, or paused at a spend limit), and adds up what the sessions started in the last 24 hours have spent. ## Delete a session Deleting stops the session and releases its sandbox. Its disk is kept for 7 days (`volume_kept_until`): a `resume()` in that time undoes the delete, with every file and the conversation. After that the disk is deleted, so download any files you need. A final patch is saved when it stops, and events and patches stay readable afterwards. Delete a session ``` const stopped = await sessions.delete(session.id) console.log(stopped.status) ``` Warning Always clean up An idle session holds its sandbox until it pauses on its own. In scripts, CI and batch jobs, delete sessions in a `finally` block, as every example on these pages does. ## Retry safely Pass an idempotency key when creating sessions from code that may run twice, such as a queue worker or a webhook handler. A second call with the same key returns the first session instead of starting another. The same key with different settings raises `conflict`. Create a session exactly once ``` const settings = { agent: { model: "anthropic/claude-sonnet-5.5" }, input: `Summarize ticket ${ticket} in one line.`, idempotencyKey: `summarize-${ticket}`, } const first = await sessions.create(settings) const retry = await sessions.create(settings) // e.g. your job queue ran twice console.log(first.id === retry.id) // true: one session, not two ``` - When there's no capacity, creating or resuming fails with `runner_unavailable`. Retry after a short wait, with the same key. - Your organization may cap active sessions. Past the cap, creation fails with `session_limit_reached`. Source: https://latentstack.dev/docs/agents/manage --- # Repositories and patches Give an agent your GitHub repositories on any branch, tag or commit, and get back what it changed as a patch. ## Environments | environment | The agent gets | | --- | --- | | omitted, or { type: "none" } | An empty sandbox with a shell, git, Python 3 and Node.js. No GitHub setup, and no patch. | | { type: "repos", repos: [...] } | Up to six of your repositories, each cloned into its own folder. One patch per repository. | Both take `network`, which sets what the sandbox can reach. See Network. Repository sessions need a GitHub token that can read every listed repository. Save one in the console's Repositories tab, and tick the repositories there. Creating a session checks access first, and fails with `github_not_connected` or `repo_not_accessible` (naming the repository) if something is missing. ## Choose where to start A repository listed as `"owner/name"` starts on its default branch. Use `{ repo, ref }` to start on a branch, tag or commit. With a single repository, a top-level `ref` does the same. One repository, on a pull request's branch ``` environment: { type: "repos", repos: ["acme/payments"], ref: "feature/refunds" } ``` Several repositories, each on its own ref ``` const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Keep changes minimal.", permissions: [{ action: "bash", effect: "deny" }], // file tools only }, environment: { type: "repos", repos: [ "acme/demo", // its default branch { repo: "acme/website", ref: "master" }, // a branch, tag or commit ], }, input: "In each repository, add a line at the end of the README: 'Maintained by the platform team.'", }) ``` ### The workspace ``` /work ← the agent starts here, in every session ├── demo/ ← acme/demo ├── website/ ← acme/website ├── uploads/ ← your files └── out/ ← what the agent leaves for you ``` - The workspace is the session's own disk (5 GiB), mounted at `/work`. Each repository is cloned into `/work/`, so two repositories with the same name can't be used together. - Your uploads go in `uploads/`, and the agent leaves what you ask for in `out/`. See Files. - The agent is told which folder holds which repository, and where files go, before it reads your instructions. - git works as usual inside each clone. Clone, fetch and push of any GitHub repository your token can reach go through LatentStack with your token, and `gh` has your token in the sandbox. `gh` calls the GitHub API, so it needs the `open` network mode. Give the token only the access you want the agent to have. ## Patches A patch is the diff of one repository against the commit it started from, including new, deleted and binary files. It applies with `git apply`. Patches are saved when a run ends, when the session pauses and when it stops, so you can download them after the sandbox is gone. While the session is active, you always get the current state. Change one repository and save the patch ``` import { writeFile } from "node:fs/promises" import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Keep changes small.", // This task only needs the file tools. Denying the shell also means the agent never stops to ask. permissions: [{ action: "bash", effect: "deny" }], }, environment: { type: "repos", repos: ["acme/demo"] }, input: "Add a CONTRIBUTING.md that explains how to set up this project and run its tests, based on what you find in the repository.", }) try { for await (const event of sessions.events(session.id)) { if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } const patch = await sessions.artifact(session.id) await writeFile("contributing.patch", patch) // apply with: git apply contributing.patch console.log(patch) // a unified diff adding CONTRIBUTING.md } finally { await sessions.delete(session.id) } ``` ### Several repositories `artifacts()` lists one entry per repository with a summary of changed files. Download each patch by naming its repository: List the changes, then save each patch ``` const { data } = await sessions.artifacts(session.id) for (const change of data) { console.log(change.repo, (change.files ?? []).map((f) => `${f.status} ${f.file} +${f.additions} -${f.deletions}`)) const patch = await sessions.artifact(session.id, "patch", { repo: change.repo! }) await writeFile(`${change.repo!.split("/")[1]}.patch`, patch) } ``` | Field | Meaning | | --- | --- | | repo · base_commit | The repository, and the commit the patch applies to. | | files | Each changed file with `status` (`added`, `modified` or `deleted`) and line counts. | | size · final | Size in bytes; `final` is true once the session is deleted and the patch can't change. | Warning Size limit A patch can be up to 15 MB; larger ones fail with `patch_too_large`. Keep build output and generated files out of the change. Source: https://latentstack.dev/docs/agents/repositories --- # Files Give the agent files and take back what it makes. Every session has a disk of its own. You upload files to it, the agent works with them and leaves its results there, and you download what you need. Each call moves one file, named by its path in the workspace. ## The workspace ``` /work ← the agent's working directory ├── payments/ ← a repository, cloned into /work/ ├── uploads/ ← your files └── out/ ← what the agent leaves for you ``` - The session's disk holds 5 GiB and is mounted at `/work` in every sandbox the session runs in. - Each repository is cloned into `/work/`. See Repositories and patches. - Put your files in `uploads/`. The agent is told to leave what you ask for in `out/`. - A path in a file call is relative to `/work`: `uploads/photo.png`, `out/report.md`, `payments/README.md`. You don't need to explain this to the agent. When its sandbox starts, LatentStack writes a note into its instructions with this layout, how files move, what a pause keeps and what the network allows. Your own `instructions` come after the note and win where the two meet. ## Upload a file Upload a photo for the agent ``` import { readFile } from "node:fs/promises" const photo = await readFile("photo.png") const file = await sessions.uploadFile(session.id, "uploads/photo.png", photo, { contentType: "image/png" }) console.log(file.path, file.size, file.sha256) ``` - The file is stored at that path. Missing folders are created, and an existing file is replaced. - The answer is the stored file: `{ object: "agent.file", path, size, sha256 }`. - TypeScript takes a `Blob` or `File`, an `ArrayBuffer`, a typed array such as a Node.js `Buffer`, or a string. A string is the file's content, as UTF-8. - Python takes `bytes`, an open binary file, or a path. A `str` is the path of a file to read, not content. - One upload is at most 1 GiB. A larger file fails with `file_too_large`. ### Paths - Relative to the workspace, with forward slashes: `uploads/data/january.csv`. - No `.` or `..` segments, and no leading or trailing slash. The SDKs refuse these with `invalid_request` before sending anything. - `.git` and `.latentstack` can't be written, downloaded, listed or deleted. ## Show the agent an image Name workspace images in `files` when you send a message. The model sees them together with your text. Ask about an uploaded photo ``` await sessions.message(session.id, "Make a 3-second mp4 that zooms into this photo. Save it as out/zoom.mp4.", { files: ["uploads/photo.png"], }) ``` - PNG, JPEG, GIF or WebP only. Up to 10 images per message, 5 MiB each and 20 MiB in all. - Any other file, such as a CSV or a video, the agent reads at its path. Name the path in your message, not in `files`. ## List and download Download everything the agent left in out/ ``` import { writeFile } from "node:fs/promises" import { basename } from "node:path" const { data } = await sessions.listFiles(session.id, { prefix: "out/" }) for (const file of data) { const blob = await sessions.downloadFile(session.id, file.path) await writeFile(basename(file.path), Buffer.from(await blob.arrayBuffer())) } ``` - A listing is `{ object, data: [{ path, size, modified_at }], truncated }`, in path order. `.git` folders are left out. - `prefix` keeps only paths that start with it. `limit` is up to 1,000, the default. When `truncated` is true there were more files; narrow the prefix. - A download is the whole file: a `Blob` in TypeScript, `bytes` in Python. Its content type comes from the file's extension. ## Delete a file ``` await sessions.deleteFile(session.id, "uploads/photo.png") ``` A path with no file fails with `not_found`. You don't need to clean up before deleting a session: its disk goes with it, 7 days later. ## Limits, and paused sessions | Limit | Value | | --- | --- | | One upload | 1 GiB | | The session's disk | 5 GiB, for everything in the workspace | | Images on one message | 10, at most 5 MiB each and 20 MiB in all | | One listing | 1,000 files | ### Paused and starting sessions File calls are served by the session's sandbox. A paused session, or one that's still starting, has none to serve them, and file calls fail with `conflict`. Send a paused session a message to resume it, then try again once its status is `idle`, `running` or `waiting`. A message that names `files` can go to a paused session. It resumes the session and attaches the images once it runs. If an image is missing or too large by then, that message is dropped and the session's `error` says why. A new session that hasn't started yet refuses a message with `files` with `conflict`: there is nothing uploaded to attach. Note How long files last A pause keeps every file: they live on the session's disk, and the next sandbox mounts the same disk. Deleting a session keeps its disk for 7 days (a resume in that time brings it back), then deletes it; a session left paused for 4 months is stopped the same way. Download what you need before then, or name it in outputs when you create the session to keep a copy after it ends. See Manage sessions. ## Over HTTP | Request | Does | | --- | --- | | GET /v1/agents/sessions/{id}/files?prefix=&limit= | Lists files. | | PUT /v1/agents/sessions/{id}/files/{path} | Stores the request body at `path`. Needs a `Content-Length`. Answers 201 with the stored file. | | GET /v1/agents/sessions/{id}/files/{path} | Downloads the file. | | DELETE /v1/agents/sessions/{id}/files/{path} | Removes the file. Answers 204. | To attach images over HTTP, list their paths in the message input's `files`. Source: https://latentstack.dev/docs/agents/files --- # Outputs Name the files you want from a session, and download them with links that keep working after it ends. A session's files live on its own disk, which is deleted when the session ends. Outputs are the files you name when you create the session. LatentStack copies them out at the end of each run and keeps them after the session ends, with download links that need no API key. You can collect them later, or hand the links to someone else. ## Name your outputs Send a file in, name what comes out, and stop after the run ``` const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5" }, input: "Sort the names in uploads/names.txt and save them as out/sorted.txt.", files: { "uploads/names.txt": "Mira\nArjun\nZoe\nLena\n" }, // in the workspace before the first message outputs: ["out/*.txt"], // copied out when the run ends, and kept after the session end_after_run: true, // stop once the run has ended }) ``` `outputs`list of pathsoptional Up to 50 workspace paths, such as `out/report.pdf`. In a name, `*` matches any characters and `?` one character, within one folder: `out/*.json` is every JSON file directly in `out/`, not in the folders below it. `reports/*/summary.md` works too. `**` isn't supported. `files`objectoptional Files to put in the workspace before the first message runs: path to content. See Send files with create. `end_after_run`booleanoptionaldefault `false` Stop the session once its run has ended. See End after the run. Paths follow the same rules as file calls: relative to the workspace, no `..`, and nothing inside `.git`. The agent is already told to leave what you ask for in `out/`, so naming the file in your message is enough. ## When they're copied - At the end of every run, whether it completed or failed. The copy is made before the run's webhook is sent, so `run.completed` already lists the files with their links. - Once more when the session stops while its sandbox is still up: when you delete it, or after its run with `end_after_run`. A session stopped while paused has no sandbox to copy from, so the copies made before are what you get. - When it pauses with its sandbox up, including at a spend limit, where its run never reaches an end. The `session.paused` webhook then lists the files with their links. - A file that hasn't changed since its last copy (the same size and modification time) isn't copied again. - Each path keeps only its newest copy. ### When something is missing The run's `run.completed` or `run.failed` webhook says what this copy couldn't do: | Field | Meaning | | --- | --- | | outputs_missing | Patterns that matched no file this time. | | outputs_errors | Files or patterns that couldn't be copied, each with a `message`. | | outputs_truncated | A pattern looks through at most 1,000 files under its folder, subfolders included. `true` when a folder held more. | | outputs_error | The copy failed as a whole. The outputs already kept are still listed. | ## List and download Wait for the session to stop, then download its outputs ``` await sessions.wait(session.id, { until: ["stopped", "failed"] }) const listing = await sessions.outputs(session.id) for (const output of listing.data) { // The link needs no API key and works for 24 hours. const response = await fetch(output.url) await writeFile(basename(output.path), Buffer.from(await response.arrayBuffer())) console.log(output.path, output.size, "bytes") } ``` A listing is `{ object: "list", data, patterns }`: the outputs in path order, and the patterns the session asked for. JSON ``` { "id": "out_5e0a91c2d4b7e8f1a2c3d4e5", "object": "agent.output", "path": "out/sorted.txt", "size": 20, "sha256": "9f2c…", "content_type": "text/plain", "run_seq": 14, "captured_at": "2026-10-14T06:12:40.118000+00:00", "url": "https://latentstack.dev/v1/agents/outputs/out_5e0a91c2d4b7e8f1a2c3d4e5/content?token=…", "url_expires_at": "2026-10-15T06:13:02.540000+00:00" } ``` | Field | Meaning | | --- | --- | | path · size · sha256 · content_type | The file, as it was copied. | | run_seq | The event number of the run end (or the stop) that copied it. | | captured_at | When it was copied. | | url · url_expires_at | A download link, and when it stops working. | ### Links - A link downloads the file without an API key until `url_expires_at`: 24 hours after you list. List again for fresh links. - Links inside a `run.completed` or `run.failed` webhook last 4 days, longer than the webhook's retries. - A link always gives the newest copy of its path. - A browser saves the file rather than opening it. - An expired link, or one for a deleted output, answers 404. Warning Anyone with the link can download the file The link is the permission. Treat it like the file itself: don't log it, and share it only with people who may see the file. ## Keep and delete Outputs stay after the session stops or is deleted, until you delete them. List them with the session's id as before. The rest of the session's disk is still deleted when the session ends. Delete an output ``` await sessions.deleteOutput(session.id, output.id) ``` Its links stop working at once. If the session runs again, the next run's end copies the file again under a new id. ## Send files with create `files` on create puts files in the workspace before the first message runs, so `input` can use them at once. You don't have to wait for the sandbox and call uploadFile(). - It maps a workspace path to the file's content. In both SDKs a string is the file's text, stored as UTF-8, and bytes (`Uint8Array` in TypeScript) are its content. The SDK sends them as base64; over HTTP, send base64 yourself. - The files travel inside the create request, which is at most 50 MB in all (`request_too_large` otherwise). For larger files, create the session without `input`, upload them with `uploadFile()` once it is running (any size), then send the message. - If a file can't be put in place, the session fails with an `error` of type `files_error` that names the file. ## End after the run With `end_after_run: true`, the session stops as soon as a run ends. First its patch is saved, its outputs are copied and the run's webhook is sent. Then it stops with `stop_reason` `run_finished`. - Use it for one-off jobs, such as CI or a webhook that starts a task. Waiting for `stopped` or `failed`, as the example does, then tells you the work is done. - Such a session has nothing to come back to, so where another session would pause, it stops: when idle (`stop_reason` `idle_timeout`) or when its sandbox reaches its time limit (`hard_limit`). If it pauses anyway, at a spend limit for example, it waits 7 days for you to raise the limit and continue, then stops. See Pause and resume. - Schedules turn it on for their sessions unless you say otherwise. ## Over HTTP | Request | Does | | --- | --- | | GET /v1/agents/sessions/{id}/outputs | Lists the outputs, each with a fresh link. | | DELETE /v1/agents/sessions/{id}/outputs/{output_id} | Deletes one. Answers 204. | | GET | Downloads the file. No API key: the token in the link is the permission. | On `POST /v1/agents/sessions`, `files` is an object of path to base64 content, `outputs` a list of paths, and `end_after_run` a boolean. The session carries its `outputs` and `end_after_run` back. Note Turned on per deployment Your administrator turns outputs on for a deployment. Where they're off, `outputs` on create is refused with `invalid_request` and the outputs requests answer 404. Source: https://latentstack.dev/docs/agents/outputs --- # Webhooks Be told when something happens in a session, without holding the event stream open. A webhook is an HTTPS address on your server. When a session changes state, for example a run finishes or the agent asks for approval, LatentStack sends a signed `POST` to it. You don't keep a connection open, and your server can be down for a while: deliveries are retried for about three days, and every event is kept in a log you can read back. Webhooks carry changes of state. The agent's live output, its text and tool calls, stays on the event stream. ## Two ways to set one up | | Registered endpoint | On one session | | --- | --- | --- | | Made with | `webhooks.create()` | The `webhook` field when you create a session | | Hears | Every session you create in the organization, and your schedules' skipped runs | That session only | | Secret | Made for you, shown once | Yours, or made for you and shown once | | Lasts | Until you delete it | 7 days after the session ends | | How many | 10 per person in each organization, unless your administrator set another number | Not counted | A schedule can have a webhook of its own, which hears every session it starts. See Schedules. ## Register an endpoint Hear about finished runs and approvals for all your sessions ``` const endpoint = await client.agents.webhooks.create({ url: "https://example.com/hooks/latentstack", events: ["run.completed", "run.failed", "approval.requested"], description: "Production", }) console.log(endpoint.id, endpoint.secret) // the secret is shown only now: store it ``` `url`stringrequired HTTPS on port 443, to a public host. At most 2,048 characters. It is checked now, and a URL that can't be delivered to is refused with the reason. See Where deliveries can go. `events`listrequired What to send: exact types such as `run.completed`, a family such as `run.*` or `session.*`, or `*` for everything. Up to 50 entries. `description`stringoptional A note for yourself, up to 500 characters. `enabled`booleanoptionaldefault `true` Off means nothing is sent to it. - The answer is the endpoint with its `secret` (`whsec_…`). It is shown only in this answer. Keep it with your receiver's settings. - The endpoint hears the sessions you create in the organization you're working in. Other people in the organization have their own. - Past the limit, create fails with `endpoint_limit_reached`. Delete one first. - Change `url`, `events`, `description` or `enabled` later with `webhooks.update()`. The other fields keep their values. - Deleting an endpoint marks the deliveries still waiting for it as failed. ## A webhook for one session Pass `webhook` when you create a session to hear about that session alone. This suits a job runner that starts one session per task and wants a callback to the task's own URL. ``` const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5" }, input: "Fix the failing test in packages/core.", webhook: { url: "https://example.com/hooks/tasks/42", events: ["run.*", "session.stopped"] }, }) console.log(session.webhook?.secret) // made for you, shown only now ``` - `events` defaults to `["*"]`. - The create answer has a `webhook` field: the endpoint, with `session_id` set. It has a `secret` only when LatentStack made one, and only in this answer. - Or bring your own `secret`, so one receiver can verify every session with the same key. It is `whsec_` followed by the base64 of 24 to 64 random bytes. - It isn't listed with your registered endpoints and doesn't count toward their limit. Read, update, test and rotate it by its id like any other endpoint. - Your registered endpoints hear the session too, for the types they subscribe to. - It is removed 7 days after the session stops or fails, which is longer than the retries of its last events. ``` echo "whsec_$(openssl rand -base64 32)" ``` Note With an idempotency key, bring your own secret A create repeated with the same idempotency key returns the first session without its `webhook`, so a secret made for you would be lost if the first answer never arrived. Pass your own `secret` when you also pass an idempotency key. ## Events | type | Sent when | data | | --- | --- | --- | | session.ready | A sandbox is ready: when the session starts, and each time it resumes. | `instance_number`, `instance_context` | | session.paused | The session paused: you paused it, it was idle, it reached a spend limit, its sandbox reached its time limit, or its sandbox was lost. | `reason`: `requested`, `idle_timeout`, the spend limit (`max_turns`, `max_tokens`, `max_cost_usd`), `hard_limit`, or why the sandbox was lost. With `error` when the sandbox was lost or a resume couldn't restore it. For a session made with `outputs`: `outputs`, copied as it paused. | | session.stopped | The session ended for good. | `stop_reason` | | session.failed | The session couldn't start, or failed for good. | `error` | | run.started | The agent picked up a message. | `seq` | | run.completed | A run finished, or you cancelled it. Sent after its patch and outputs are saved. | `seq`, `last_message`, `patches`, and `outputs` for a session with outputs | | run.failed | A run stopped on an error. The session is still usable. | `seq`, `error`, `patches`, and `outputs` | | approval.requested | The agent is waiting for your permission. See Approvals. | `request_id`, `action`, `resources`, `metadata` | | question.requested | The agent asked you a question. | `request_id`, `questions` | | limit.warning | 80% of a spend cap is used. Once per cap. | `limit`, `max`, `spent` | | limit.reached | A spend cap was reached. The agent wraps up, then the session pauses until the cap is raised. | `limit`, `max`, `spent` | | artifact.ready | A patch with changes was saved at the end of a run or when the session stopped. Sent once per patch: the same changes are not reported twice. See Repositories and patches. | The patch's record (`repo`, `version`, `size`, `files`, …), without its content | | schedule.skipped | A schedule's time came and no session was started. See Schedules. | `schedule_id`, `due_at`, `trigger`, `reason`, `message` | | webhook.test | You asked for a test. Sent whatever the endpoint subscribes to. | `endpoint_id`, `message` | In `events`, a family is the part before the dot: `session.*`, `run.*`, `approval.*`, `question.*`, `limit.*`, `artifact.*` or `schedule.*`. New event types can appear over time. Answer 2xx to any you don't recognise. ### run.completed | Field | Meaning | | --- | --- | | seq | The number of the run's last event on the session's event stream. | | last_message | The agent's last reply. Cut to 8 KB, with `last_message_truncated: true`. `null` when there is none. | | patches | One per repository: `repo`, `version`, `size`, `files_changed`, `final`. Download the patch with `artifact()`. | | outputs | Only for a session made with `outputs`: every output as it now stands, with links that work for 4 days. See Outputs. | | outputs_missing | Patterns that matched no file this time. | ## The envelope Every delivery is one event, as JSON: JSON ``` { "id": "evt_5b1f0c9e2a7d4e8f9a0b1c2d", "object": "event", "type": "run.completed", "api_version": "v1", "created_at": "2026-10-14T04:01:12.381000+00:00", "sequence": 6, "session": { "id": "ags_4843742656c9cbc90685c6d2", "status": "idle", "metadata": { "customer": "cus_123" }, "stop_reason": null, "error": null, "limits": { "max_turns": null, "max_tokens": null, "max_cost_usd": 2.0, "spent": { … } }, "instance_number": 1, "last_seq": 41, "schedule_id": null }, "data": { "seq": 41, "last_message": "Done. The names are sorted in out/sorted.txt.", "patches": [] } } ``` | Field | Meaning | | --- | --- | | id | The event's id. The same on every retry, and sent as the `webhook-id` header. Dedupe on it. | | type · api_version | The event type, and `v1`. | | created_at | When the event happened. | | sequence | Counts up with each event about the same session. Order by it. `null` for `schedule.skipped` and `webhook.test`. | | session | The session as it was when the event happened: `id`, `status`, `metadata`, `stop_reason`, `error`, `limits`, `instance_number`, `last_seq` and `schedule_id`. `null` for `schedule.skipped` and `webhook.test`. | | data | Depends on the type; see Events. | A body is at most 256 KB. If an event would be larger, `session.metadata` is replaced by `{ "omitted": true, "reason": "…" }`, and if that isn't enough, so is `data`. Read the session for the full picture. In `artifact.ready`, a list of more than 200 files is cut short with `files_truncated: true`. ## Verify the signature Anyone can send a `POST` to your URL, so check that a delivery came from LatentStack before you act on it. Each one is signed with the endpoint's secret. `verifyWebhook` (TypeScript) and `verify_webhook` (Python) check the signature and the time it was sent, and return the event. When a check fails they throw `WebhookVerificationError`. A receiver that verifies, answers at once, then does the work ``` import { createServer } from "node:http" import { verifyWebhook } from "@latentcode/sandbox-agents" const secret = process.env.LS_WEBHOOK_SECRET! // whsec_…, shown when you made the endpoint const seen = new Set() // event ids already handled; keep them in your database in production createServer(async (req, res) => { // The raw body: the signature is over the exact bytes that were sent. const chunks: Buffer[] = [] for await (const chunk of req) chunks.push(chunk) let event try { event = await verifyWebhook(Buffer.concat(chunks), req.headers, secret) } catch { res.writeHead(400).end() return } res.writeHead(200).end() // answer first, then do the work if (seen.has(event.id)) return // a retry carries the same id seen.add(event.id) if (event.type === "run.completed") console.log(event.session?.id, event.data?.last_message) }).listen(8000) ``` - Pass the body exactly as it arrived, as bytes or a string. A body parsed as JSON and turned back into text won't match the signature. - A delivery sent more than 5 minutes from your server's clock is refused, so an old delivery can't be replayed. Change it with `toleranceSeconds` (TypeScript) or `tolerance_seconds` (Python), in seconds. - Neither helper makes a network call. In Python, `verify_webhook` is a plain function, so it works the same next to the async client. - Run the Python receiver with `uvicorn receiver:app --port 8000`, and the TypeScript one with `npx tsx receiver.ts`. Both read the secret from `LS_WEBHOOK_SECRET`. ``` POST /hooks/latentstack HTTP/1.1 content-type: application/json user-agent: latentstack-webhooks/1 webhook-id: evt_5b1f0c9e2a7d4e8f9a0b1c2d webhook-timestamp: 1791950472 webhook-signature: v1,0eV36p6rL+HHnw+Z+xt0vUONglojAeIaGO0deTCGYn0= {"id":"evt_5b1f0c9e2a7d4e8f9a0b1c2d","object":"event","type":"run.completed",…} ``` ### In other languages Signatures follow the Standard Webhooks scheme, so any Standard Webhooks library can verify them. To do it yourself: - 01Check the time.Read `webhook-timestamp` (Unix seconds). Refuse the delivery if it is more than 5 minutes from now. - 02Build the signed text.Join `webhook-id`, `webhook-timestamp` and the raw body with dots: `{id}.{timestamp}.{body}`. - 03Make the key.Remove `whsec_` from the start of the secret and base64-decode the rest. - 04Sign.Compute the HMAC-SHA256 of the signed text with the key, and base64-encode it. - 05Compare.`webhook-signature` holds one or more entries such as `v1,`, separated by spaces. Accept the delivery if any entry matches yours. Compare in constant time. ## Answer fast, then do the work - Answer with any 2xx status within 15 seconds. Anything else counts as a failure and is retried: another status, no answer in time, or a redirect (redirects aren't followed). - Answer first and do the work afterwards: put the event on a queue, or in a background task as the example does. A handler that takes too long is retried even though it worked. - Answer 2xx to events you don't handle too, so they aren't retried. - Answer `410 Gone` to turn the endpoint off. ## Retries A delivery that fails is tried again after 5 seconds, 30 seconds, 2, 5, 15 and 30 minutes, 1, 2 and 4 hours, then every 8 hours: 18 attempts over about three days. Each wait varies by up to a fifth, so retries from many sessions don't all arrive together. After the last attempt the delivery is `failed`. The event stays in the event log. ### When an endpoint is turned off - When it answers `410`, or when every delivery to it has failed for three days (at least 10 attempts in a row). - Its `enabled` becomes `false` and `disabled_reason` says why: `gone` or `failing`. Deliveries waiting for it are marked failed. - LatentStack tells you with a notification and an email. - Fix the receiver, then turn the endpoint back on with `webhooks.update()` and `enabled: true`. Events from while it was off aren't sent again on their own: catch up from the log, or retry the deliveries you need. `last_success_at`, `last_failure_at`, `failing_since` and `failure_count` (failed attempts since the last success) on the endpoint show how it is doing, and `disabled_at` when it was turned off. Up to 1,000 deliveries can wait for one endpoint. Past that, new events are still logged but not queued for it. ## Order and duplicates - Each event is delivered at least once. A retry, or an answer that was lost on the way back, can bring the same event twice. Dedupe on `id`. - Events don't always arrive in order: a retried event can arrive after a later one. Within a session, order by `sequence`. Numbers can skip, so don't expect each one to be the last plus one. - `session` is a snapshot from when the event happened. For the current state, read the session. ## Where deliveries can go - HTTPS on port 443 only. - The host must resolve only to public internet addresses: no `localhost` and no private networks. - No user name or password in the URL. The host is a plain ASCII name without a trailing dot; write an international domain in its `xn--` form. - The URL is checked when you set it, and again before every attempt. To try a receiver on your own machine, expose it through an HTTPS tunnel that gives it a public address on port 443. ## Delivery logs Every attempt is recorded. Read what was sent to one endpoint, or what was sent about one session to every endpoint that heard it. Both are newest first and kept for 30 days. Find failed deliveries ``` const { data } = await client.agents.webhooks.deliveries(endpoint.id, { status: "failed" }) for (const d of data) console.log(d.event_type, d.attempts, d.last_attempt?.status_code, d.last_attempt?.error) // What was sent about one session, to every endpoint const sent = await sessions.webhookDeliveries(session.id) ``` | Field | Meaning | | --- | --- | | id · event_id · event_type | The delivery (`whd_…`), and the event it carries. | | endpoint_id · session_id | Where it went, and the session it is about (`null` for a test or a skipped schedule). | | status | `pending` until a 2xx (`succeeded`), or `failed`: the retries ran out, the endpoint answered 410, or it was turned off or deleted. | | attempts · max_attempts · next_attempt_at | How many attempts so far, how many it gets (18, or 3 for a test event), and when the next one is due while pending. | | last_attempt | `at`, `status_code` (`null` when no answer came), `latency_ms`, `response` (the first 512 bytes of your answer) and `error`. | ## Test, rotate and retry ``` const webhooks = client.agents.webhooks // Send a webhook.test event now const delivery = await webhooks.test(endpoint.id) // Make a new secret. The old one keeps working for 24 hours. const { secret } = await webhooks.rotateSecret(endpoint.id) // Send a delivery again now, e.g. a failed one from the delivery log await webhooks.retryDelivery(endpoint.id, deliveryId) ``` ### Test A test sends a `webhook.test` event to that endpoint, whatever it subscribes to. The answer is the delivery; read it again from the delivery log to see how it went. A test is tried 3 times at most. Test events have no session and aren't in the event log. ### Rotate the secret Rotating makes a new secret and shows it once. For the next 24 hours, each delivery carries two signatures, one for each secret, so a receiver that knows either one accepts it. Give your receiver the new secret within that time. ### Retry A retry puts a delivery back in the queue for an attempt right away, whatever its status. It fails with `conflict` while that delivery is being attempted. Tests and retries need the endpoint to be on; otherwise they fail with `endpoint_disabled`. Together they are limited to 60 a minute per person (`rate_limited`). A test fails with `endpoint_backlogged` when 1,000 deliveries are already waiting for the endpoint. ## Catch up from the event log Every event is also kept in a log for 30 days, whether or not an endpoint received it. After your receiver was down, or turned off, read the log from the last event you handled. Handle everything since the last event you saw ``` let after = lastHandledId // the id of the last event you handled, from your database while (true) { const page = await client.agents.events.list({ after, limit: 100 }) for (const event of page.data) await handle(event) // the same handler, deduping on id if (!page.has_more) break after = page.next_after! } ``` - Events come oldest first, with the same body a delivery has, for your sessions and schedules in the organization you're working in. - Filter with `types` (a comma-separated list; families and `*` work) and `session_id`. - An event appears in the log a few seconds after it happens. Test events aren't listed. - `after` must be an event still in the log. If your last id is more than 30 days old, start again without it. ## Over HTTP | Request | Does | | --- | --- | | POST /v1/agents/webhooks | Registers an endpoint. Answers 201 with its `secret`. | | GET /v1/agents/webhooks?limit=&after= | Lists your registered endpoints, newest first. | | GET /v1/agents/webhooks/{id} | Reads one endpoint, registered or given with a session or schedule. | | PATCH /v1/agents/webhooks/{id} | Changes `url`, `events`, `description` or `enabled`. | | DELETE /v1/agents/webhooks/{id} | Deletes it. Answers 204. | | POST /v1/agents/webhooks/{id}/rotate | Makes a new secret. Answers with the endpoint and its new `secret`. | | POST /v1/agents/webhooks/{id}/test | Sends a test event. Answers 202 with the delivery. | | GET /v1/agents/webhooks/{id}/deliveries?status=&limit=&after= | What was sent to it. `status` is `pending`, `succeeded` or `failed`. | | GET /v1/agents/webhooks/{id}/deliveries/{delivery_id} | One delivery, with every attempt made at it (`attempt_log`) and the `event` it carries. | | POST /v1/agents/webhooks/{id}/deliveries/{delivery_id}/retry | Sends a delivery again now. Answers 202. | | GET /v1/agents/sessions/{id}/webhooks?limit=&after= | What was sent about one session. | | GET /v1/agents/events?types=&session_id=&order=&after=&limit= | The event log, oldest first. With `order=newest` it reads back from now, and `after` pages to older events. | Lists hold 20 items by default (the event log 50), and up to 100. When `has_more` is true, pass `next_after` as `after` for the next page. Note Turned on per deployment Your administrator turns webhooks on for a deployment. Where they're off, these requests answer 404 and a `webhook` on create is refused with `invalid_request`. Source: https://latentstack.dev/docs/agents/webhooks --- # Schedules Start a session at set times, such as every weekday at 9:30, and get its results without being there. A schedule is the body of a session create plus a time, written as a cron expression. At each time, LatentStack starts an ordinary session from it, as you. Everything a session does works the same way: limits, network, files, outputs, patches, usage and webhooks. ## Create a schedule A standup video at 9:30 India time, Monday to Friday ``` const schedule = await client.agents.schedules.create({ name: "standup video", cron: "30 9 * * 1-5", // 9:30, Monday to Friday timezone: "Asia/Kolkata", session: { agent: { model: "anthropic/claude-sonnet-5.5" }, environment: { type: "repos", repos: ["acme/demo"] }, input: "Make a 30-second video for today's standup that sums up the commits of the last day. " + "Save it as out/standup.mp4.", limits: { max_cost_usd: 2 }, }, outputs: ["out/standup.mp4"], webhook: { url: "https://example.com/hooks/latentstack", events: ["run.completed", "run.failed", "session.failed", "schedule.skipped"], }, }) console.log(schedule.id, "next run:", schedule.next_run_at) console.log("webhook secret:", schedule.webhook?.secret) // shown only now: give it to your receiver ``` Each weekday at 9:30 in India, a session clones `acme/demo`, makes the video and stops. The video is kept as an output, and the webhook's `run.completed` carries a link to download it. `cron`stringrequired Five fields: minute, hour, day of month, month, day of week. `30 9 * * 1-5` is 9:30, Monday to Friday. Read in `timezone`. `timezone`stringoptionaldefault `UTC` An IANA time zone name, such as `Asia/Kolkata` or `Europe/London`. `session`objectrequired What you would pass to create a session: `agent`, `environment`, `input`, `limits`, `metadata`, `files`, `outputs`, `end_after_run`. Not `webhook`: that goes on the schedule. `outputs`list of pathsoptional The same as `session.outputs`, and returned at the top of the schedule too. Given in both places, this one wins. `webhook`objectoptional `{ url, events?, secret? }`. Hears every run. See Webhook. `name`stringoptional For yourself, up to 200 characters. `concurrency`"skip" | "allow"optionaldefault `skip` What to do when a time comes while the last run is still going. See Concurrency. `enabled`booleanoptionaldefault `true` Off means no runs until you turn it on. See Pause, change and delete. - The session settings are checked when you save the schedule, as a create would check them: the model on your tier, the permission rules, and GitHub access to the repositories. A mistake fails now, not at 9:30. - The answer is the schedule, with `next_run_at`, the next time it will run, in UTC. - A schedule is yours alone, in the organization you made it in, like a session. ## Each run - At each time, LatentStack creates a session from `session`, as the person who made the schedule. Your API key, your membership of the organization and your tier are checked again first. - The session's `schedule_id` says which schedule started it. So does the `session` block on its webhook events. - It ends after its run: `end_after_run` is `true` unless `session` says `false`. Its patch is saved, its outputs copied and its webhook sent, then it stops. See End after the run. - One time starts one session, even if LatentStack restarts while starting it. - Its usage counts like that of any session you create, against your tier. ### Files Put `files` in `session`. They are kept with the schedule and put in each run's workspace before its first message. The schedule lists them as `files: [{ path, size }]`, without their content. ### Outputs Each run's outputs belong to its own session. Get them from the `run.completed` webhook, or list them with the session id from the run ledger. ### Webhook - `webhook` on the schedule hears every session the schedule starts, and the schedule's `schedule.skipped` events. `events` defaults to `["*"]`. - Its `secret` is in the answer that made it, and only there, unless you passed your own. - Your registered endpoints hear the runs too. ## When a run is skipped A time that doesn't start a session is recorded as skipped in the run ledger, and a `schedule.skipped` event is sent. The schedule stays on, and the next time runs as usual. | reason | Why | | --- | --- | | missed | LatentStack wasn't running at that time and came back more than an hour later. That time is skipped, not run late, and the schedule carries on from the next time to come. Back within the hour, it runs late, once. | | previous_running | `concurrency` is `skip`, and the last run's session is still starting, running or waiting for an approval. | | unavailable | A session couldn't be started for a whole hour: no capacity, your organization at its session limit, or GitHub out of reach. Until then the same time is tried again every minute. | | key_revoked · key_expired | The API key you made the schedule with has been revoked or has expired. | | not_a_member · user_not_found | You are no longer a member of the organization, or your account is gone. | | project_access_denied | You are no longer in the team your tier came from. | | model_not_allowed · no_tier_assigned | The model is no longer on your tier, or you have no tier in the organization. | | another error type | The create failed, for example `repo_not_accessible`. `message` says why. | JSON ``` { "id": "evt_8c27d1e04b9a6f3e5d2c1b0a", "object": "event", "type": "schedule.skipped", "api_version": "v1", "created_at": "2026-10-15T04:00:04.212000+00:00", "sequence": null, "session": null, "data": { "schedule_id": "sch_1a2b3c4d5e6f7a8b9c0d1e2f", "due_at": "2026-10-15T04:00:00+00:00", "trigger": "clock", "reason": "previous_running", "message": "The previous run (ags_4843742656c9cbc90685c6d2) was still going." } } ``` Warning A schedule keeps the key it was made with Every run checks the API key you used to create the schedule. If you revoke that key, each run is skipped with `key_revoked`. Create the schedule again with your new key, and delete the old one. ## Concurrency | concurrency | When a time comes while the last run is still going | | --- | --- | | skip | The default. The time is skipped with `previous_running`. | | allow | Another session starts anyway. | A run is still going while its session is starting, running or waiting for an approval. A session that is idle, paused or stopped doesn't hold the next run back. ## The run ledger Each run gets one row, and so does each skipped time. Rows are newest first. What came of the last ten times ``` const { data } = await client.agents.schedules.runs(schedule.id, { limit: 10 }) for (const run of data) console.log(run.due_at, run.outcome, run.reason ?? run.session_id, run.cost_usd) ``` | Field | Meaning | | --- | --- | | due_at | The time it was for. For a run you started by hand, when you asked. | | trigger | `clock`, or `manual` for a run you started with `run()`. | | session_id | The session it started, or `null` when skipped. | | outcome | `started` while the session works on its run, then `completed`, `failed`, or `stopped` when the session stopped before its run ended (for example at a spend limit). `skipped` when no session was started. | | reason · message | Why it was skipped. See When a run is skipped. | | error · stop_reason | Why the run failed, or why its session stopped. | | cost_usd | What the session had spent when its run ended. | | started_at · ended_at | When the session was started, and when the run ended or was skipped. | The schedule's own `last_run_at`, `last_session_id` and `last_outcome` sum up the latest run. ## Run now ``` const run = await client.agents.schedules.run(schedule.id) console.log(run.session_id) ``` - Starts a session right away, outside the timetable. The next booked time doesn't change. - The answer is the ledger row, with `trigger: "manual"` and the new `session_id`. - It starts even while the last run is still going: `concurrency` applies to the timetable's runs only. - When a session can't be started right now (no capacity, or your organization at its session limit), it fails with `runner_unavailable` and the message says why. Try again shortly. - Any other reason a run would be skipped is returned as the error, such as `key_revoked`. ## Pause, change and delete ``` const schedules = client.agents.schedules await schedules.update(schedule.id, { enabled: false }) // pause await schedules.update(schedule.id, { enabled: true, cron: "0 10 * * 1-5" }) // resume, at 10:00 from now on await schedules.delete(schedule.id) ``` - Pause with `enabled: false`. `next_run_at` becomes `null`. Turned on again, the next time counts from now: times that passed while it was paused don't run. - Change any field; the others keep their values. A new `cron` or `timezone` books the next time from now. A new `session` replaces the settings and their files, and is checked again. Its `outputs` stay unless the new `session` has its own; `outputs: null` removes them. - A `webhook` with the same `url` and no `secret` keeps the endpoint and its secret, and turns it back on if it was off. A new `url` replaces the old endpoint, whose waiting deliveries are marked failed. `webhook: null` (`webhook=None` in Python) removes it. - Delete stops all further runs. Sessions it already started keep going, and its webhook stays for 7 days so they can still report. ## Over HTTP | Request | Does | | --- | --- | | POST /v1/agents/schedules | Creates a schedule. Answers 201, with the webhook's `secret` when one was made. | | GET /v1/agents/schedules?limit=&after=&runs= | Lists your schedules, newest first. With `runs` (up to 30), each one comes with its newest runs as `recent_runs`. | | GET /v1/agents/schedules/preview?cron=&timezone=&count= | The next times a cron runs in a time zone (3 by default, up to 10), checked as a create checks it. A cron it won't take answers 400 with the reason. | | GET /v1/agents/schedules/{id} | Reads one. | | PATCH /v1/agents/schedules/{id} | Changes the fields you send. | | DELETE /v1/agents/schedules/{id} | Deletes it. Answers 204. | | POST /v1/agents/schedules/{id}/run | Starts a run now. Answers 201 with the ledger row. | | GET /v1/agents/schedules/{id}/runs?limit=&after= | The run ledger, newest first. | On `POST`, `session.files` is an object of path to base64 content, as on session create. Lists hold 20 items by default and up to 100; pass `next_after` as `after` for the next page. Note Turned on per deployment Your administrator turns schedules on for a deployment. Where they're off, these requests answer 404. Source: https://latentstack.dev/docs/agents/schedules --- # TypeScript SDK @latentcode/sandbox-agents 0.1.4: a typed client for hosted agent sessions. It has no runtime dependencies and runs anywhere fetch does. ## Install The package is distributed by LatentStack rather than npm. Installing from the URL records it in `package.json`: ``` npm install https://latentstack.dev/dl/latentcode-sandbox-agents-0.1.4.tgz ``` `bun add`, `pnpm add` and `yarn add` take the same URL. To pin a copy, download the tarball and install the file (`npm install ./latentcode-sandbox-agents-0.1.4.tgz`). | Runtime | Supported | | --- | --- | | Node.js | 22 or newer | | Bun · Deno | Yes | | Browsers | Technically yes, but never ship an `ls-` key to a browser. Call from your server. | ## Create a client TypeScript ``` import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions ``` ``` new LatentStack(options: LatentStackOptions) ``` | Option | Type | | | --- | --- | --- | | apiKey | string | Required. Your `ls-…` key. | | baseUrl | string | Your LatentStack URL, if it isn't `https://latentstack.dev`. | | fetch | typeof fetch | Your own fetch, for proxies, tracing or tests. | ## client.agents.sessions ### Lifecycle ``` create(params: CreateSessionParams): Promise ``` Starts a session. `params` holds the session settings (`agent`, `environment`, `limits`, `input`, `metadata`) and an optional `idempotencyKey` that makes the call safe to retry. `environment.network` sets what the sandbox can reach; `limits` caps what the session may spend. `files`, `outputs` and `end_after_run` are on Outputs, and `webhook` on Webhooks. returns`Session` ``` get(sessionId: string): Promise ``` Reads a session, with `limits`, `stop_reason` and `usage`. returns`Session` ``` list(params?: { limit?: number; after?: string }): Promise ``` Your sessions, newest first. Pass `next_after` as `after` for the next page. returns`{ data, has_more, next_after }` ``` delete(sessionId: string): Promise ``` Stops the session for good and deletes its disk. Its events and patches stay readable. returns`Session (stopping or stopped)` ``` pause(sessionId: string): Promise ``` Saves its state and releases the sandbox. returns`Session (pausing)` ``` resume(sessionId: string): Promise ``` Continues a paused session in a new sandbox. `message()` does this on its own. Also brings back a stopped session while its disk is kept (`volume_kept_until`). returns`Session (provisioning)` ``` fork(sessionId: string, params?): Promise ``` A new session from an idle one as it is now: its repositories, its changes and its conversation. Takes `input`, `metadata`, `limits`, `outputs`, `end_after_run`, `webhook` and `idempotencyKey`. See Fork a session. returns`Session (provisioning)` ``` update(sessionId: string, { limits }): Promise ``` Changes its spend limits. A session paused at a limit continues once the limit is raised; `null`removes one. returns`Session` ### Input ``` message(sessionId: string, text: string, options?: { delivery?: "steer" | "queue"; files?: string[] }): Promise ``` Sends a message. `steer` (default) folds into the current run; `queue` runs after it. `files` names workspace images (png, jpeg, gif or webp) to put in front of the model with the text. returns`{ accepted, queued?, resumed? }` ``` approve(sessionId: string, requestId: string, reply: "once" | "always" | "reject", message?: string): Promise ``` Answers an `approval.requested` frame. ``` cancel(sessionId: string): Promise ``` Interrupts the current run. The session stays open. ``` send(sessionId: string, input: SessionInput): Promise ``` Any of the above as a typed object, e.g. `{ type: "message", text, delivery }`. ### Following ``` events(sessionId: string, options?: EventsOptions): AsyncGenerator ``` The session's frames, live. It reconnects with `after=` when the connection drops and ends when the session is `stopped` or `failed`. It throws a `LatentStackError` if the session can't be read (e.g. `not_found`) or the stream keeps closing (5 attempts in a row). | Option | Type | | | --- | --- | --- | | after | number | Start after this seq, e.g. a stored `session.last_seq`. Default: from the beginning. | | signal | AbortSignal | Ends the loop when aborted. | | retryDelayMs | number | Fixed wait between reconnects. Default: 1 s, 2 s, 3 s … per failed attempt. | ``` wait(sessionId: string, options?: { until?: SessionStatusName[]; timeoutMs?: number; pollMs?: number }): Promise ``` Polls until the status is in `until` (default `SETTLED`: idle, waiting, paused, stopped, failed). `timeoutMs` defaults to 10 minutes and `pollMs` to 2 seconds. On timeout it throws `LatentStackError` with type `timeout`. Right after `create()` a session is briefly `idle` before its first message starts, so follow `events()` to know a task is done. returns`Session` ### Artifacts ``` artifacts(sessionId: string): Promise ``` One record per repository, with a per-file summary. returns`{ data: Artifact[] }` ``` artifact(sessionId: string, name = "patch", options?: { repo?: string }): Promise ``` The patch as text. Pass `repo` when the session has several repositories. returns`string (unified diff)` ### Files Paths are relative to the workspace, like `uploads/photo.png`. A path with a `.` or `..` segment, or a leading or trailing slash, throws `invalid_request` before anything is sent. See Files. ``` uploadFile(sessionId: string, path: string, data: Blob | ArrayBuffer | ArrayBufferView | string, options?: { contentType?: string }): Promise ``` Stores `data` at `path`. Missing folders are created, and an existing file is replaced. A string is the file's content, as UTF-8. `contentType` defaults to the Blob's own type, else `application/octet-stream`. returns`{ object, path, size, sha256 }` ``` downloadFile(sessionId: string, path: string): Promise ``` The whole file. The Blob's `type` comes from the file's extension. returns`Blob` ``` listFiles(sessionId: string, params?: { prefix?: string; limit?: number }): Promise ``` Files whose path starts with `prefix`, in path order, up to `limit` (1,000 at most). `.git` is left out. `truncated` is true when there were more. returns`{ object, data: [{ path, size, modified_at }], truncated }` ``` deleteFile(sessionId: string, path: string): Promise ``` Removes the file. ## Working with frames `StreamFrame` is a union of `SessionStatus`, `ApprovalRequested` and `Event`. A durable event's `type` is an open string, so narrow on `"seq" in frame` first. `data` may be missing; read it with `?.`. TypeScript ``` for await (const frame of sessions.events(id)) { if ("seq" in frame) { // Event: { seq, type, data: Record, time } if (frame.type === "text.ended") console.log(frame.data?.text) if (frame.type === "run.completed") break } else if (frame.type === "session.status") { // SessionStatus: status, error, instance_number, pending_approvals } else if (frame.type === "approval.requested") { // ApprovalRequested: request_id, action, resources, metadata await sessions.approve(id, frame.request_id, "once") } } ``` ## Errors Every failed call throws `LatentStackError`, with `status` (0 if no response arrived), `type` and `message`. See Errors for the list of types. TypeScript ``` import { LatentStackError } from "@latentcode/sandbox-agents" try { await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5" }, input: "hi" }) } catch (e) { if (e instanceof LatentStackError && e.type === "model_not_allowed") { /* pick another model */ } else throw e } ``` ## Exports | Export | What | | --- | --- | | LatentStack | The client. | | Sessions | The class behind `client.agents.sessions`. | | Webhooks · Events · Schedules | The classes behind `client.agents.webhooks`, `client.agents.events` and `client.agents.schedules`. | | LatentStackError | The error class. | | verifyWebhook · WebhookVerificationError | Checks a webhook delivery and returns its event, or throws. See Verify the signature. | | SETTLED | `["idle", "waiting", "paused", "stopped", "failed"]` | | DEFAULT_BASE_URL | `https://latentstack.dev` | | types | Session, SessionList, SessionStatusName, Agent, Rule, Event, StreamFrame, SessionStatus, ApprovalRequested, PendingApproval, InputAccepted, SessionInput, Artifact, ArtifactList, FileChange, FileInfo, FileList, FileData, ApiError, CreateSessionParams, ListSessionsParams, MessageOptions, ListFilesParams, UploadFileOptions, WaitOptions, EventsOptions, LatentStackOptions, Output, OutputList, WebhookEndpoint, WebhookEndpointList, WebhookDelivery, WebhookDeliveryList, WebhookAttempt, WebhookEvent, EventList, EventSession, Schedule, ScheduleList, ScheduleRun, ScheduleRunList, StagedFile, PageParams, CreateWebhookParams, UpdateWebhookParams, ListWebhookDeliveriesParams, ListEventsParams, ScheduleSession, CreateScheduleParams, UpdateScheduleParams, WebhookHeaders, VerifyWebhookOptions | ## Upgrading - Each new version has its own install URL; see Install above. Update the URL in `package.json` and reinstall. - `0.1.1` added several repositories per session and the `repo` option on `artifact()`. - `0.1.2` added `limits` and `environment.network` on `create()`, and `limits`, `usage` and `stop_reason` on the session. - `0.1.3` added `uploadFile()`, `downloadFile()`, `listFiles()`, `deleteFile()` and the `files` option on `message()`. - `0.1.4` added `client.agents.webhooks`, `client.agents.events` and `client.agents.schedules`; `outputs()`, `deleteOutput()` and `webhookDeliveries()` on sessions; `files`, `outputs`, `end_after_run` and `webhook` on `create()`; and `verifyWebhook()` with `WebhookVerificationError`; and `update()` to raise a session's limits. A spend limit now pauses a session instead of stopping it, and `resume()` brings back a stopped one for 7 days. See Webhooks, Outputs and Schedules. Source: https://latentstack.dev/docs/agents/sdk-typescript --- # Python SDK latentcode_sandbox_agents 0.1.4: the same client as the TypeScript one, in sync and asyncio variants. Python 3.10+, one dependency (httpx). ## Install ``` pip install https://latentstack.dev/dl/latentcode_sandbox_agents-0.1.4-py3-none-any.whl ``` Works with `uv pip install` and `poetry add` too. In `requirements.txt`, list the URL on its own line. To pin a copy, download the wheel and install the file. ## Create a client Python ``` import os from latentcode_sandbox_agents import LatentStack client = LatentStack(api_key=os.environ["LS_API_KEY"]) sessions = client.agents.sessions # ... and when you're done (or use "with LatentStack(...) as client:") client.close() ``` ``` LatentStack(api_key: str, *, base_url: str | None = None, transport: httpx.BaseTransport | None = None, timeout: float | httpx.Timeout | None = 60.0) ``` | Argument | | | --- | --- | | api_key | Required. Your `ls-…` key. | | base_url | Your LatentStack URL, if it isn't `https://latentstack.dev`. | | transport | Your own httpx transport, for proxies or tests. | | timeout | Per-request timeout in seconds. The event stream is not bounded by it. | ## asyncio `AsyncLatentStack` takes the same arguments. Its methods are coroutines, and `events()` is an async iterator. Close the stream explicitly if you `break` out of it early: Stream a session with asyncio ``` import asyncio import os from contextlib import aclosing from latentcode_sandbox_agents import AsyncLatentStack async def main() -> None: async with AsyncLatentStack(api_key=os.environ["LS_API_KEY"]) as client: sessions = client.agents.sessions session = await sessions.create( agent={"model": "anthropic/claude-sonnet-5.5", "instructions": "Answer briefly."}, input="Name three uses of a lighthouse.", ) try: # aclosing() closes the stream when you break out early. async with aclosing(sessions.events(session["id"])) as events: async for event in events: if event["type"] == "text.ended": print(event["data"]["text"]) if event["type"] in ("run.completed", "run.failed"): break finally: await sessions.delete(session["id"]) asyncio.run(main()) ``` ## client.agents.sessions Responses are plain `dict`s with the same fields as the TypeScript types. The package's `TypedDict`s (`Session`, `StreamFrame`, `Event`, …) give your editor the keys. All options are keyword-only. ### Lifecycle ``` create(*, agent, environment=None, input=None, metadata=None, idempotency_key=None, limits=None, files=None, outputs=None, end_after_run=None, webhook=None) -> Session ``` Starts a session. See Configuring agents for the settings. `environment["network"]` sets what the sandbox can reach; `limits` caps what the session may spend. `idempotency_key` makes the call safe to retry. `files`, `outputs` and `end_after_run` are on Outputs, and `webhook` on Webhooks. ``` get(session_id) -> Session ``` Reads a session, with `limits`, `stop_reason` and `usage`. ``` list(*, limit=None, after=None) -> SessionList ``` Newest first. Pass `next_after` as `after` for the next page. ``` delete(session_id) -> Session ``` Stops the session for good and deletes its disk. ``` pause(session_id) -> Session ``` Saves its state and releases the sandbox. ``` resume(session_id) -> Session ``` Continues a paused session in a new sandbox. Also brings back a stopped session while its disk is kept (`volume_kept_until`). ``` fork(session_id, *, input=None, metadata=None, limits=None, outputs=None, end_after_run=None, webhook=None, idempotency_key=None) -> Session ``` A new session from an idle one as it is now: its repositories, its changes and its conversation. See Fork a session. ``` update(session_id, *, limits) -> Session ``` Changes its spend limits. A session paused at a limit continues once the limit is raised; `None` removes one. ### Input ``` message(session_id, text, *, delivery=None, files=None) -> InputAccepted ``` `delivery`: `"steer"` (default) or `"queue"`. `files`: workspace paths of images (png, jpeg, gif or webp) to put in front of the model with the text. ``` approve(session_id, request_id, reply, message=None) -> InputAccepted ``` `reply`: `"once"`, `"always"` or `"reject"`. ``` cancel(session_id) -> InputAccepted ``` Interrupts the current run. ``` send(session_id, input) -> InputAccepted ``` Any input as a dict. ### Following ``` events(session_id, *, after=None, stop=None, retry_delay=None) -> Iterator[StreamFrame] ``` Live frames, reconnecting with the last seq when the connection drops. Ends when the session is `stopped` or `failed`, or when `stop` is set. | Argument | | | --- | --- | | after | Start after this seq. Default: from the beginning. | | stop | A `threading.Event` (`asyncio.Event` for the async client). It may take a few seconds to stop. | | retry_delay | Fixed seconds between reconnects. Default: 1, 2, 3 … per failed attempt; gives up after 5. | ``` wait(session_id, *, until=None, timeout=600.0, poll=2.0) -> Session ``` Polls until the status is in `until` (default `SETTLED`). Raises `LatentStackError(type="timeout")` after `timeout` seconds. Right after `create()` a session is briefly `idle` before its first message starts, so follow `events()` to know a task is done. ### Artifacts ``` artifacts(session_id) -> ArtifactList ``` One record per repository. ``` artifact(session_id, name="patch", *, repo=None) -> str ``` The unified diff. `repo` is required with several repositories. ### Files Paths are relative to the workspace, like `uploads/photo.png`. A path with a `.` or `..` segment, or a leading or trailing slash, raises `invalid_request` before anything is sent. See Files. ``` upload_file(session_id, path, data, *, content_type="application/octet-stream") -> FileInfo ``` Stores `data` at `path`: `bytes`, an open binary file, or a path to a file to read. A `str` is a path, not content. Missing folders are created, and an existing file is replaced. Returns the stored file's `path`, `size` and `sha256`. ``` download_file(session_id, path) -> bytes ``` The whole file. ``` list_files(session_id, *, prefix=None, limit=None) -> FileList ``` Files whose path starts with `prefix`, in path order, up to `limit` (1,000 at most). `.git` is left out. `truncated` is true when there were more. ``` delete_file(session_id, path) -> None ``` Removes the file. ## Errors Python ``` from latentcode_sandbox_agents import LatentStackError try: sessions.get("ags_missing") except LatentStackError as e: print(e.status, e.type, e.message) # 404 not_found No session 'ags_missing'. ``` `status` is 0 when no response arrived (`network_error`). See Errors for all types. ## Exports | Export | What | | --- | --- | | LatentStack · AsyncLatentStack | The clients. | | Sessions · AsyncSessions · Agents · AsyncAgents | The classes behind `client.agents.sessions`. | | Webhooks · Events · Schedules (and Async…) | The classes behind `client.agents.webhooks`, `client.agents.events` and `client.agents.schedules`. | | LatentStackError | The error: `status`, `type`, `message`. | | verify_webhook · WebhookVerificationError | Checks a webhook delivery and returns its event, or raises. See Verify the signature. | | SETTLED · DEFAULT_BASE_URL · __version__ | Constants. | | TypedDicts | Session, SessionList, SessionStatus, SessionStatusName, Agent, Rule, Effect, Environment, EnvironmentNone, EnvironmentRepos, RepoSpec, Network, Limits, LimitsView, Spent, SubagentSpent, Usage, StopReason, Event, StreamFrame, ApprovalRequested, PendingApproval, SessionInput, MessageInput, ApprovalInput, CancelInput, ApprovalReply, Delivery, InputAccepted, Artifact, ArtifactList, FileChange, FileInfo, FileList, InstanceContext, ApiError, Output, OutputList, InlineWebhook, WebhookEndpoint, WebhookEndpointList, WebhookDelivery, WebhookDeliveryList, WebhookAttempt, DeliveryStatus, WebhookEvent, EventList, EventSession, Schedule, ScheduleList, ScheduleRun, ScheduleRunList, ScheduleOutcome, StagedFile, Concurrency | Note Same behaviour, both languages The Python client behaves exactly like the TypeScript one: the same methods, errors and reconnecting event stream. Only the naming follows each language. ## Upgrading - Each new version has its own install URL; see Install above. Reinstall from the new URL. - `latentcode_sandbox_agents.__version__` tells you what you have. - `0.1.2` added `limits` and `environment["network"]` on `create()`, and `limits`, `usage` and `stop_reason` on the session. - `0.1.3` added `upload_file()`, `download_file()`, `list_files()`, `delete_file()` and the `files` argument on `message()`. - `0.1.4` added `client.agents.webhooks`, `client.agents.events` and `client.agents.schedules`; `outputs()`, `delete_output()` and `webhook_deliveries()` on sessions; the `files`, `outputs`, `end_after_run` and `webhook` arguments on `create()`; and `verify_webhook()` with `WebhookVerificationError`; and `update()` to raise a session's limits. A spend limit now pauses a session instead of stopping it, and `resume()` brings back a stopped one for 7 days. See Webhooks, Outputs and Schedules. Source: https://latentstack.dev/docs/agents/sdk-python --- # MCP server Use hosted agents from Claude Code, Codex, Cursor, VS Code or any other MCP client. Ask your assistant to hand a task to an agent, and it starts one, follows it, and brings back the result. This page is about reaching hosted agents from your own MCP client. To give an agent tools from MCP servers instead, see MCP servers in Configuring agents. Tip Setup is two steps Install and connect your client. That's all you need; everything after those two sections is there for when you want more. ## Install ``` npm i -g https://latentstack.dev/dl/latentcode-agents-mcp-0.1.0.tgz ``` This installs the `latentstack-agents-mcp` command. You need Node 20 or newer and an API key (`ls-…`) from your LatentStack account. ## Connect your client Run once in your terminal. Bash ``` claude mcp add latentstack-agents -e LATENTSTACK_API_KEY=ls-… -- latentstack-agents-mcp ``` Restart the client or reload its MCP servers, and the `latentstack-agents` tools appear. You're set up; the sections below are extras. ## Settings Set these next to `LATENTSTACK_API_KEY`, the same way: `-e NAME=value` for Claude Code, or more entries in `env` for the config files. In Claude Code, `--scope user` makes the server available in every project. | Setting | | | --- | --- | | LATENTSTACK_BASE_URL | Your LatentStack URL, if it isn't `https://latentstack.dev`. | | LATENTSTACK_DEFAULT_MODEL | The model agents use unless you name another. Without it, your assistant picks one from the models your plan allows. | ## What you can ask for Once connected, ask in plain words. For example: ``` Start an agent on acme/payments to fix the failing tests, and show me the diff when it's done. Fork that session and try it without the cache. Pause it; I'll come back to it tomorrow. Every weekday at 9:30 IST, run an agent on acme/payments that writes a standup from yesterday's commits. ``` Your assistant uses these tools on your behalf: | Tool | What it does | | --- | --- | | create_session | Starts an agent with a task, optionally on your GitHub repositories, with spend caps and settings of your choice. | | wait_for_session | Waits until the agent finishes or needs you, and reports what happened. | | reply_approval · answer_question | Answers the agent when it asks before doing something (see Approvals). | | send_message · cancel_run | Gives the agent more instructions, or stops what it is doing. | | get_patch · list_outputs | The changes the agent made, and the files it kept for you. | | list_files · read_file · write_file | Reads and writes files in the agent's workspace. | | fork_session | Starts a second agent from where this one is, to try another approach (Fork a session). | | update_limits | Raises or lowers spend caps; an agent paused at a cap carries on. | | get_session · list_sessions · get_events | Status, spend, and what the agent has been doing. | | pause_session · resume_session · delete_session | Pause, continue or end a session (Manage sessions). | | create_schedule · run_schedule | Runs an agent on a clock, or once right now (Schedules). | | list_schedules · get_schedule · update_schedule · list_schedule_runs · delete_schedule | Your schedules: when each runs next, how past runs went; pause, change or remove one. | | list_models | The models your plan allows. | ## Share one server with your team Run it once over HTTP and point everyone's client at it. Each person connects with their own key, so their sessions and spend stay their own. ``` latentstack-agents-mcp --transport http --port 8765 ``` Each person connects with ``` claude mcp add --transport http latentstack-agents http://your-host:8765/mcp \ --header "Authorization: Bearer ls-…" ``` ## Good to know Warning Permission rules cannot stop a push An agent on a repository can push to branches your GitHub access allows, even with a rule like `{ "action": "bash", "resource": "git push*", "effect": "ask" }`. If it should not push, say so in its instructions. Source: https://latentstack.dev/docs/agents/mcp --- # Errors Every failed call raises one error type with a stable name you can branch on. ## LatentStackError Both SDKs raise `LatentStackError` for every failure. It has a `type` to branch on, a `message` written for people, and the HTTP `status` (0 when no response arrived). Branch on `type`; messages may change. Catch and inspect an error ``` import { LatentStack, LatentStackError } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions try { await sessions.get("ags_does_not_exist") } catch (error) { if (!(error instanceof LatentStackError)) throw error console.log(error.status, error.type, error.message) // 404 not_found No session 'ags_does_not_exist'. } try { await sessions.create({ agent: { model: "no-such/model" }, input: "hi" }) } catch (error) { if (!(error instanceof LatentStackError)) throw error console.log(error.status, error.type) // 403 model_not_allowed } ``` ``` 404 not_found No session 'ags_does_not_exist'. 403 model_not_allowed ``` ## Error types | type | Meaning | What to do | | --- | --- | --- | | invalid_request | A setting or argument is wrong. The message names it. | Fix the call. | | invalid_api_key | The key is missing, invalid or expired, or it isn't an `ls-` API key. | Use a valid API key. | | model_not_allowed | Your tier doesn't include the model. | Choose one from `latentcode models`. | | no_tier_assigned | Your account has no access tier in this organization. | Ask an administrator. | | github_not_connected | A repository session needs a GitHub token. | Add one in Agent Settings. | | repo_not_accessible | Your GitHub token can't read a repository. The message names it. | Check the name, or grant the token access. | | not_found | The session doesn't exist or isn't yours, or the request, repository, patch or file doesn't exist. | Don't retry. | | conflict | Not possible in the session's current state (e.g. an approval, or a file call, to a paused session), or an idempotency key reused with different settings. | Check the status, then act. | | limit_reached | The session reached a spend limit. While it wraps up it takes no more messages (approvals and cancel still work); once paused at the cap it does not continue. | Raise the cap with update(), then send a message or resume. | | patch_too_large | The patch is over 15 MB. | Keep generated files out of the change. | | request_too_large | A create request is over 50 MB, usually from large files sent inline. | Create without input, upload the files once it is running, then send the message. | | file_too_large | An upload is over the 1 GiB cap. | Upload a smaller file. | | attachment_too_large · attachments_too_large | An image named in a message's `files` is over 5 MiB, or the images together are over 20 MiB. | Send fewer or smaller images, or name the path in the message. | | session_limit_reached | Your organization is at its cap of live sessions, where one is set. | Delete one, or wait for one to pause. | | endpoint_limit_reached | You have as many registered webhook endpoints as allowed in this organization. | Delete one first. | | endpoint_disabled | A test or retry was sent to a webhook endpoint that is turned off. | Turn it on with `enabled: true`. | | endpoint_backlogged | A webhook endpoint already has 1,000 deliveries waiting, so no test was queued. | Let them finish or fail first. | | rate_limited | More than 60 webhook tests and retries in a minute. | Wait a minute. | | runner_unavailable | No capacity to start a sandbox right now. | Retry after a short wait. | | github_unavailable | GitHub couldn't be reached to check access. | Retry shortly. | | container_error | The sandbox didn't accept an input or a file call. | Retry. | | network_error | The request never got an answer (DNS, TLS, connection). | Retry with backoff. | | timeout | `wait()` ran out of time. The session itself is unaffected. | Wait again, or check on it later. | ## Errors on the session Some problems happen after your call has returned: a sandbox fails to start, or disappears. These don't raise an error in your code. They show on the session's `error` field and on `session.status` items: - A new session whose sandbox can't start, or isn't ready within 240 seconds (`start_timeout`), becomes `failed`. Create another. - A paused session that can't resume goes back to `paused` with the error, and keeps your messages. Send another message to retry. - A session whose sandbox disappears becomes `paused`, and resumes with its files on the next message. - A file sent with `files` on create that can't be put in the workspace makes the session `failed`, with an error of type `files_error` that names the file. `run.failed` is different again: one run stopped on an error, such as the model provider failing. The session is fine; send another message. ## Retries - `runner_unavailable`, `github_unavailable`, `container_error` and `network_error` are safe to retry with backoff. Pass an idempotency key when retrying a create. - `conflict` while a session is pausing clears in a few seconds. - Everything else needs a change before trying again. - The event stream retries dropped connections on its own and resumes without gaps. Source: https://latentstack.dev/docs/agents/errors --- # Examples Complete programs to copy and adapt. Each reads your key from LS_API_KEY and cleans up after itself. ## Change a repository and get the patch The agent adds a file based on what it finds in the repository, and the program saves the result as a patch you can apply or turn into a pull request. The shell is denied, so it runs without anyone watching. ``` import { writeFile } from "node:fs/promises" import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Keep changes small.", // This task only needs the file tools. Denying the shell also means the agent never stops to ask. permissions: [{ action: "bash", effect: "deny" }], }, environment: { type: "repos", repos: ["acme/demo"] }, input: "Add a CONTRIBUTING.md that explains how to set up this project and run its tests, based on what you find in the repository.", }) try { for await (const event of sessions.events(session.id)) { if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } const patch = await sessions.artifact(session.id) await writeFile("contributing.patch", patch) // apply with: git apply contributing.patch console.log(patch) // a unified diff adding CONTRIBUTING.md } finally { await sessions.delete(session.id) } ``` ## Review code without changing it A read-only reviewer. It can read files and run git, and nothing else: every other tool is denied, so it never waits for approval and can't modify the repository. ``` import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "You review code. Read before you judge, name files and lines, and never modify files.", permissions: [ { action: "*", effect: "deny" }, // anything not allowed below is refused { action: "read", effect: "allow" }, { action: "glob", effect: "allow" }, { action: "grep", effect: "allow" }, { action: "list", effect: "allow" }, { action: "bash", resource: "git *", effect: "allow" }, { action: "bash", resource: "git push*", effect: "deny" }, // later rules win ], }, environment: { type: "repos", repos: ["acme/demo"] }, input: "Review the most recent commit (git show HEAD). List up to three concrete risks or improvements.", }) try { let review = "" for await (const event of sessions.events(session.id)) { if (event.type === "text.ended") review = String(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } console.log(review) const patch = await sessions.artifact(session.id) console.log(patch === "" ? "no files changed" : "files changed!") } finally { await sessions.delete(session.id) } ``` ## Make one change across several repositories One session, two repositories, one patch per repository. ``` import { writeFile } from "node:fs/promises" import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", instructions: "Keep changes minimal.", permissions: [{ action: "bash", effect: "deny" }], // file tools only }, environment: { type: "repos", repos: [ "acme/demo", // its default branch { repo: "acme/website", ref: "master" }, // a branch, tag or commit ], }, input: "In each repository, add a line at the end of the README: 'Maintained by the platform team.'", }) try { for await (const event of sessions.events(session.id)) { if (event.type === "run.completed" || event.type === "run.failed") break } const { data } = await sessions.artifacts(session.id) for (const change of data) { console.log(change.repo, (change.files ?? []).map((f) => `${f.status} ${f.file} +${f.additions} -${f.deletions}`)) const patch = await sessions.artifact(session.id, "patch", { repo: change.repo! }) await writeFile(`${change.repo!.split("/")[1]}.patch`, patch) } } finally { await sessions.delete(session.id) } ``` ## Chat in the terminal, approving commands An interactive chat. A `bash` rule set to `ask` makes the agent ask before every shell command, and you answer each one with `y`, `a` (always) or `n`. ``` // A chat with an agent in your terminal. You approve its shell commands as they come up. import * as readline from "node:readline/promises" import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const terminal = readline.createInterface({ input: process.stdin, output: process.stdout }) const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5", permissions: [{ action: "bash", effect: "ask" }] }, input: await terminal.question("task> "), }) try { for await (const event of sessions.events(session.id)) { if (event.type === "approval.requested" && !("seq" in event)) { const answer = await terminal.question(`run \`${(event.resources ?? []).join(" ")}\`? [y]es / [a]lways / [n]o `) const reply = answer === "a" ? "always" : answer === "y" ? "once" : "reject" await sessions.approve(session.id, event.request_id, reply) } if (event.type === "tool.called") console.log(` · ${event.data?.tool}`) if (event.type === "text.ended") console.log(`\n${event.data?.text}\n`) if (event.type === "run.completed" || event.type === "run.failed") { const next = await terminal.question("task> (empty to quit) ") if (!next) break await sessions.message(session.id, next) } } } finally { terminal.close() await sessions.delete(session.id) } ``` ``` task> Run `uname -s` in the shell and tell me the result. · bash run `uname -s`? [y]es / [a]lways / [n]o y The result of `uname -s` is: Linux task> (empty to quit) ``` ## A long-lived assistant One session per conversation, kept across runs of your program. It stores the session id and the last event number in a file. Each run sends a message and prints only the new reply. If the session paused in the meantime, the message wakes it with its files and conversation. ``` // A long-lived assistant: one session per conversation, kept across restarts of your program. // tsx assistant.ts "Start a notes.md with three ideas for a blog post." // tsx assistant.ts "Expand the second idea into an outline." (minutes or days later) import { existsSync, readFileSync, writeFileSync } from "node:fs" import { LatentStack } from "@latentcode/sandbox-agents" const client = new LatentStack({ apiKey: process.env.LS_API_KEY! }) const sessions = client.agents.sessions const STATE = "conversation.json" type Saved = { sessionId: string; position: number } const saved: Saved | undefined = existsSync(STATE) ? JSON.parse(readFileSync(STATE, "utf8")) : undefined const message = process.argv[2] ?? "Hello!" let sessionId: string let position = 0 if (saved) { // An idle session pauses after a while; a message wakes it with its files and history. ;({ sessionId, position } = saved) await sessions.message(sessionId, message) } else { const session = await sessions.create({ agent: { model: "anthropic/claude-sonnet-5.5" }, input: message }) sessionId = session.id } for await (const event of sessions.events(sessionId, { after: position })) { if (!("seq" in event)) continue position = event.seq if (event.type === "text.ended") console.log(event.data?.text) if (event.type === "run.completed" || event.type === "run.failed") break } writeFileSync(STATE, JSON.stringify({ sessionId, position } satisfies Saved)) ``` ## Python with asyncio `AsyncLatentStack` has the same methods as `LatentStack`, awaited. Wrap the event stream in `aclosing()` so the connection closes when you break out early. ``` import asyncio import os from contextlib import aclosing from latentcode_sandbox_agents import AsyncLatentStack async def main() -> None: async with AsyncLatentStack(api_key=os.environ["LS_API_KEY"]) as client: sessions = client.agents.sessions session = await sessions.create( agent={"model": "anthropic/claude-sonnet-5.5", "instructions": "Answer briefly."}, input="Name three uses of a lighthouse.", ) try: # aclosing() closes the stream when you break out early. async with aclosing(sessions.events(session["id"])) as events: async for event in events: if event["type"] == "text.ended": print(event["data"]["text"]) if event["type"] in ("run.completed", "run.failed"): break finally: await sessions.delete(session["id"]) asyncio.run(main()) ``` ## Run it in CI Any example that doesn't wait for a person runs as-is in a CI job. Store your key as a secret and upload what the agent produced: YAML ``` # .github/workflows/agent.yml name: agent on: workflow_dispatch jobs: contributing: runs-on: ubuntu-latest steps: - uses: actions/setup-python@v5 with: { python-version: "3.12" } - run: pip install https://latentstack.dev/dl/latentcode_sandbox_agents-0.1.4-py3-none-any.whl - run: python fix_repo.py env: LS_API_KEY: ${{ secrets.LS_API_KEY }} - uses: actions/upload-artifact@v4 with: { name: patch, path: contributing.patch } ``` Source: https://latentstack.dev/docs/agents/examples